0

我正在尝试在 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
}

}

4

1 回答 1

0

您的代码中至少有两个问题:

  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();
        }
    }
    
于 2013-07-05T11:09:41.247 回答