编写filter过滤器有两种方法,一种是使用注解配置,另一种是使用web.xml配置,此处使用web.xml配置来实现过滤器
(1)使用web.xml配置过程
<filter> <filter-name>setCharacterFilter</filter-name> <filter-class>com.qst.setCharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>setCharacterFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
(2)过滤器主体demo
public class setCharacterEncodingFilter implements Filter{ @Override public void destroy() { // TODO Auto-generated method stub //Filter.super.destroy(); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub //Filter.super.init(filterConfig); } }
通过过滤器,我们可以实现统一的对请求和响应中文乱码问题的配置,不用在每次请求和响应的demo中都去设置utf-8的编码
原文地址:https://www.cnblogs.com/yinghuapiaoluo/p/12683747.html
时间: 2024-10-27 02:10:23