web.xml的配置
<filter> <filter-name>FilterTest01</filter-name> <filter-class>com.baowei.fiiter.FilterTest01</filter-class> <init-param> <param-name>charset</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>FilterTest01</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Filter的实现
public class FilterTest01 implements Filter { private FilterConfig config = null; private String defaultCharSet = "utf-8"; @Override public void init(FilterConfig filterConfig) throws ServletException { config = filterConfig; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String charset = config.getInitParameter("charset"); if (charset == null) { charset = defaultCharSet; }
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
req.setCharacterEncoding(charset);
resp.setCharacterEncoding(charset);
resp.setContentType("text/html;charset=" + charset);
} @Override public void destroy() { } }
时间: 2024-10-30 15:31:39