拦截器写法很简单:implements Filter
实现:public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
实现:public void init(FilterConfig filterConfig) throws ServletException
还可以根据业务需要写多个拦截器
package quality.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class LoginCheckFilter implements Filter
{
protected Log log=LogFactory.getLog(getClass());
private String loginPage="";
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
HttpServletRequest httpServletRequest=(HttpServletRequest)request;
log.debug("用户请求URL:"+httpServletRequest.getServletPath()+"?"+httpServletRequest.getQueryString());
log.debug("用户请求参数:"+httpServletRequest.getParameterMap());
String url=httpServletRequest.getServletPath();
if(url.indexOf("login.jsp")>=0 ||url.indexOf("login.action")>=0)
{
chain.doFilter(request, response);
}
else
{
HttpSession session = httpServletRequest.getSession();
//判断用户session是否过期或是否登录
if (session!= null&&session.getAttribute("operatorId")!=null)
{
chain.doFilter(request, response);
}
else
{
//转向登录页面
RequestDispatcher rd=request.getRequestDispatcher(loginPage);
rd.forward(request, response);
}
}
}
public void init(FilterConfig filterConfig) throws ServletException
{
this.loginPage=filterConfig.getInitParameter("loginPage");
}
public void destroy() {}
}
web.xml中配置:
<filter>
<filter-name>LoginCheckFilter</filter-name>
<filter-class>
quality.util.LoginCheckFilter
</filter-class>
<init-param>
<param-name>loginPage</param-name>
<param-value>/login.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LoginCheckFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LoginCheckFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
.NET中用HttpHandel机制实现同样的需求:
<httpHandlers>
<add verb="GET" path="*.aspx" type="AspNetForums.Components.HttpHandler.AvatarHttpHandler, AspNetForums.Components" />
</httpHandlers>
HttpHandlers 是对文件访问句柄进行控制的也就是说,假如我要访问某个网页时,在这之前我要处理某些事情时。
Model是对事件句柄访问进行控制。在页面创建,请求的前后要处理某些事情。
*.aspx 也就是说所有的aspx文件访问都会触发
Path就是对应的文件路径。但这个文件不一定是必须存在的,只要对
文件名进行了请求就会立刻转到HttpHandlers对象类进行处理,而不会再转到页面上进行处理, 也就相当于那个页面是一个虚拟的.
Type 是要处理这些事情要转到那个类去处理,第一个分号前是处理的类最好加上命名空间,第二个是类的命名空间也就是依赖项.
另外,使用这种机制还可以捕捉“盗链”情况,例如在IIS没有做*.rar到asp.net映射之前,这个请求根本不经过asp.net机制的处理,映射后,就可以通过handler拦截到