编写一个过滤器MyFilter实现以下功能: 1)按照utf-8字符集处理请求和响应中字符; 2)实现跨域访问
时间: 2024-11-27 20:17:58 浏览: 3
过滤器笔记整理
编写一个名为MyFilter的过滤器,用于处理UTF-8字符并支持跨域访问,可以基于Spring MVC框架来做,因为Spring MVC的Filter机制允许自定义请求处理流程。以下是一个简单的例子,假设你已经在项目中配置了Spring WebMVC和Spring Security:
```java
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 设置UTF-8字符编码
HttpServletRequest httpRequest = (HttpServletRequest) request;
httpRequest.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json; charset=UTF-8");
// 跨域访问设置
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有来源
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
// 如果请求是OPTIONS预检请求,则直接返回
if ("OPTIONS".equals(request.getMethod())) {
httpResponse.setStatus(HttpServletResponse.SC_OK);
return;
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}
```
在这个例子中,`doFilter`方法首先设置了请求和响应的UTF-8字符编码,然后添加了必要的HTTP头信息来允许跨域访问。当接收到OPTIONS请求时,这是浏览器在实际发送请求前发出的检查请求,我们简单地返回状态码200以确认支持。
阅读全文