1. 程式人生 > >Java Servlet

Java Servlet

tco def 請求 on() file sch sys web.xml配置 lips

1.配置tomcat到eclipse

2.編寫html頁面(ajax請求後臺接口)》配置web.xml映射到對應的類》編寫類實現邏輯處理

3.打war包,放在linux tomcat 的web apps目錄下(註:依賴的包要放在截圖的目錄下)

技術分享圖片

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, "&*($eIa61M$(&^%M"); //&*($HJDGH4867%&T
String secret="cardniu$#^2015";
String testUrl="http://kn.feidee.net/loanmanage/loan/insidepartner/user_check_inside.do?"; //
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