jQuery.Post到Struts2的action处理,并返回json对象到前端

之前虽然一直在用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;

	}
}








  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值