Java Servlet

Posted Lynne~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Servlet相关的知识,希望对你有一定的参考价值。

1.配置tomcat到eclipse

2.编写html页面(ajax请求后台接口)》配置web.xml映射到对应的类》编写类实现逻辑处理

3.打war包,放在linux tomcat 的web apps目录下(注:依赖的包要放在截图的目录下)

3.1关于传war包到linux遇到的问题

1)提示没有权限传包,切换sudo su

2)查看server.xml http对应的端口,即为配置地址的端口

3)查看webapps下war包是否解压,不行就重启tomcat ./startup.sh

4.代码分享

核心发请求代码:

package util;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

/**
* 带参数的get请求
* @param url
* @param param
* @return String
*/
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
else
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

/**
* 不带参数的get请求
* @param url
* @return String
*/
public static String doGet(String url) {
return doGet(url, null);
}

/**
* 带参数的post请求
* @param url
* @param param
* @return String
*/
public static String doPost(String url, Map<String, ?> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
if(param.get(key)instanceof String[]){
paramList.add(new BasicNameValuePair(key, Arrays.toString((Object[]) param.get(key))));
}
else
paramList.add(new BasicNameValuePair(key, (String) param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
if(!(response.getStatusLine().getStatusCode() == 200)){
return null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

/**
* 带参数的posts请求
* @param url
* @param param
* @return String
*/
public static String doPosts(String url, Map<String, String[]> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, Arrays.toString(param.get(key))));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

/**
* 不带参数的post请求
* @param url
* @return String
*/
public static String doPost(String url) {
return doPost(url, null);
}

/**
* 传送json类型的post请求
* @param url
* @param json
* @return String
*/
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}

 

前端利用ajax请求:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>数据端触发初筛url</title>
</head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function Chushai(){
var partnerName = document.getElementById(\'partnerName\').value
var userid = document.getElementById(\'userid\').value
var name = document.getElementById(\'name\').value
$.ajax({
url:\'http://172.22.69.52:8080/FirstWebProject/Chushai?partnerName=\' + partnerName + \'&userid=\' + userid + \'&name=\' + name,
type:\'get\',
dataType:\'text\',
data:$("#myForm").serialize(),
success:function(result){
console.log(result);//打印服务端返回的数据(调试用)
$("#td1").text(result)
if (result.resultCode == 200) {
alert("SUCCESS");
}
;
},
error : function() {
alert("异常!");
}
});
};
</script>
<body>
<form id="myForm" onsubmit="returen false" action="##" method="get">
product code:<input type="text" name="partnerName" id="partnerName" align="left"><br>
userid:<input type="text" name="userid" id="userid" align="left"><br>
name:<input type="text" name="name" id="name" align="left"><br>
<input type="Button" value="触发初筛url" onclick="Chushai()">
</form>
<div id="td1"></div>
</body>
</html>

 

逻辑处理代码(servlet类):

package firstWebProject;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.CardNiuSimpleAES;
import util.HttpClientUtil;
import util.MD5;

/**
* Servlet implementation class Chuchai
*/
@WebServlet("/Chuchai")
public class Chushai extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Chushai() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String partnerName = request.getParameter("partnerName");
String userid = request.getParameter("userid");
String name = request.getParameter("name");
//解决请求中文乱码
name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
String userId = CardNiuSimpleAES.encrypt(userid, ""); 
String secret="";
String testUrl="XXXXXXX?"; //
String t=System.currentTimeMillis()+"";
String sign = MD5.GetMD5Code(secret+userId+t);
String Url = testUrl+"cn="+partnerName+"&userid="+userid+"&name="+name+"&t="+t+"&sign="+sign;
response.setContentType("text/html;charset=utf-8");
String s = HttpClientUtil.doGet(Url);
response.getWriter().write(s);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

 

 

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FirstWebProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ServletDemo</servlet-name>
<servlet-class>firstWebProject.ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo</servlet-name>
<url-pattern>/ServletDemo</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Chushai</servlet-name>
<servlet-class>firstWebProject.Chushai</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Chushai</servlet-name>
<url-pattern>/Chushai</url-pattern>
</servlet-mapping>
</web-app>

 

以上是关于Java Servlet的主要内容,如果未能解决你的问题,请参考以下文章

Servlet学习1

ServletServlet 详解(使用+原理)

ServletServlet 详解(使用+原理)

ServletServlet容器等内容讲解

Servlet学习笔记

ServletServlet学习之基础篇