欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

拦截JSP页面,校验是否已登录详解及实现代码

程序员文章站 2024-03-11 15:30:01
拦截jsp页面,校验是否已登录    最近使用struts2做项目,需要拦截jsp以校验是否已经登,但struts2的过滤器链只能过滤action。后...

拦截jsp页面,校验是否已登录

   最近使用struts2做项目,需要拦截jsp以校验是否已经登,但struts2的过滤器链只能过滤action。后来发现在web.xml里可以直接增加javax.servlet.filter实现类的过滤器,可以过滤jsp。请看代码

filter实现类

<span style="font-size:18px;">package com.common; 
 
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.httpservlet; 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
 
public class loginfilter extends httpservlet implements filter {  
    
  private static final long serialversionuid = 1l;  
  
  @override  
  public void dofilter(servletrequest request, servletresponse response,  
      filterchain chain) throws ioexception, servletexception {  
    httpservletrequest req = (httpservletrequest)request;  
    httpservletresponse res = (httpservletresponse)response;  
    string path = req.getcontextpath(); 
    string indexpath = req.getscheme()+"://"+req.getservername()+":"+req.getserverport()+path+ "/pages/login.jsp"; 
    if(req.getrequesturi().endswith("login.jsp")) 
    { 
      chain.dofilter(request, response);  
      return; 
    } 
     
    object loginuser = req.getsession().getattribute("<strong><span style="color:#ff0000;">loginsession</span></strong>");  
    if(loginuser == null){ 
      res.sendredirect(indexpath);  
      return;  
    } 
    chain.dofilter(request, response);  
  }  
  
  @override  
  public void init(filterconfig arg0) throws servletexception {  
    // todo auto-generated method stub   
  }  
  
}  
</span> 

登录方法:



<span style="font-size:18px;"> public string login() 
  { 
    login login = new login(); 
       
    //.......校验登录信息 
    actioncontext ctx = actioncontext.getcontext(); 
    map<string, object> session = ctx.getsession(); 
    session.put("<strong><span style="color:#ff0000;">loginsession</span></strong>", login); 
    return "success"; 
  }</span> 

 web.xml配置

<filter>  
   <filter-name>setlog</filter-name>  
   <filter-class>com.common.loginfilter</filter-class>  
</filter>  
<filter-mapping>  
   <filter-name>setlog</filter-name>  
   <url-pattern>/pages/home.jsp</url-pattern> 
   <url-pattern>/pages/channel/*</url-pattern> 
   <url-pattern>/pages/content/*</url-pattern> 
   <url-pattern>/pages/product/*</url-pattern> 
   <url-pattern>/pages/vodtask/*</url-pattern> 
</filter-mapping> 



注意,如果页面上使用了框架,则可能导致session超时后退出到登录页面,此时登录页面显示在框架的某个子页面,解决方法,在登录页面加入如下代码即可。

<span style="font-size: 18px;">  <script language="javascript">   
    if (top != window)   
      top.location.href = window.location.href;   
  </script></span> 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!