Reputation: 1
i am facing trouble in applying session.
index.jsp has simple login form which when submitted go to a servlet which create session and redirect to admin_home.jsp page, everything is fine here.
But I want that when user directly want to go to admin_home.jsp, he will redirected to index.jsp page.Here is the problem:
admin_home.jsp
<body>
<%
session=request.getSession(false);
if(session.getAttribute("User_ID")==null)
{
response.sendRedirect("index.jsp");
}
%>
<jsp:include page="header.jsp"></jsp:include>
<div>
<div id="left">
<div id="photo">
<img alt="" src="images/users_image/<%out.println(session.getAttribute("User_ID").toString().concat(".jpg"));%>" />
</div>
</div>
</div>
</body>
The login servlet is setting the value User_ID in session....
So when user try to access admin_home.jsp directly he should redirect to index.jsp page... what is wrong in my code ....
Upvotes: 0
Views: 7512
Reputation: 51
<%
session=request.getSession(false);
if(session.getAttribute("User_ID")==null)
{
response.sendRedirect("index.jsp");
}
%>
put that code in between html and head section that worked for me
Upvotes: 0
Reputation: 691715
This code should be done before anything is flushed to the response, and it should not execute any instruction after the redirect.
Moreover, this isn't view logic (so it shouldn't be in a JSP), and you really don't want to have this code in every JSP and servlet of your application that needs the user to be authenticated. You should thus put this logic in a servlet filter.
Finally, the following code will throw an exception if there's no session yet. Soc heck that the session is not null, or don't use getSession(false)
, but getSession()
:
session=request.getSession(false);
if(session.getAttribute("User_ID")==null)
Upvotes: 1