views:

69

answers:

2

I am creating a login page for my web application. I want to create a session object whenever a new user logged in. I know the concept of sessions, but i didnt used that before. Can i do it with a simple class. Or, i have to move to servlet. If i shall do it with a simple class means, how to create a session object.


This is my scenario...

The HTML CODE:

<table>
<tr>
<td>User Name: </td><td><input id="uName"  class="required" type="text" 
    size="5" /></td>
</tr>
<tr>
<td>Password: </td><td><input id="pwd"  class="required" type="text" size="5"
    onclick="login()"/></td>
</tr>
</table>

The JS Code:

function login(){
var userDetails = { uName : null, pwd : null };
dwr.util.getValues(userDetails);//Yes, i am using DWR.
LoginAuthentication.doLogin(userDetails, loginResult);
}

 function loginResult(nextPage){
window.location.href = nextPage;
}

The Java Code:

public class LoginAuthentication
{
public String doLogin(User user) throws SQLException, ClassNotFoundException{
    String userName = user.getUserName();
    boolean loginResult = verifyUser(user);//Another method that verifies user details with the DB.
    if (loginResult == true){
        /* Here I have to create session object,
          and i want to add the current username in that object. How to do it.*/

        return "MainPage.html";
    }
    else{

        return "loginRetryPage.html";

    }
   }

The concept that was given to me about session is pretty simple and clear. I have to create a session object after a valid user input & add the user name to that object, Destroy the object when logout was clicked. But i didnt worked on sessions before. I mean, i dont know the syntax to create a session variable.

How shall i create a session Object here?

Any suggestions would be more appreciative!!!

Thanks in Advance!!!

+2  A: 

In a servlet a session is obtained with the following line:

Session session = request.getSession();

And to get the request object with DWR, you do (see here):

WebContext ctx = WebContextFactory.get();
HttpServletRequest request = ctx.getHttpServletRequest();

(The HttpServletRequest contains all data about the HTTP request that has been sent by the browser to the server)

Bozho
@Bozho: What is the "request"? What is its purpose?
NooBDevelopeR
@MaRaVan - see updated
Bozho
@Bozho: Thanks for your instant update. I went thro your link, it seems it ll be useful to me. But, can you explain me what is WebContext. What it ll do? What will happen if i add these two lines? WebContext ctx = WebContextFactory.get();req = ctx.getHttpServletRequest();
NooBDevelopeR
yes, it will. The above three lines will give you the Session object, where you can add things and retrieve things.
Bozho
+2  A: 

It is better to always use request.getSession(false); after successful login.

Suresh S
NooBDevelopeR