public class BaseAction extends ActionSupport { private static final long serialVersionUID = 4260238422873356334L; /** * 返回json数据 * @param object * @return */ public String jsonOut(Object object){ ObjectMapper objectMapper=new ObjectMapper(); try { String jsonString=objectMapper.writeValueAsString(object); HttpServletResponse response=ServletActionContext.getResponse(); response.setContentType("text/json;charset=UTF8"); response.getWriter().print(jsonString); } catch (Exception e) { e.printStackTrace(); } return null; } }
public class TestAction extends BaseAction { private String userName; /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } @SuppressWarnings({ "unchecked", "rawtypes" }) public String login() { Map jsonMap = new HashMap(); if ("admin".equals(userName)) { jsonMap.put("msg", "登陆成功!!!"); } else { jsonMap.put("msg", "登陆失败!!!"); } return jsonOut(jsonMap); } }
<?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="struts" extends="struts-default" namespace="/"> <action name="testAction" class="com.acca.action.TestAction" method="login"> </action> </package> </struts>
<%@ page language="java" contentType="text/html; charset=utf-8"%> <!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;"> <title>Insert title here</title> <script type="text/javascript" src="jquery/jquery-1.7.2.min.js"></script> <script type="text/javascript"> function doSubmit() { $.ajax({ type: "post", data:{"userName":"admin"}, url: "testAction", dataType: "json", cache: false, success: function(data) { $.each(data, function(key, val) { if (key == "msg" && val != ''){ $("#mes").html(val); return false; } }); } }); } </script> </head> <body> <div id="mes"></div> <input type="button" value="提交" onclick="doSubmit()"> </body> </html>