[Java Web] 过滤器
Posted arseneyao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java Web] 过滤器相关的知识,希望对你有一定的参考价值。
一、简述
过滤器是服务端与客户端的请求与响应的中间层组件,主要用户对浏览器的请求进行过滤处理后再转给下一个资源。
客户端的请求在交给Servlet处理之前要经过FilterChain,服务端返回的响应也要经过FilterChain。FilterChain包含了多个Filter。
二、使用
FilterConfig是过滤器的配置对象,主要作用是获取过滤器中的配置信息。
//MyFilter.java package filter; import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; public class MyFilter implements Filter { private FilterConfig config; private String addr; @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { String remote = servletRequest.getRemoteAddr(); servletResponse.setCharacterEncoding("GB2312"); PrintWriter out = servletResponse.getWriter(); if (remote.equals(addr)) { out.println("request rejected: " + remote); } else { out.println("request accepted: " + remote); filterChain.doFilter(servletRequest, servletResponse); } } @Override public void init(FilterConfig filterConfig) { config = filterConfig; addr = config.getInitParameter("addr"); } } //web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app> <filter> <filter-name>MyFilter</filter-name> <filter-class>filter.MyFilter</filter-class> <init-param> <param-name>addr</param-name> <param-value>127.0.0.1</param-value> </init-param> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/*</url-pattern> <!-- 过滤所有请求 --> </filter-mapping> </web-app>
使用过滤器转换字符编码。
//MyFilter.java package filter; import javax.servlet.*; import java.io.IOException; public class MyFilter implements Filter { private boolean enable; private String encoding; @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (enable) { servletRequest.setCharacterEncoding(encoding); servletResponse.setCharacterEncoding(encoding); } filterChain.doFilter(servletRequest, servletResponse); } @Override public void init(FilterConfig filterConfig) { enable = Boolean.valueOf(filterConfig.getInitParameter("enable")); encoding = filterConfig.getInitParameter("encoding"); } } //web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app> <filter> <filter-name>MyFilter</filter-name> <filter-class>filter.MyFilter</filter-class> <init-param> <param-name>enable</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>encoding</param-name> <param-value>GB2312</param-value> </init-param> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/*</url-pattern> <!-- 过滤所有请求 --> </filter-mapping> </web-app>
以上是关于[Java Web] 过滤器的主要内容,如果未能解决你的问题,请参考以下文章
[原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等(代码片段