jQuery.Post到Struts2的action處理,並返回json物件到前端
阿新 • • 發佈:2019-02-01
之前雖然一直在用jQuery.post函式,將前端頁面的請求傳送到struts中的action處理,但是用的是公司寫好的一套東西,基本都是複製貼上,反而對基本的post功能沒有深入瞭解。下面簡單配置說明action中接收處理post的請求。
用的是struts2,web.xml配置如下
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
struts.xml中配置了一個action,配置如下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="com.test.action"> <action name="logon" class="com.test.action.LogonAction"> </action> </package> </struts>
index.jsp傳送post請求,指定返回資料格式為json。
post的URL寫了兩種型別:一種是直接傳送到jsp中處理,另外一種是傳送到action中處理
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type ="text/javascript" src = "zipedJquery.js"></script><!-- jQuery-min.js --> <script type ="text/javascript"> var jq = jQuery.noConflict(); jq(document).ready(function(){ jq("#btn").click(function(){ //post到jsp中處理 var username = jq("#username").val(); var password = jq("#password").val(); jq.post("MyJsp.jsp", { "username":username, "password":password }, function(data,status){ alert("appTime: " + data["appTime"] ); }, "json" ); }); jq("#btn1").click(function(){ //post到action中處理 var username = jq("#username").val(); var password = jq("#password").val(); jq.post("logon", { "method":"post" //傳遞引數 }, function(data,status){ alert(data); var msg ="returnCode: " + data["returnCode"] + "&returnMsg:" + data["returnMsg"]+ "&appTime:"+ data["appTime"]; alert(msg); }, "json" ); }); }); </script> </head> <body> This is my JSP page. <br> <form action="logon" method="post" > 使用者名稱:<input type ="text" name ="username" id ="username" value="" /><br/> 密 碼:<input type ="password" name ="password" id ="password" value="" /><br/> <input type= "submit" value="提交" /> </form> <br/> <button id= "btn" title = "post to MyJsp">MyJsp</button> <button id= "btn1" title = "post to PostAction">PostAction</button> <br/> </body> </html>
MyJsp.jsp中處理post請求,用request.getParameter()獲取引數,再用response將組織好的json格式的字串返回。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="java.text.SimpleDateFormat"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'MyJsp.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
This is my JSP page.
<br>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String json = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if ("Duck".equals(username)) {
json = "{\"appTime\":\"" + sdf.format(new java.util.Date())+ "\"}";
} else {
json = "{\"appTime\":\"\"}";
}
response.getWriter().write(json);
response.getWriter().flush();
response.getWriter().close();
%>
</body>
</html>
PostAction處理post請求,以前用的是struts1.2,action中的execute方法中的有request和response引數,struts2裡面需要自己去獲取
package com.test.action;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LogonAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println(getUsername());
System.out.println(getPassword());
//獲取response和request物件
HttpServletResponse response = (HttpServletResponse) ActionContext
.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
System.out.println(request.getParameter("method"));
String json = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if ("Duck".equals(username)) {
json = "{\"returnCode\":\"1\",\"returnMsg\":\"Success\",\"appTime\":\"" +
sdf.format(new java.util.Date()) + "\"}";
} else {
json = "{\"returnCode\":\"0\",\"returnMsg\":\"Failed\",\"appTime\":\"" +
sdf.format(new java.util.Date()) + "\"}";
}
response.getWriter().write(json); //返回json
response.getWriter().flush();
response.getWriter().close();
return null;
}
}