How to return json in Struts2

To return json in Struts2, you need to define the variable in the Action and write a get method.
1. The following is the code in Action

public class LoginJsonAction extends ActionSupport implements ModelDriven<User> {
    
    

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private User user;
	
	//用于返回消息
	private String message;
		

	@Override
	public User getModel() {
    
    
		if (user == null) {
    
    
			user = new User();
		}
		return user;
	}

	// 登录方法
	public String login() {
    
    
		if (user.getUserName().equals(user.getPassword())) {
    
    			
			return SUCCESS;
		}else {
    
    
			message="用户名和密码不匹配";
			return ERROR;
		}
	}
	
	//========getter方法==========
	public User getUser() {
    
    
		return user;
	}

	public String getMessage() {
    
    
		return message;
	}
}

2. There are two ways to configure the returned json format in struts.mxl
(1) The first is to inherit json-default in the package, and specify the return type as json in the result, sample code:

<!-- 返回json的第一种写法 -->
<package name="return-json" namespace="/json" extends="json-default">
	<action name="loginJsonAction" class="com.gx.web.LoginJsonAction">
		<result name="success" type="json">
			<param name="root">user</param>
		</result>
		<result name="error" type="json">
			<param name="root">message</param>
		</result>
	</action>
</package>

(2) The second type is to define result-type in the package, sample code:

<!-- 返回json的第二种写法 -->
<package name="return-json" namespace="/json" extends="struts-default">
	<result-types>
		<result-type name="json" class="org.apache.struts2.json.JSONResult">
		
		</result-type>
	</result-types>
	<action name="loginJsonAction" class="com.gx.web.LoginJsonAction">
		<result name="success" type="json">
			<param name="root">user</param>
		</result>
		<result name="error" type="json">
			<param name="root">message</param>
		</result>
	</action>
</package>

3.jsp page code:

<script type="text/javascript">
   	function login(){
    
    
   		var userName=$("#userName").val();
   		var password=$("#password").val();
   		
   		$.get("${ctx}/json/loginJsonAction!login.action",{
    
    userName:userName,
   			password:password},function(data){
    
    
   			console.log(data);
   		},"json");
   	}
</script>

Guess you like

Origin blog.csdn.net/weixin_44547592/article/details/106412604