CSDN ask channel, see About STRUTS2 return JSON data problem, organized the next struts2 simple demo, complete the presentation of JSON data.
Action definition
public class Validateaction extends Actionsupport {private static final long Serialversionuid = 1l;private String username ;p ublic map<string, object> result = new hashmap<string, object> ();p ublic map<string, object> GetResult () {return result;} Public String Execute () throws Exception {if ("Zhangsan". Equals (username)) {result.put ("message", "success result"); return action.success;} else {System.out.println ("error result"), Result.put ("message", "error result"); return action.error;}} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;}}
Configure 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=" Default "extends=" Json-default "> <action name=" Validate "class=" Validateaction "> <result type=" json "/> <result name=" error "type=" JSON "></result ></action> </package></struts>
Page Access JSON
<%@ 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 + "/";%>&L t;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">There is no problem testing the basic functionality. Only the return value of the action is success or error, which affects the page. In the above configuration, the success and error types in the action configuration are JSON, so that the member variable result object is converted to JSON back to the page, regardless of whether the action goes to the return success or the error branch. Ajax requests are all going into the success branch. But if the error type is configured as a JSP, then the AJAX request returns to the error branch.<struts> <package name= "Default" extends= "Json-default" > <action name= "Validate" class= " Validateaction "> <result type=" json "/> <result name=" error ">/error.jsp</result></action > </package></struts>
and the browser does not automatically jump to the error.jsp page. So the question is: Why does the AJAX request go into the error branch when the configuration error is error.jsp? The datatype type that should be the AJAX request is set to JSON, and if the action returns ERROR.JSP, then Ajax is considered an exception.
JAVAEE-STUTS2 return JSON data simple implementation