6 Replies - 1364 Views - Last Post: 31 August 2013 - 01:39 AM

#1 kiad_198  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 119
  • Joined: 19-November 08

Browser Back Button or My Code in Servlet

Posted 23 August 2013 - 08:52 PM

Hi Guys,

I am newbie in Java Servlet. I start working on Login/Logout application. My Problem is that when I successfully login it will go to welcome page and try to logout then when I press the Back button at the browser, it will back to welcome page which shouldn't be.

How to fix my Logout code?

Please I need help.

Here's my code:

* Login.java
package mypackage;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class Login extends HttpServlet{

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String user = request.getParameter("user");
        String pass = request.getParameter("pass");
        
        if(Validate.checkUser(user, pass))        {
        	
            RequestDispatcher rs = request.getRequestDispatcher("Welcome");
            rs.forward(request, response);
        }
        else
        {
           out.println("Username or Password incorrect");
           RequestDispatcher rs = request.getRequestDispatcher("index.html");
           rs.include(request, response);
        }
       
    }  
}



* Logout
package mypackage;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		
		response.setHeader("Cache-Control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");

		request.getSession().invalidate();
    	response.sendRedirect(request.getContextPath() + "/index.html");
	}

}



* Validate
package mypackage;
import java.sql.*;

public class Validate
 {
 
     public static boolean checkUser(String user,String pass) 
     {
      boolean st =false;
      try{

	 //loading driver
         Class.forName("com.mysql.jdbc.Driver");

 	 //creating connection with the database 
         Connection con=DriverManager.getConnection
                        ("jdbc:mysql://localhost:3306/login","root","");
         PreparedStatement ps =con.prepareStatement
                             ("select * from log where User=? and Pass=?");
         ps.setString(1, user);
         ps.setString(2, pass);
         ResultSet rs =ps.executeQuery();
         st = rs.next();
        
      }catch(Exception e)
      {
          e.printStackTrace();
      }
         return st;                 
  }   
}



* Welcome
package mypackage;
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class Welcome extends HttpServlet {

    
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
         
        String n=request.getParameter("user");
        out.println("Welcome " +n + "! ");        
        out.println("<a href = 'Logout' onclick = 'on_Click();'> Logout </a>");            
        
      }          
}



index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Form</title>
</head>
<body>
	<div class="form">
	<form method="post" action="Login">
	Username:<input type="text" name="user" /><br />
	Password:<input type="password" name="pass" /><br />
	<input type="submit" value="Login" />
	</form>
	</div>
</body>
</html>



* web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>Sample</display-name>
	<servlet>
		<description>
		</description>
		<display-name>Login</display-name>
		<servlet-name>Login</servlet-name>
		<servlet-class>mypackage.Login</servlet-class>
	</servlet>
	<servlet>
		<description>
		</description>
		<display-name>Welcome</display-name>
		<servlet-name>Welcome</servlet-name>
		<servlet-class>mypackage.Welcome</servlet-class>
	</servlet>
	<servlet>
		<description>
		</description>
		<display-name>Logout</display-name>
		<servlet-name>Logout</servlet-name>
		<servlet-class>mypackage.Logout</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>Login</servlet-name>
		<url-pattern>/Login</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Welcome</servlet-name>
		<url-pattern>/Welcome</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Logout</servlet-name>
		<url-pattern>/Logout</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>		
	</welcome-file-list>
</web-app>




Thanks Guys,

Is This A Good Question/Topic? 0
  • +

Replies To: Browser Back Button or My Code in Servlet

#2 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,055
  • Joined: 28-December 10

Re: Browser Back Button or My Code in Servlet

Posted 27 August 2013 - 07:10 PM

You should create a session so you can distinguish if a user is logged in or not. This way, if the session is still alive, you can redirect the user anyway you want.
Was This Post Helpful? 0
  • +
  • -

#3 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Browser Back Button or My Code in Servlet

Posted 28 August 2013 - 10:18 AM

Quote

You should create a session so you can distinguish if a user is logged in or not. This way, if the session is still alive, you can redirect the user anyway you want.


If the page is accessed via the back button, a cache version will probably be returned.

Quote

I am newbie in Java Servlet. I start working on Login/Logout application. My Problem is that when I successfully login it will go to welcome page and try to logout then when I press the Back button at the browser, it will back to welcome page which shouldn't be.


Checking the session per page request, as fromTheSprawl suggested, will ensure restricted access to internal site pages for unauthorized users. To solve the back button issue, you can issue a must-revalidate cache control directive in the response header to force the browser to run the script, even when the back button is pressed. If the page contains highly sensitive data, you should use no-store/no-cache cache control to prevent pages from being stored on the client.

This post has been edited by blackcompe: 28 August 2013 - 10:20 AM

Was This Post Helpful? 0
  • +
  • -

#4 kiad_198  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 119
  • Joined: 19-November 08

Re: Browser Back Button or My Code in Servlet

Posted 28 August 2013 - 07:46 PM

Thanks for the reply guys very much appreciated.

Where do I start the session in this code?
Actually, I don't know how to add session this code.
I am still at the process of learning. I am not knowledgeable enough, I am sorry for that.
Hope any suggestion would be great.


Thanks guys,
Was This Post Helpful? 0
  • +
  • -

#5 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Browser Back Button or My Code in Servlet

Posted 28 August 2013 - 08:07 PM

To fix your current issue, just add the response headers, no sessioning needed. Java sessions aren't so easily explained. You'll need to do some reading. As far as code goes, it's pretty simple. I'd suggest looking at some code examples on the web.

LoginServlet.java

if(loginCredentialsAreCorrect)
     request.getSession().setAttribute("authenticated", true);



Other restricted access pages

sess = request.getSession(false);
if(sess == null || sess.getAttribute("authenticated") == null)
     response.getWriter().println("Please sign-in.");


Was This Post Helpful? 1
  • +
  • -

#6 kiad_198  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 119
  • Joined: 19-November 08

Re: Browser Back Button or My Code in Servlet

Posted 31 August 2013 - 12:26 AM

I've found this code and its working using session but still when I press back button the session not end.
What to add in this code?

Login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Form</title>
</head>
<body>
<div align="center">
<form id="loginform" action="Validate" method="post">
<div style="font-size:40px; font-weight:bolder;">Login Page</div>
<table>
 <tr>
 <td><label for="loginid">UserId</label></td>
 <td><input type="text" name="uid" /></td>
 </tr>
 <tr>
 <td><label for="pass">Password</label></td>
 <td><input type="password" name="pid" /></td>
 </tr>
 <tr>
 <td></td>
 <td><input type="submit" value="logn" /></td>
 </tr>
</table>
</form></div>
</body>
</html>



Logout.java
package my.packages;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Logout extends HttpServlet {

	private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
 response.setContentType("text/html;charset=UTF-8");
 PrintWriter out = response.getWriter();
 try {
 HttpSession session=request.getSession();
 session.invalidate();
 out.println("<div style='float:left;font-size:25px;'>"+"click here to "
       +"<a href='Login.html'>login</a></div>");
 out.println("<h1 align='center'>"+"Logout Sucessfully..."+"</h1>");
 }finally {            
 out.close();
 }
 }
}



Validate.java
package my.packages;

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Validate extends HttpServlet {

	private static final long serialVersionUID = 1L;

public void doPost(HttpServletRequest request,HttpServletResponse 
 response) 
      throws ServletException,IOException
{
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
  try{
    String name=request.getParameter("uid");
    String pass=request.getParameter("pid");
    Class.forName("com.mysql.jdbc.Driver");
    Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","");
 Statement s=con.createStatement();
ResultSet rs=s.executeQuery("select * from log where user='"+name+"' ");

   if(rs.next())
      {
               
 if( (name.trim().equals(rs.getString(1).trim())) && (   
       pass.trim().equals(rs.getString(2).trim()) )  )
    {

//New session creation
  HttpSession session=request.getSession(true);
  //setting attribute on session
  session.setAttribute("user",name);
 //send request to Welcome.jsp page

RequestDispatcher view =   
      request.getRequestDispatcher("Welcome.jsp");
       
view.forward(request, response);
                
   }
  else
    {
 out.println("<div style='font-size:30px; color:red'>"
          +"Userid and password does not matched "+"</div>");
 RequestDispatcher view =
    request.getRequestDispatcher("Login.html");
    
view.include(request, response);
         }
      }
 else
  {
 out.println("<div style='font-size:30px; color:red'> Please fill userid and password </div>");
 RequestDispatcher view=request.getRequestDispatcher("Login.html");
    view.include(request, response);
   }
     }catch(Exception e){}
     finally{
     out.close();
 }
 }
}




Welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>
<%@ page import="javax.servlet.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<% String name=(String)session.getAttribute("user"); %>
<% java.util.Date cr=new java.util.Date (session.getCreationTime()); %>
<% java.util.Date lr=new java.util.Date (session.getLastAccessedTime()); %>
<div style="font-size:25px;">Click here to <a href="Logout">Logout</a></div>
<center>
<div style="font-size:30px;">
<div>Hello <%=name %></div>
<div>Login time:<%=cr %></div>
<div>Last Accessed Time:<%=lr %></div>
</div></center>

</body>
</html>



Thanks guys,
Was This Post Helpful? 0
  • +
  • -

#7 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Browser Back Button or My Code in Servlet

Posted 31 August 2013 - 01:39 AM

Quote

To fix your current issue, just add the response headers, no sessioning needed.


You haven't added the response headers.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1