ThreadLocal使用 --用于保存每个登录用户的信息-userInfo

 

有时我们需要知道每个用户的登录信息,一般我们是将登录的用户信息是保存在session范围内,而我们在DAO中要是使用用户的某些信息,比哪录录ID,单位ID之类的信息进行过滤时,需要从从control 层传到

sevice层,再传到DAO层,比较麻烦。所以我们利用threadLocal 类来解决这方案,做到在任何类中可以直接得到session中的类型,具体实现思路是:用threadLocal 来保存userInfo的信息,在需要使用的类中只需要  new LocalThreadBean().getUserInfo()就可以得到用户登录信息了。

首先建立一个bean:

 

/**
 *〖文件名〗:  LocalThreadBean .java<br>
 *〖功能模块〗:XXX系统<br>
 *〖目的〗:       <br>
 *〖开发者〗:   <br>
 *〖创建日期〗: 2009-7-28<br>
 *〖版本〗:     1.00<br>
 *〖版权信息〗:XXXX<br>
 *〖更改记录〗: 更改时间、更改人、更改原因、更改内容<br>
 */
package com.ygsoft.util;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;

import com.jframe.mf.model.UserInfo;

public class LocalThreadBean implements Serializable{
    private static ThreadLocal<Object> threadLocal = new ThreadLocal<Object>();

    public HttpServletRequest getContext(){
    return (HttpServletRequest)threadLocal.get();
    }
    public void setContext(HttpServletRequest request){
    threadLocal.set(request);
    }

    public void cleanContext(){
    threadLocal.set(null);
    }
    public UserInfo getUserInfo()
    {
 return (UserInfo)this.getContext().getSession().getAttribute("UserData");
    }
    }
然后在系统的过滤器中配置下:

package com.jframe.http;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ygsoft.basic.dao.HibernateDaoSupport;
import com.ygsoft.util.LocalThreadBean;

public class EncodingFilter
    implements Filter
{

    private FilterConfig config;
    private String targetEncoding;
    private LocalThreadBean localThreadBean;
    public EncodingFilter()
    {
        config = null;
        targetEncoding = "GB18030";
        localThreadBean =new LocalThreadBean();

    }

    public void init(FilterConfig config)
        throws ServletException
    {
        this.config = config;
        try
        {
            String temp = config.getInitParameter("encoding");
            if(temp != null)
                targetEncoding = temp;
        }
        catch(Exception exception) { }
    }

    public void destroy()
    {
        config = null;
        targetEncoding = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException
    {
        HttpServletRequest hreq = (HttpServletRequest)request;
        HttpServletResponse hres = (HttpServletResponse)response;
        request.setCharacterEncoding(targetEncoding);
        chain.doFilter(request, response);
        LocalThreadBean.setContext((HttpServletRequest)request);

//      关闭遗漏的 Session
        HibernateDaoSupport.closeSessionList();
    }
}
当然,还需要在web.xml中加上此过滤bean了。

你可能感兴趣的:(DAO,bean,exception,session,String,null)