Struts2过滤器中获取JSON数据的完整指南
在Java Web开发中,Struts2框架作为经典的MVC框架,经常需要处理前端传递的JSON数据,本文将详细介绍在Struts2过滤器中如何获取JSON数据,包括配置、编码处理以及实际代码示例。
Struts2过滤器获取JSON的基本原理
Struts2通过Interceptor拦截器机制处理请求,当需要获取JSON数据时,主要依赖于json-default包中提供的拦截器,过滤器(Filter)在Struts2中通常指StrutsPrepareAndExecuteFilter,它作为请求的入口点,负责将请求转发给相应的Action处理。
配置Struts2以支持JSON
需要在struts.xml配置文件中启用JSON支持:
<package name="default" extends="json-default">
<action name="jsonExample" class="com.example.JsonAction">
<result type="json"/>
</action>
</package>
关键点:
- 继承
json-default包而非默认的struts-default - 为Action配置
json类型的Result
在过滤器中获取JSON数据的方法
通过HttpServletRequest获取原始JSON数据
在自定义过滤器中,可以通过HttpServletRequest的输入流获取原始JSON数据:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if ("application/json".equals(httpRequest.getContentType())) {
// 读取JSON数据
StringBuilder sb = new StringBuilder();
BufferedReader reader = httpRequest.getReader();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String jsonBody = sb.toString();
// 可以将JSON数据存储到request属性中供后续使用
httpRequest.setAttribute("jsonBody", jsonBody);
}
chain.doFilter(request, response);
}
通过Struts2拦截器获取JSON数据
Struts2提供了json拦截器,可以自动将JSON数据解析为Action属性:
public class JsonAction extends ActionSupport {
private Map<String, Object> jsonData;
@Override
public String execute() throws Exception {
// jsonData已经被自动填充
System.out.println("Received JSON: " + jsonData);
return SUCCESS;
}
// getter和setter
public Map<String, Object> getJsonData() {
return jsonData;
}
public void setJsonData(Map<String, Object> jsonData) {
this.jsonData = jsonData;
}
}
使用@Body注解直接映射JSON(Struts2.5+)
对于较新版本的Struts2,可以使用注解方式直接映射JSON数据:
public class JsonAction extends ActionSupport {
@Body
private MyModel model;
@Override
public String execute() throws Exception {
System.out.println("Model from JSON: " + model);
return SUCCESS;
}
// getter和setter
public MyModel getModel() {
return model;
}
public void setModel(MyModel model) {
this.model = model;
}
}
处理编码问题
获取JSON数据时,编码问题经常出现,确保正确处理编码:
// 在过滤器中设置编码
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");
完整示例
前端发送JSON请求
$.ajax({
url: "/yourapp/jsonExample",
type: "POST",
contentType: "application/json",
data: JSON.stringify({name: "John", age: 30}),
success: function(response) {
console.log(response);
}
});
Struts2 Action处理
public class JsonAction extends ActionSupport {
private String name;
private int age;
@Override
public String execute() throws Exception {
// 处理接收到的数据
System.out.println("Name: " + name + ", Age: " + age);
return SUCCESS;
}
// getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
自定义过滤器示例
@WebFilter("/*")
public class JsonFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 设置编码
httpRequest.setCharacterEncoding("UTF-8");
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json");
// 检查是否为JSON请求
if (isJsonRequest(httpRequest)) {
String jsonBody = getJsonBody(httpRequest);
httpRequest.setAttribute("jsonBody", jsonBody);
}
chain.doFilter(request, response);
}
private boolean isJsonRequest(HttpServletRequest request) {
String contentType = request.getContentType();
return contentType != null && contentType.contains("application/json");
}
private String getJsonBody(HttpServletRequest request) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = request.getReader()) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
return sb.toString();
}
// 其他Filter方法...
}
注意事项
- 性能考虑:直接读取请求体会影响性能,对于大JSON数据应谨慎处理
- 安全性:对JSON数据进行验证和清理,防止注入攻击
- 版本兼容性:不同Struts2版本对JSON的支持可能有所不同
- 异常处理:添加适当的异常处理机制,如JSON解析错误
在Struts2过滤器中获取JSON数据可以通过多种方式实现,选择哪种方法取决于具体需求和Struts2版本,对于简单的JSON数据,可以直接通过HttpServletRequest获取;对于复杂的对象映射,建议使用Struts2内置的JSON拦截器或注解功能,正确处理编码和安全性问题是确保JSON数据正常处理的关键。
通过合理配置和使用Struts2的JSON处理机制,可以高效地实现前后端数据交互,提升Web应用的灵活性和用户体验。



还没有评论,来说两句吧...