如何用Filter实现对注册用户是否登录的过滤

package filter;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.* ;

public class UserFilter implements Filter
{
 
 public void init(FilterConfig filterConfig) throws ServletException
 {
 
 }
 

 public void doFilter(ServletRequest request,
            ServletResponse response,
            FilterChain chain) throws ServletException,IOException
 {
  response.setContentType("text/html ;charset=UTF-8");
  request.setCharacterEncoding("UTF-8");
  PrintWriter out=response.getWriter();
 
  HttpServletRequest req=(HttpServletRequest)request;
  HttpSession session=req.getSession();
  //System.out.println(session.getAttribute("user"));
 
 
  if(session.getAttribute("user")!=null){
   RequestDispatcher rd = null;
   rd = request.getRequestDispatcher("/index.jsp"); //定向的页面
   rd.forward(request, response);
  }
  else{
   RequestDispatcher rd = null;
   rd = request.getRequestDispatcher("/login.jsp"); //定向的页面
   rd.forward(request, response);

  
  }
 }

 public void destroy(){}
}

你可能感兴趣的:(filter)