Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpServletRequest request = this.getThreadLocalRequest() return null?

Tags:

gwt

I want to get a Attribute of session in GWT app. i get Session like this

HttpServletRequest request = this.getThreadLocalRequest();
System.out.println("Check HttpServletRequest");       
HttpSession session = request.getSession();

but this.getThreadLocalRequest() is always null.

CODE :

Client:

@RemoteServiceRelativePath("service.s3gwt")
public interface getAttributeSession extends RemoteService 
{
    String getSessionAttribute(String name);
}

public interface getAttributeSessionAsync 
{
    void getSessionAttribute(String name, AsyncCallback<String> callback);
}

Server:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import daTotNghiep.client.service.getAttributeSession;

public class getAttributeSessionImpl extends RemoteServiceServlet implements getAttributeSession 
{
    private static final long serialVersionUID = 1L;

    public String getSessionAttribute(String name) 
    {
    // TODO Auto-generated method stub

    HttpServletRequest request = this.getThreadLocalRequest();
    System.out.println("Check HttpServletRequest");
    if(request == null) System.out.println("SO BAD");

   //   HttpSession session = request.getSession();
   // System.out.println("ID session "+session.getId());

     return "";
    }
}

When call method getSessionAttribute() I see that this.getThreadLocalRequest() always returns null. So Why? And how to fix it?

like image 662
user1403078 Avatar asked Nov 13 '22 05:11

user1403078


1 Answers

The method getThreadLocalRequest() is implemented in the class AbstractRemoteServiceServlet, which is inherited by RemoteServiceServlet. The implementation sets the field perThreadRequest (which is used by getThreadLocalRequest()) only for the method doPost(). That means, getThreadLocalRequest() will only return the request if it is called from within a POST request, and then only if you didn't overwrite doPost() without calling the super method.

So to make sure getThreadLocalRequest() doesn't return null

  • make sure you're calling itfrom within a POST request (and not a GET or some other HTTP request type).
  • make sure you didn't overwrite doPost() without calling super.doPost()
like image 77
Bob Avatar answered Jun 23 '23 02:06

Bob