需要引入struts2的struts2-json-plugin-2.5.10.1.jar包
action如下:
package com.action;
import org.apache.struts2.json.annotations.JSON;
import com.bean.User;
import com.opensymphony.xwork2.ActionSupport;
public class JsonAction extends ActionSupport {
private User user;
/*
* 使用注解方式返回json数据
*/
@JSON()
public User getInputStream() {
return user;
}
public User getUser() {
user = new User();
user.setUsername("半仙");
user.setPassword("123456");
return user;
}
public void setUser(User user) {
this.user = user;
}
}
struts.xml配置如下:
在struts.xml中需要引入struts-plugin.xml 文件,
<include file="struts-plugin.xml"></include>
<!--继承默认的json-default -->
<package name="user1" extends="json-default">
<action name="jsonAction" class="com.action.JsonAction">
<!--结果类型为json -->
<result type="json">
<param name="contentType">text/html</param>
</result>
</action>
</package>
struts-plugin.xml文件在struts2的struts2-json-plugin-2.5.10.1.jar这个包下就可以找到
该文件是struts2默认配置好的,拿过来直接用就可以
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="json-default" extends="struts-default">
<result-types>
<result-type name="json" class="org.apache.struts2.json.JSONResult"/>
<result-type name="jsonActionRedirect" class="org.apache.struts2.json.JSONActionRedirectResult"/>
</result-types>
<interceptors>
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
<interceptor name="jsonValidation" class="org.apache.struts2.json.JSONValidationInterceptor"/>
<!-- Sample JSON validation stack -->
<interceptor-stack name="jsonValidationWorkflowStack">
<interceptor-ref name="basicStack"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel</param>
</interceptor-ref>
<interceptor-ref name="jsonValidation"/>
<interceptor-ref name="workflow"/>
</interceptor-stack>
</interceptors>
</package>
</struts>
jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'json.jsp' starting page</title>
</head>
<body>
<form id="jsonAction" >
<input type="text" name="name"/>
<input type="button" value="提交" id="button"/>
</form>
</body>
<script>
var jsonAction = document.getElementById("jsonAction");
var button = document.getElementById("button");
button.οnclick= function(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data){
if(xhr.readyState==4 && xhr.status==200){
var result = xhr.responseText;
var json = JSON.parse(result);
console.log(json.user);
}
}
xhr.open("post", "jsonAction.action");
xhr.send();
}
</script>
</html>