LoginFilter

package com.chenfei.auction.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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.chenfei.auction.entity.AuctionUser;

/**
* Servlet Filter implementation class LoginFilter
*/
public class LoginFilter implements Filter {

    /**
     * Default constructor.
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}

/**
* 登录过滤
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest  httpReq = (HttpServletRequest)request;
HttpServletResponse httpRes = (HttpServletResponse)response;

//String url = httpReq.getRequestURI();
//url = url.substring(url.indexOf("/",1));

/*保存访问的页面路径*/
List<String> notFilter = new ArrayList();
notFilter.add("/login.jsp");
notFilter.add("/productList.jsp");
//获取当前页面路径
String currentURI = httpReq.getServletPath();
/*判断当前页面路径是否能被访问*/
if(notFilter.contains(currentURI)){
//允许请求通过过滤器继续往下调用
chain.doFilter(request, response);
}else{
//获取session对象
HttpSession session = httpReq.getSession();
//获取当前登录用户
AuctionUser user = (AuctionUser)session.getAttribute("LOGINUSER");
/*用户未登录,跳转登录页面*/
if(user == null){
String path = "/login.jsp";
//若请求为商品竞拍页面
if(currentURI.endsWith("/ProductDetail")){
//获取商品编号
String prodId = httpReq.getParameter("prodId");
if(prodId !=null && !prodId.equals("")) {
//保存商品Id
httpReq.setAttribute("PRODID", prodId);
}
}
//转发至登录页面
httpReq.getRequestDispatcher(path).forward(httpReq, httpRes);
}else{
//允许请求通过过滤器继续往下调用
chain.doFilter(request, response);
}
}

}

/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}

}

你可能感兴趣的:(filter)