4

I'm new in GWT ... I would like to implement sessions in my Web App Basically I want that a session starts at the click of a button (handle an event) and ends at the click of another button (other handle an event). It's possible?

How to do it step by step?

Is it okay this code?:

Main (client-side):

Button b1 = new Button("b1");
b1.addClickHandler(new ClickHandler) {
      public voin onClick(){
              ...
             rpc.setSession(callback); //rpc call the service...

   }
}

Button b2 = new Button("b2");
b1.addClickHandler(new ClickHandler) {
      public voin onClick(){
              ...
             rpc.exitSession(callback);

   }
}

//------------------------------------------------------------------------------------

import com.google.gwt.user.client.rpc.RemoteService;

public interface MySession extends RemoteService {

    public void setSession();

    public void exitSession();
}

//------------------------------------------------------------------------------------

import com.google.gwt.user.client.rpc.AsyncCallback;

public interface MySessionAsync {

    void setSession(AsyncCallback<Void> callback);

    void exitSession(AsyncCallback<Void> callback);

}

//------------------------------------------------------------------------------------

import de.vogella.gwt.helloworld.client.MySession;

public class MySessionImpl extends RemoteServiceServlet implements MySession {

    HttpSession httpSession;
    @Override

    public void setSession() {
        httpSession = getThreadLocalRequest().getSession();

        httpSession = this.getThreadLocalRequest().getSession();
        httpSession.setAttribute("b", "1");

    }

    @Override
    public void exitSession() {
          httpSession = this.getThreadLocalRequest().getSession();
          httpSession.invalidate(); // kill session     
    }

}

What I do is I connect with my Web application to another web page, if I click the back button of the browser that I return to my web app with the session still alive ... How can I do?

I hope I have explained well what my problem ...

*****NEW PROBLEM***:**

I tried to do so ...

---client side.... MAIN:

        MyServiceAsync service = (MyServiceAsync) GWT.create(MyService.class);
        ServiceDefTarget serviceDef = (ServiceDefTarget) service;
        serviceDef.setServiceEntryPoint(GWT.getModuleBaseURL()+ "rpc");

        boolean b=false;;

        b=service.checkSession(new AsyncCallback<Boolean>() {

            @Override
            public void onSuccess(Boolean result) {
                // here is the result
                if(result){
                        // yes the attribute was setted
                   }
            }

            @Override
            public void onFailure(Throwable caught) {
                Window.alert(caught.getMessage());

            }
        });

        if (b==false){ // se non esiste una sessione
        RootPanel.get().add(verticalPanel); 
        RootPanel.get().add(etichetta); 
        RootPanel.get().add(nameField);
        RootPanel.get().add(sendButton);
        RootPanel.get().add(horizontalPanel); 

        }

        else{ //esiste già una sessione attiva (pagina da loggato)
            welcome.setText("Ciao "+userCorrect+"!!");
            RootPanel.get().add(verticalPanelLog);
            RootPanel.get().add(etichetta);
            RootPanel.get().add(nameField);
            RootPanel.get().add(cercaLog);
            RootPanel.get().add(horizontalPanel);
        }

////////////////////////////////////////////////////////////////////////

public interface MyServiceAsync {
...

    void exitSession(AsyncCallback<Void> callback);

    void setSession(AsyncCallback<Void> callback);

    void checkSession(AsyncCallback<Boolean> callback); //error!!

////////////////////////////////////////////////////////////////////////

public interface MyService extends RemoteService {
    /.....

    public void setSession();

    public void exitSession();

    public boolean checkSession();

////////////////////////////////////////////////////////////////////////

server-side:

public boolean checkSession() {

      httpSession = this.getThreadLocalRequest().getSession();

      //se la sessione esiste già
      if (httpSession.getAttribute("b")!= null){
          return true;
      }
      else{ .
          return false;
      }
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
JackDaniels
  • 77
  • 1
  • 2
  • 7

1 Answers1

12

session in GWT is similar to session in servlet. The difference is in servlet you call
HTTPSession session = request.getSession();

in gwt you call

HttpServletRequest request = this.getThreadLocalRequest(); to get request and then again request.getSession();

in your situation you should call RPC when click the button and manage the session on server the previous code and call another RPC when clicking another button and invalidate session. Here is example;

Button b1 = new Button("b1");
b1.addClickHandler(new ClickHandler) {
    // call RPC and 
   // session = this.getThreadLocalRequest().getSession();
  // session.setAtribute("b", "1");
}


Button b2 = new Button("b2");
b1.addClickHandler(new ClickHandler) {
    // call RPC and 
   // session = this.getThreadLocalRequest().getSession();
  // session.invalidate(); // kill session
}

This link maybe helpful to you Using Servlet Sessions in GWT

Edit :

If you want to test whether the session isExist() or not try this

add to your interface boolean test(String attr);
add to your .async add void test(String attr, AsyncCallback<Boolean> callback);
add to your .impl

@Override
public boolean test(String attr) {
    return session.getAttribute(attr) != null;
}

and just call

Rpc.test(attribute, new AsyncCallback<Boolean>() {

        @Override
        public void onSuccess(Boolean result) {
            // here is the result
            if(result){
                    // yes the attribute was setted
               }
        }

        @Override
        public void onFailure(Throwable caught) {
            Window.alert(caught.getMessage());

        }
    });
  • Hi hilal, thank for your response... but I don't understand a thing: HttpSession httpSession = getThreadLocalRequest().getSession() must be included in the "impl" server-side right? If not too much trouble, could you give me an example of the "RPC call" buttons within? Thanks – JackDaniels Jan 15 '11 at 09:26
  • for example...I have interface "MySession", "MySessionAsync" in the client-side, and I have "MySessionImpl" in server-side. What should I put in these containers? – JackDaniels Jan 15 '11 at 09:33
  • yes it must be included in the "impl". you can't do it on client-side. For every server actions you should call rpc –  Jan 15 '11 at 09:51
  • this nothing related to session management. It gives "this is either misconfiguration or a hack attempt". Did you do this @RemoteServiceRelativePath("/*greet*/") to your async service and is your web.xml correct ? servlet mapping ? please check these errors. this is not related to session management –  Jan 15 '11 at 12:15
  • I don't use @RemoteServiceRelativePath...I manage a remote procedure call and the other is functioning properly. But because I said "Blocked attempt to access interface 'de.vogella.gwt.helloworld.client.MyService, ' Which is not implemented by 'de.vogella.gwt.helloworld.server.MySessionImpl''Either this is a misconfiguration or hack attempt "when MySessionImpl is Implemented by MySession?? (MyService is the other call ..) – JackDaniels Jan 17 '11 at 08:42
  • please follow these steps that mentioned in http://www.vogella.de/articles/GWT/article.html to create a simple app in gwt and don't forget @RemoteServiceRelativePath and in web.xml –  Jan 17 '11 at 08:46
  • If I use a single rpc, it works. But If I click the first button and then I connect to an external web page via a url of my webapp and then go back to the browser's back button I lost the session (ie the session is still active .. I) but in my code tells me that I should still log in (which should not happen). I think that, it back to the Entry-point of the webapp (Where do I log in). – JackDaniels Jan 17 '11 at 09:16
  • In the method onModuleLoad () I set the initial panel. Can I check to see if the session exists or not? – JackDaniels Jan 17 '11 at 09:35
  • perfect...one last thing ... I wish they'd return a boolean from the RPC server. But do not let me why? I mean, I want to do: if boolean b = true (if no active session): panel insert initials. b = false else if (insert panel from the terrace). Can you help me? Thank you very much – JackDaniels Jan 17 '11 at 10:12
  • define a method that return boolean in your interface. boolean isSessionExists(); for example. then you can do it with callin rpc and asynccallback. after that do whatever you want if(result) do this else do that –  Jan 17 '11 at 10:16
  • I have a mistake ... I'm not making the asynchronous call return ... why? I post my new problem ... (sorry if I have not yet accepted the answer) ... – JackDaniels Jan 17 '11 at 10:25
  • insert this to your interface boolean isSessionExist(); after that implement it on server .impl and then client call as a normal rpc that take the output/result with asynccallback. that's all. I will answer your other question in 15 minutes. now I should turn to my job :) –  Jan 17 '11 at 10:30
  • If I insert boolean checkSession(AsyncCallback callback); in my interface async I have an error!!tells me to be void ... – JackDaniels Jan 17 '11 at 10:34
  • In your interface : boolean test(); in your async : void test(AsyncCallback callback); in your .impl boolean test() { return session.getAttribute(attribute) != null;) –  Jan 17 '11 at 10:36
  • PS: but I can instantiate the answer? for example rpc.checkSession boolean b = (callback)? I need this ...thanks for your help, Hilal...I'm missing only this..:( – JackDaniels Jan 17 '11 at 11:37
  • 1
    you are welcome. it makes me happy that you learn something new –  Jan 18 '11 at 05:05