1、什么是Filter?
Filter是服务器端的组件,用来过滤web请求。可以拦截所有访问web资源的请求或响应操作。当发生一个web请求时,web容器会先检查请求的URL是否设置了Filter,如果设置了,则执行该Filter的doFilter方法。所有Filter都实现了javax.servlet.Filter接口,doFilter是定义在该接口中的最重要的方法。
最常见的使用过滤器的例子有:登录访问页面验证,错误日志记录,编码转换等。
2、怎么创建一个过滤器?(以登录访问页面验证为例)
1)创建一个类实现Filter接口
2)重写接口中方法 doFilter方法是真正过滤的
package com.hyg.core.filter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginFilter implements Filter {
@Override
public void destroy() {
}
//不过滤的页面设置
String passUrl = "";
private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
//不过滤的页面设置
String[] strArray = passUrl.split(";");
for (String str : strArray) {
if (StringUtils.isBlank(str))
continue;
str = str.replace("\n", "").trim();
if (httpRequest.getRequestURL().indexOf(str) >= 0) {
chain.doFilter(request, response);
return;
}
}
String url = httpRequest.getRequestURL().substring(httpRequest.getContextPath().length());
logger.info("获取到url请求{}",url);
HttpSession session = httpRequest.getSession();
if (session.getAttribute("userName") != null) {
logger.info("获取到session中的adminCode,放行");
chain.doFilter(request, response);
} else {
//默认ajax是不支持重定向的,因为ajax本身就是局部刷新,不重新加载页面的。过滤ajax重定向的方法:
logger.info("未获取到session中的adminCode,跳转登录页面");
if (httpRequest.getHeader("x-requested-with") != null && "XMLHttpRequest".equals(httpRequest.getHeader("x-requested-with"))){
httpResponse.setHeader("sessionstatus","timeout");
httpResponse.setStatus(403);
httpResponse.addHeader("loginPath",httpRequest.getScheme()+"://" + httpRequest.getServerName() + ":" + httpRequest.getServerPort() + "/production");
chain.doFilter(httpRequest,httpResponse);
logger.info("获取到ajax请求,跳转登录页面");
return;
}
httpResponse.sendRedirect(httpRequest.getContextPath() + "/jsp/talent/login.jsp");
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
passUrl = arg0.getInitParameter("passUrl");
}
}
3)在web.xml文件中配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<listener>
<listener-class>
com.hyg.core.listener.TomcatListener
</listener-class>
</listener>
<listener>
<listener-class>net.sf.ehcache.constructs.web.ShutdownListener</listener-class>
</listener>
<filter>
<filter-name>DomainFilter</filter-name>
<filter-class>com.hyg.core.filter.DomainFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>DomainFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.hyg.core.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 安全过滤器 -->
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>
com.hyg.core.filter.LoginFilter
</filter-class>
<init-param>
<param-name>passUrl</param-name>
<param-value>index.jsp;/login.jsp;/web/talent/login;/addMyjob.jsp;/web/talent/myPdf/uploader;
/web/talent/vip/alipayCallbackSynch;/web/talent/vip/alipayCallbackAsync;/register.jsp;/web/talent/register;
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
<url-pattern>/web/talent/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>com.hyg.core.web.ActionServlet</servlet-class>
<init-param>
<param-name>packages</param-name>
<param-value>
com.hyg.talent.action,
com.hyg.tracking.action,
com.hyg.talent.action.vip
</param-value>
</init-param>
<init-param>
<param-name>initial_actions</param-name>
<param-value>index</param-value>
</init-param>
<init-param>
<param-name>error_page</param-name>
<param-value>/jsp/error/action.jsp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>/web/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<error-page>
<error-code>401</error-code>
<location>/jsp/error/401.html</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/jsp/error/403.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/jsp/error/nullPointer.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/jsp/error/500.html</location>
</error-page>
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/jsp/error/nullPointer.jsp</location>
</error-page>
<!-- <session-config>
<session-timeout>1</session-timeout>
</session-config> -->
</web-app>
注意:在Filter的doFilter方法内如果没有执行chain.doFilter(request,response)那么资源是不会被访问到的。