非action层 通过 ThreadLocal 获取 request值

来源:互联网 发布:淘宝官方旗舰店怎么开 编辑:程序博客网 时间:2024/06/07 10:17
通过ThreadLocal传递action层中的信息,如request对象等,到飞action层中进行引用。

public class SessionThreadLocal {
@SuppressWarnings("unchecked")
static ThreadLocal sessionUser = new ThreadLocal();

@SuppressWarnings("unchecked")
public static void setSessionUser(ServiceSessionInfo cSession) {
sessionUser.set(cSession);
}

public static ServiceSessionInfo getSessionUser(){
return (ServiceSessionInfo )sessionUser.get();
}

public static String getSessionId(){
return getSessionUser().getSessionId();
}
public static String getId(){
return getSessionUser().getId();
}
}
ServiceSessionInfo是一个pojo,里面放置一些属性和气get和set方法。

编写一个Filter,通过Filter为ThreadLocal设置需要传递的值

主要是从filter中获取servlet对象,再获取session中的登陆信息



/**
 * 通过filter获取servlet相关信息
 * 然后设置到ThreadLocal中,方便飞action层的对象使用
 *
 */


public class SessionFilter implements Filter {

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws ServletException, IOException {
HttpServletRequest hrequest = (HttpServletRequest) request;
ServiceSessionInfo cs = (ServiceSessionInfo) hrequest.getSession(true).getAttribute("custom_report");
if(cs!=null){
SessionThreadLocal.setSessionUser(cs);
}
    chain.doFilter(request,response);
}
public void init(FilterConfig config)throws ServletException {
}
public void destroy() {}
}

第三步:web.xml中加入filter

第四部:飞action层进行引用。例如SessionThreadLocal.getId()


原创粉丝点击