In fact, it is quite simple to return to json through action, but it always needs to be forgotten, so I simply wrote it on the blog. OK, start.
First, introduce the necessary jar package:
struts2-json-plugin-2.3.24.jar
Then we 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;}}It is a very simple action, assigning values to the user object, passing them back and returning success.
There are two properties in the User class, one id and one username, and the corresponding get and set methods.
Mainly configuration configuration files:
<!-- Configure an action that returns a json string --><package name="resultJson" namespace="/" extends="json-default"><action name="resultJson"><result name="success" type="json"><!--root is part of the ognl expression that cannot be replaced --><param name="root">user</param></result></action></package>
The root here is an attribute of the ognl expression and cannot be changed! Can't change! Can't change! (Say important things three times)
Start tomcat and access: http://localhost:8080/spring-struts/resultJson (the path here may be different)
As shown in the figure:
In this way, even if you successfully return the json object in the foreground, ok!