Search code examples
jspservletsjakarta-eeurl-routinghttpsession

JEE: How to stop URL mapping?


I'm trying to prevent URL mapping. Only logged in user will be allowed to assess welcome.jsp page.

My Login.java servlet is as follows,

package com.login;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/Login")
public class Login extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uname=request.getParameter("uname");
        String pass= request.getParameter("pass");

    if(uname.equals("indrajith") && pass.equals("123")) {
        HttpSession session =request.getSession();
        session.setAttribute("username", uname);
        response.sendRedirect("welcome.jsp");
    }
    else {
        response.sendRedirect("login.jsp");
    }
    }


}

My login.jsp page contains following form,

    <form action="Login">
        Enter username:<input type="text" name="uname"><br>
        Enter password:<input type="password" name="pass"><br>
        <input type="submit" value="login">
    <form>

In my welcome.jsp page I'm checking what is the data user has entered,

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
    if(session.getAttribute("username")==null){
    response.sendRedirect("login.jsp");
}
%>
    welcome ${username}

</body>
</html>

But my problem is still I can URL routing whether I'm logged in or not. I have no idea what is wrong with my code. In StackOverflow, there are some similar questions but the answers are not giving a solution to my problem.

Thanks in advance!

PS: I'm using Tomcat 8.5.40 with eclipse IDE in my 64bit Windows machine.


Solution

  • Everything you write in a .jsp will be added inside a method called _jspService() (long story short). After setting the redirect url, you must use the return statement to stop jvm from executing the rest of the code.

    Keep in mind that sendRedirect() is just another method for jvm which adds the Location header in the response.


    Update your welcome.jsp

    <%
        if(session.getAttribute("username") == null){
            response.sendRedirect("login.jsp");
            return; // add this statement
        }
    %>
    

    and it's better to add this code fragment on top of the page.