Filter过滤器
Posted huang麦穗儿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Filter过滤器相关的知识,希望对你有一定的参考价值。
Filterservlet.java
package com.xxpx.servlet;
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;
import javax.servlet.http.HttpSession;
import com.xxpx.bean.User;
public class FilterTest implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest)servletRequest;
String requestURI = request.getRequestURI();
int lastIndexOf = requestURI.lastIndexOf("/");
String substring = requestURI.substring(lastIndexOf+1);
if("login.jsp".equals(substring)){
arg2.doFilter(servletRequest, servletResponse);
}else{
HttpServletResponse response = (HttpServletResponse)servletResponse;
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
if(user==null){
response.sendRedirect("login.jsp");
}else{
arg2.doFilter(servletRequest, servletResponse);
}
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
System.out.println("开始过滤");
}
}
web.xml配置
<filter>
<filter-name>test</filter-name>
<filter-class>com.xxpx.servlet.FilterTest</filter-class>
</filter>
<filter-mapping>
<filter-name>test</filter-name>
<url-pattern>/houtai/pages/*</url-pattern>
<url-pattern>/houtai/main.jsp</url-pattern>
</filter-mapping>
以上是关于Filter过滤器的主要内容,如果未能解决你的问题,请参考以下文章