SpringMVC has been used for a long time and is not very busy recently. So I learned about Struts2. in the past, many times I used JQuery request Json in projects.
Of course, SpringMVC provides several methods to obtain Json, such:
JSONArray json = JSONArray.fromObject(childNode.toArray());String s = json.toString();response.setContentType("text/json; charset=UTF-8");response.setCharacterEncoding("UTF-8");try {response.getWriter().write(s);} catch (IOException e) {e.printStackTrace();}
I use Gson in most cases, and the above example uses json-lib-2.3-jdk15.jar.
Below I will use struts2 + jquery + json integration to get JSON and require lib to include struts2-json-plugin-2.3.7.jar and json-lib-2.3-jdk15.jar.
UserAction:
public String jsonUser() throws Exception{UserService uService=new UserService();List<User> list=uService.findByAll();Gson gson=new Gson();result=gson.toJson(list);for (User user : list) {System.out.println(gson.toJson(list)+"====================="+user.getId()+"--"+user.getName());}return SUCCESS;}
The result is an attribute variable of UserAction:
// Return the result to the Client private String result; public String getResult () {return result;} public void setResult (String result) {this. result = result ;}
Struts. xml:
<Package name = "jsonUser" extends = "json-default"> <! -- Get JSON of all users --> <action name = "jsonuser" class = "com. mzsx. user. action. userAction "method =" jsonUser "> <result type =" json "> <param name =" root "> result </param> </result> </action> </package>
The most noteworthy is the extends=
"Json-default", <resulttype ="json"
> And <paramname ="root"
>result</param>。
For ease, my js on the front-end page is:
$ (Function () {alert ("START"); $. getJSON ('HTTP: // localhost: 8080/hibernate/jsonuser. action ', function (data) {alert (data );});});
Running result:
650) this.width=650;" title="111.png" src="http://www.bkjia.com/uploads/allimg/131228/14160014R-0.png" alt="110248689.png" />
This article from the "Dream think Xi" blog, please be sure to keep this source http://qiangmzsx.blog.51cto.com/2052549/1305058