CSDN的ASK频道,看到关于struts2返回json数据的问题,整理了下struts2的简单demo,完成JSON数据的展示。
public class ValidateAction extends ActionSupport { private static final long serialVersionUID = 1L; private String username; public Map<String, Object> result = new HashMap<String, Object>(); public Map<String, Object> getResult() { return result; } public String execute() throws Exception { if ("zhangsan".equals(username)) { result.put("message", "success结果"); return Action.SUCCESS; }else { System.out.println("error结果"); result.put("message", "error结果"); return Action.ERROR; } } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
<?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="default" extends="json-default"> <action name="validate" class="ValidateAction"> <result type="json" /> <result name="error" type="json"></result> </action> </package> </struts>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Welcome to BoadVedio</title> <script type='text/javascript' src="<%=basePath%>resource/js/jquery-1.8.3.js"></script> <script type="text/javascript"> var basePath = '<%=basePath%>'; function validate(){ var username = document.getElementById("username").value; $.ajax({ url:basePath+"validate.action", type:"post", dataType:"json", data:{username:username}, success:function(data){ var message = data.result.message; $('#message').html(message); }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert("error when insert."); } }); } </script> </head> <body> <input type="text" name="username" id="username"/> <input type="button" value="提交" onclick="validate();"/> <div id="message"></div> </body> </html>测试基本功能没有问题。只是对于Action的返回值是SUCCESS还是ERROR,对页面是有影响的。上述配置,action配置中的success和error类型都是JSON,这样不管Action走入的是return SUCCESS还是ERROR分支,都会把成员变量result对象转化成JSON返回给页面的,ajax请求都是走入success分支中的。但是如果把error类型配置成一个jsp,那么,此时ajax的请求返回时是进入了error分支了
<struts> <package name="default" extends="json-default"> <action name="validate" class="ValidateAction"> <result type="json" /> <result name="error" >/error.jsp</result> </action> </package> </struts>而且浏览器并没有自动跳转到error.jsp页面去。那么问题来了:为什么配置error为error.jsp的时候,ajax请求走入了error分支呢?这个应该是ajax请求的dataType类型设置成了json,如果此时Action返回了error.jsp,那么ajax会视为异常。
原文地址:http://blog.csdn.net/wojiushiwo945you/article/details/45247391