Servlet过滤器

过滤器的概念:
过滤器也是一种特殊的servlet,需要在配置文件中进行配置或使用注解进行配置,过滤器可以指定的请求拦截,并对被拦截的请求进行相关的验证或处理,执行完成后将被拦截的请求放行;

要实现过滤器需要使用接口“javax.servlet.Filter”

修改xml文件:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
//设置过滤器处理路径
<url-pattern>/*</url-pattern>
</filter-mapping>

实现程序:
package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyFilter implements Filter {

@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
//向下转型
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
//设置响应和请求的字符类型
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
// 放行请求
chain.doFilter(req, resp);
}

@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

}

 

上一篇:第十六周学习进度总结


下一篇:Dubbo编写filter