Java Filter 过滤器 Servlet 原始写法
原创
©著作权归作者所有:来自51CTO博客作者wx61cd54ea3a202的原创作品,请联系作者获取转载授权,否则将追究法律责任
过滤器,拦截中文乱码
package com.chenxb;
import javax.servlet.*;
import java.io.IOException;
public class Filter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化。。。");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse.setCharacterEncoding("utf-8");
System.out.println("执行前。。。");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("执行后。。。");
}
@Override
public void destroy() {
System.out.println("销毁。。。");
}
}
调取测试
package com.chenxb;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class FilterTest extends ServletContextSet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("通过过滤器修复中文乱码");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
web.xml配置
<!--过滤器mapping-->
<filter>
<filter-name>Filter</filter-name>
<filter-class>com.chenxb.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter</filter-name>
<!--/filter/的所有请求都被过滤-->
<url-pattern>/Filter