访问JAVA类中的会话属性

时间:2013-07-05 11:04:26

标签: java session servlets filter attributes

我正在尝试在java类中获取会话属性。我发现了这篇文章:get HttpSession|Request from simple java class not servlet class ...我试图做Matej tymes建议的事情。我写了一个RequestFilter并尝试获取请求和会话对象。从那里我试图获得会话属性。但我得到一个空对象。请在下面找到我的代码:

    Front Controller Servlet:
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException{
    PrintWriter out=response.getWriter();
    response.setContentType("text/html");
    String userName=request.getParameter("userName");
    String pass=request.getParameter("userPassWord");
    String clientId = request.getParameter("client");

    try {

        Class.forName("com.mysql.jdbc.Driver");

        connection =
         DriverManager.getConnection("jdbc:mysql://localhost:3306/ABC", "xyz", "*****");

        String queryString = "SELECT * FROM userInfo WHERE UserName=?";

        //connection =ConnectionFactory.getInstance().getConnection();
        ptmt = connection.prepareStatement(queryString);
        ptmt.setString(1, userName);
        resultSet = ptmt.executeQuery();
        //Creating Servlet Context object
        if(resultSet.next() && pass.equalsIgnoreCase(resultSet.getString("UserPass")))
        {
            HttpSession session=request.getSession(true);
            session.setAttribute("loggedUser", userName);
            session.setAttribute("clientId", clientId);

            ServletContext context=getServletContext(); 
            RequestDispatcher dispatcher=context.getRequestDispatcher("/tabmenu.html");
            dispatcher.forward(request, response);

        }else{
            request.setAttribute("wrongUser",userName);

            ServletContext context=getServletContext(); 
            RequestDispatcher dispatcher=context.getRequestDispatcher("/fail");
            dispatcher.forward(request, response);

        }

    } catch (SQLException e) {
        e.printStackTrace();
    }catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    }

/**   
 * Servlet Filter implementation class RequestFilter
 */
@WebFilter("/RequestFilter")
public class RequestFilter implements Filter {
private static ThreadLocal<HttpServletRequest> localRequest = new ThreadLocal<HttpServletRequest>();

/**
 * Default constructor. 
 */
public RequestFilter() {
    // TODO Auto-generated constructor stub
}

/**
 * @see Filter#destroy()
 */
public void destroy() {
    // TODO Auto-generated method stub
}

public static HttpServletRequest getRequest() {
    System.out.println("Fetching the Request!!!");
    return localRequest.get();
}

public static HttpSession getSession() {
    System.out.println("Fetching the Session!!!");
    HttpServletRequest request = localRequest.get();
    return (request != null) ? request.getSession() : null;
}

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // TODO Auto-generated method stub
    // place your code here

    // pass the request along the filter chain
    chain.doFilter(request, response);

    if (request instanceof HttpServletRequest) {
        localRequest.set((HttpServletRequest) request);
    }

    try {
        chain.doFilter(request, response);
    }
    finally {
        localRequest.remove();
    }
}


/**
 * @see Filter#init(FilterConfig)
 */
public void init(FilterConfig fConfig) throws ServletException {
    // TODO Auto-generated method stub
}

}

1 个答案:

答案 0 :(得分:0)

您的代码中至少存在2个问题:

  1. @WebFilter("/RequestFilter")注释对我没有意义。必须设置一种方法来命中所有对ThreadLocal值感兴趣的传入请求,例如"/*"

  2. 您将请求两次传递给链。您必须首先设置ThreadLocal值,然后转发到链,最后删除ThreadLocal值。只需删除第一个chain.doFilter(...)调用。

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
        // pass the request along the filter chain
        chain.doFilter(request, response); <-------------------- PROBLEM
    
        if (request instanceof HttpServletRequest) {
            localRequest.set((HttpServletRequest) request);
        }
    
        try {
            chain.doFilter(request, response);
        } finally {
            localRequest.remove();
        }
    }