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
}

}

Community
  • 1
  • 1
redwolf_cr7
  • 1,845
  • 4
  • 26
  • 30

1 Answers1

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();
        }
    }
    
home
  • 12,468
  • 5
  • 46
  • 54
  • 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. – redwolf_cr7 Jul 05 '13 at 12:36
  • 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. – redwolf_cr7 Jul 05 '13 at 13:08
  • What is your servlets' path? And please show the class using the static filter methods... – home Jul 05 '13 at 13:47
  • 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); }` – redwolf_cr7 Jul 05 '13 at 17:11
  • 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? – redwolf_cr7 Jul 07 '13 at 12:29
  • On further investigation, the request itself is null. Does the request become null? Am i doing something wrong in the front controller servlet? – redwolf_cr7 Jul 07 '13 at 14:22
  • Does the request expire after we call this: dispatcher.forward(request, response); – redwolf_cr7 Jul 07 '13 at 14:50
  • Probably your servlet path (see point #1 in my answer) is wrong. So again, to which path does your servlet listen? – home Jul 08 '13 at 16:27
  • Thx for your inputs. I am directly getting the session attribute from the jsp file now and sending it across to the java class. Thx once again. – redwolf_cr7 Jul 09 '13 at 12:08
  • @user2520416: np, maybe you can tell us how you solved the problem? So the question might become helpful for others as well. – home Jul 09 '13 at 15:38
  • i wanted a solution to access the session attribute directly from the java class. Unfortunately i couldn't get it to work. So i pass the session.getAttribute from my jsp file as an argument to the servlet, which in turn passes it on to the java class. – redwolf_cr7 Jul 10 '13 at 08:46