0

I have a issue on Java. I have a "index.jsp", now whenever it will run I want to check someone login or not. If no one is log in then only login button is show otherwise show the user name in place of login. To Solve this problem I use -

session.getsession(false);
if(session==null)
    response.sendRedirect("login.jsp");
else
//rest of HTML Code.

but it is not working, it's always goes to else part.
Note:"index.jsp" is not forward from "logout.jsp" or anywhere where "session.invalidate()" is called. It is first time when the project run.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
Somnath Kayal
  • 393
  • 2
  • 9
  • 25

2 Answers2

2

Try this code to get the session

 HttpSession session = request.getSession(false);

instead of

session.getsession(false);

once u get hold of a session:

if(session == null)
{
    //session does not exists
    //redirect to login page
}
else
{
    //session is not ended
}

EDIT :

Looking at your comment, I understand that you are using JSPs. In JSPs a default session is created by the container if you don't explicitly specify not to do so.

You can ask not to create a default session by adding the following line

<%@page session="false" %> 

at the top of the page

codeMan
  • 5,730
  • 3
  • 27
  • 51
  • Thanks for your reply. But I have tried this, it always goes into else part, can't understand why? Is there any other process? ` <% session =request.getSession(false); if(session==null) { response.sendRedirect("login.html"); } else { out.println("hi"); } %>` It is always print hi. – Somnath Kayal Apr 08 '13 at 17:55
  • In JSP session quite work in a different way than u expect: Take a look at this answer : http://stackoverflow.com/questions/9135725/how-to-check-for-session-in-jsp-el – codeMan Apr 12 '13 at 05:39
0

You can use attributes to store login status (Ex: Username).

(String)session.getAttribute("Username")

If the value of the above string is null then user is not logged in. Make sure you set the value of this attribute after successful user login :)

Vishy
  • 1,292
  • 12
  • 17