JSF页面跳转时清除Session

JSF开发时,难以避免地常会有些Session ScopeMBean,对于这些Bean,我们希望它在同一页面操作时保留,在页面跳转时清除,本文介绍一种自动清除Session的方法。

1.首先在页面中添加一个Session,用来记录原页面的URI,代码如下:

<%

session.setAttribute("pageFrom", request.getRequestURI());

%>

2.添加一个Filter,拦截所有的JSF,进行Session处理,需在web.xml中添加如下代码:

 <filter>
  <display-name>sessionGuard</display-name>
  <filter-name>sessionGuard</filter-name>
  <filter-class>net.moon.filter.SessionGuardFilter</filter-class>
  <init-param>
   <description>the key of sessions want to keep to next page, others
    will be delete</description>
   <param-name>keepSessionKeys</param-name>
   <param-value>userID;pageId;com.sun.faces.logicalViewMap;com.sun.faces.application.StateManagerImpl.SerialId;javax.faces.request.charset<param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>sessionGuard</filter-name>
  <url-pattern>*.jsf</url-pattern>
 </filter-mapping>

其中,com.sun.faces.logicalViewMap;com.sun.faces.application.StateManagerImpl.SerialId;javax.faces.request.charsetJSF保存状态的一些Session,必须保留。

3.编写SessionGuardFilter类,判断请求页面是否为当前页面,如不是,进行Session处理,代码如下:

package net.moon.filter;

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

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.HttpSession;


public class SessionGuardFilter implements Filter {
 private List<String> keepSessionKeys = new ArrayList<String>();

 public void destroy() {
  // TODO Auto-generated method stub

 }

 @SuppressWarnings("unchecked")
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain filterChain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  HttpServletRequest hRequest = (HttpServletRequest) request;
  HttpSession session = hRequest.getSession();
  
  // delete useless sessions when change page
  if (!(hRequest.getRequestURI().replace(".jsf", ".jsp").equals(session
    .getAttribute("pageFrom")))) {
   Enumeration<String> en = session.getAttributeNames();
   while (en.hasMoreElements()) {
    String key = en.nextElement();
    if (!keepSessionKeys.contains(key)) {
     session.removeAttribute(key);
    }
   }
  }
 }

 public void init(FilterConfig filterConfig) throws ServletException {
  // TODO Auto-generated method stub
  StringTokenizer st = new StringTokenizer(filterConfig
    .getInitParameter("keepSessionKeys"), ";");
  while (st.hasMoreTokens()) {
   keepSessionKeys.add(st.nextToken());
  }
 }
}

 

posted @ 2008-07-16 10:44  moonsnow  阅读(302)  评论(0编辑  收藏  举报