0

I'm trying to fetch a session attribute in a java class. I came across this post: get HttpSession|Request from simple java class not servlet class... I tried to do what Matej tymes suggested. I wrote a RequestFilter and tried to fetch the request and session object. And from there i tried to get the session attribute. But i'm getting a null object. Please find my code below:

    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
}

}

0

1 Answer 1

0

There are at least 2 problems in your code:

  1. The @WebFilter("/RequestFilter") annotation does not make sense to me. It MUST be set in a way to hit all incoming requests interested in the ThreadLocal value, e.g. "/*".

  2. You pass the request twice to the chain. You must first set the ThreadLocal value, then forward to the chain, and finally remove the ThreadLocal value. Just remove the first chain.doFilter(...) invocation.

    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();
        }
    }
    
Sign up to request clarification or add additional context in comments.

11 Comments

I have removed the first chain.doFilter() call. And then from my java class i'm calling: HttpSession session = RequestFilter.getSession(); HttpServletRequest req = RequestFilter.getRequest(); String user = (String) session.getAttribute("loggedUser"); But i am still getting a null error.
Im using request filter only from the java class to retrieve the session attributes. So would the annotation make any difference? I'm just calling the request filter to fetch the session and request objects.
What is your servlets' path? And please show the class using the static filter methods...
here the java class accessing the filter: public static void FetchSessionAttributes(){ HttpSession session = RequestFilter.getSession(); HttpServletRequest req = RequestFilter.getRequest(); String user = (String) session.getAttribute("loggedUser"); System.out.println("Retrieved User: "+user); }
i'm getting a null pointer exception for session.getAttribute("loggedUser"); Does that mean the session is not existing? or am i doing something wrong in creating session and setting the attributes?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.