-1

There are a million examples on the web that shows how to create a basic Java Login Servlet, where the user has to enter a username and password which gets verified by some database. When the login info is correct, it redirects you to another page.

The problem is that the tutorials only teach how to verify if a user has inputted the correct username / password. If the user knew the URL to the other pages, he can skip the entire login process altogether. How do I make it so my login servlet actually logs me in and is required to access the other pages?

This is what my login process currently looks like

if(user.isValid())
        {
            HttpSession session = request.getSession(true);
            session.setAttribute("currentSessionUser",user);
            response.sendRedirect("Unit_Info.jsp");
        }else
            response.sendRedirect("http://google.com"); 

3 Answers 3

1

You can use a RequestFilter which will check for user session.

Read more : Filtering Requests and Responses

1

After getting the login details from the user, you can save the login details in session and in every page you can test or validate the session like...

<%
String strLoginId = (String)session.getAttribute("LoginID");
String strpassword = (String)session.getAttribute("Password");

if(strLoginId==null)  // Means session is not there
%>
<jsp:forward page="Error.jsp" />
3
  • Thats they way I do it. Oct 22, 2013 at 9:43
  • Is there any purpose for the String strpassword? And is there any security risks to using strLoginId==null ? By this, I mean can't users simply just make their strLoginId some random character to access the entire website?
    – krikara
    Oct 22, 2013 at 9:48
  • Holy smokes, it took me way too long to figure out why your code produced errors. Apparently, I was supposed to use session.getAttribute("currentSessionUser").toString(); instead of (String)session.getAttribute
    – krikara
    Oct 23, 2013 at 3:40
0

when login is successful you can set a a value in session.setAttribute() and in all pages by using session.getAttribute() check if the value is present or not.If yes stay else go back to login page.

example

After login is successful do

    session.setAttribute("user","user");

Now eac and every page check
if(session.getAttribute("user")==null)
{
response.sendRedirect("loginpage");

}
else
{

//your codes
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.