判断用户是否登录,如果登录了放行,否则跳转到登陆页面

package elkw.action;  
import javax.servlet.Filter;  
  import javax.servlet.FilterConfig;  
  import javax.servlet.ServletException;  
  import javax.servlet.ServletRequest;  
  import javax.servlet.ServletResponse;  
  import javax.servlet.FilterChain;  
  import java.io.IOException;  
  import javax.servlet.http.HttpServletRequest;  
  import javax.servlet.http.HttpSession;  
import javax.servlet.http.HttpServletResponse; 
import elkw.po.system.User;
 
  public class RightFilter  
    implements Filter {  
  public void init(FilterConfig filterConfig) throws ServletException
  {  
  }  
 
  public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
  {  
    HttpServletRequest req = (HttpServletRequest) request; 
    HttpServletResponse res = (HttpServletResponse) response;  
    HttpSession session = req.getSession(true);  
    //从session里取的用户名信息  
    User username = (User) session.getAttribute("user");  
    String reuris = req.getRequestURI(); // 获取访问路径
    String reuri = reuris.substring(0, 17); //截取0-17的字符
    String loginAction = "/backserver/login";//定义登陆的地址
    //判断如果没有取到用户信息,就跳转到登陆页面  
    String ipad = "/backserver/jsond";
    
    if (username == null || "".equals(username)) {  
     //ipad请求数据和登陆页面不过滤
     if (reuri.equals(loginAction) || reuri.equals(ipad))
        {
      chain.doFilter(request,response); 
      return;
        }
    //跳转到登陆页面  
      res.sendRedirect("http://"+req.getHeader("Host")+"/backserver"); 
    }  
    else {  
      //已经登陆,继续此次请求  
      chain.doFilter(request,response);  
    }  
  }  
 
  public void destroy() {  
  }  
} 
 


  下面配置这个过滤器 
  然后在web.xml里配置那些JSP文件需要登陆权限验证: 
 
 

<!-- 判断用户是否登录 ,过滤action的请求(你也可以写 (*.jsp) ,(*.html),(/*)全局的 ,)。。。。 -->
  <filter>  
          <filter-name>right</filter-name>  
          <filter-class>你的类名</filter-class>  
      </filter>  
  <filter-mapping>  
          <filter-name>right</filter-name>  
          <url-pattern>*.action</url-pattern><!-- 拦截-->
      </filter-mapping>

大家如果有什么疑问一起探讨探讨

你可能感兴趣的:(String,session,filter,user,import,ipad)