Struts returns json and strutsactionjson through action
In fact, it is quite simple for struts2 to return json through action, but it is always forgotten, so it is simply written on the blog. Okay. Start.
First, introduce necessary jar packages:
Struts2-json-plugin-2.3.24.jar
Then, let's write a simple action.
package com.mz.action;import com.mz.entity.User;import com.opensymphony.xwork2.ActionSupport;public class JsonAction extends ActionSupport{ private User user; public String execute() { user = new User(); user.setId(123); user.setUsername("Irasel"); return SUCCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
Is a very simple action, assign values to the user object, return the value, and return success.
The User class has two attributes, one id and one username, and the corresponding get and set methods.
Configuration files:
<! -- Configure an action that returns a json string --> <package name = "resultJson" namespace = "/" extends = "json-default"> <action name = "resultJson" class =" com. mz. action. jsonAction "> <result name =" success "type =" json "> <! -- Root is part of the ognl expression and cannot be replaced --> <param name = "root"> user </param> </result> </action> </package>
Here, root is an attribute of the ognl expression,Cannot be changed! Cannot be changed! Cannot be changed!(Three important events)
Start tomcat and access: http: // localhost: 8080/spring-struts/resultJson (the path here may be different)
:
In this case, the json object is successfully returned at the front end. OK!