0

I'm trying to redirect from a servlet controller to a JSP page but it's not working. The scenario is if a user sends a request to the JSP page then at first JSP will invoke the code from servlet. The servlet will then check if the user's session is new or not. If not the servlet will redirect the user to Login page.

To implement this scenario. I've added an JSP:include standard tag in the JSP page.

code from jsp page -

<jsp:include page="/Check_Cookie"/>

And this is the code from the Check_Cookie servlet

HttpSession session = request.getSession();
Cookie[] cookies = request.getCookies();
boolean check = true;

if(session.isNew()){
    check = false;
}

if(cookies==null){
    check = false;
}


if(!check){
    System.out.println("Guest User");   
    response.sendRedirect("Login.jsp");
    return;
}   

It seems the code is ok. But the controller is not redirecting to the login page although the user is not logged in.

It would be great if someone help me on this.

Skibrit
  • 36
  • 7
  • Are you sure, that your session is new? See: [How does isNew() tell if the session is a new one or is already in use?](http://stackoverflow.com/questions/9464166/how-does-isnew-tell-if-the-session-is-a-new-one-or-is-already-in-use) – TeeBea Jan 14 '17 at 10:07
  • You never check if the user is logged in. You only check if the request has a cookie. That will be true if the user has visited any other JSP before this one. Moreover, this is really not a good strategy to do that. You should do that in a servlet filter instead: that allows doing it in a central place instead of having to do an include on all the JSPs. And of course, you should use MVC: requests should go to a controller first, and then be forwarded to the appropriate view. – JB Nizet Jan 14 '17 at 10:10
  • yes, the session is new. I also added the println statement to check if the code inside the if condition is working or not. And yes it's working fine only the send.redirect() method is not working as expected. – Skibrit Jan 14 '17 at 10:11
  • I actually didn't put all the code here.I just added the dummy code to show that the send.redirect() is not working for me. I actually did check if a user is logged in or not but the problem also stays then as well. – Skibrit Jan 14 '17 at 10:14

0 Answers0