Total members 11894 |It is currently Fri Nov 22, 2024 12:20 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





 IDE:   Eclipse
 Type:   Login using Jsp
 Programmer:   Jaikiran
 Technology:  Jsp
 Technology:  Servlets
 Description:   This the secure code following MVC architecture to perform login and logout operations of a user by retrieving his data from database
LoginPage.jsp(view of Login Page)
Code:
<%@ page language="java"
    contentType="text/html; charset=windows-1256"
    pageEncoding="windows-1256"
%>
<%
    response.setHeader("Cache-Control","no-store, must-revalidate");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader ("Expires", -1);
    new java.util.Date();
    %>
<!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=windows-1256">
      <script>
function clearForms()
{
  var i;
  for (i = 0; (i < document.forms.length); i++) {
    document.forms[i].reset();
  }
}
function validateForm()
{
var x=document.forms["myForm"]["un"].value;
if (x==null || x=="")
  {
  alert("Username must be filled out");
  document.getElementById('un').focus();
  return false;
  }
var y=document.forms["myForm"]["pw"].value;
if (y==null || y=="")
  {
  alert("password must be filled out");
  document.getElementById('pw').focus();
  return false;
  }
}
</script>
     <title>Login Page</title>
   </head>
    <body onLoad="clearForms()" onunload="clearForms()">
    <form action="LoginServlet" onsubmit="return validateForm()" method="post"  name="myForm">
       Please enter your user name       
      <input type="text" name="un" id="un"/><br>      
      Please enter your password
      <input type="text" name="pw" id="pw"/>
      <input type="submit" value="submit">         
      </form>
   </body>
</html>

invalidLogin.jsp(redirects to this page if wrong credentials)
Code:
<%@ page language="java"
      contentType="text/html; charset=windows-1256"
      pageEncoding="windows-1256"
   %>
   <%
    response.setHeader("Cache-Control","no-store,must-revalidate");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader ("Expires", -1);
    new java.util.Date();
    %>

   <!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=windows-1256">
         <title>Invalid Login</title>
      </head>
   
      <body>
         <center>
            Sorry, you are not a registered user! Please sign up first
         </center>
      </body>
   
   </html>

userLogged.jsp(welcome page after logging in with right credentials)
Code:
<%@ page language="java"
         contentType="text/html; charset=windows-1256"
         pageEncoding="windows-1256"
         import="ExamplePackage.UserBean"
   %>
   <%
    response.setHeader("Cache-Control","no-store,must-revalidate");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader ("Expires", -1);
    new java.util.Date();
    if(session.getAttribute("currentSessionUser")!=null)
    {
    %>
   
   <!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=windows-1256">
         <title>   User Logged Successfully   </title>
         <SCRIPT type="text/javascript">
function noBack() {
   window.history.forward();
   }
</SCRIPT>
      </head>
   
<BODY onload="noBack();">
<a href="LogoutServlet">Logout</a>
         <center>
            <% UserBean currentUser = (UserBean)(session.getAttribute("currentSessionUser"));%>
         
            Welcome <%= currentUser.getFirstName() + " " + currentUser.getLastName() %>
         </center>

      </body>
   
   </html>

<%}
else
response.sendRedirect("LoginPage.jsp");%>


LoginServlet.java(takes input from LoginPage.jsp and controls the flow based on validation with database)
Code:
package ExamplePackage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LoginServlet extends HttpServlet {

private static final long serialVersionUID = 2562294252731783855L;

public void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, java.io.IOException {

try
{      

     UserBean user = new UserBean();
     user.setUserName(request.getParameter("un"));
     user.setPassword(request.getParameter("pw"));
     user = UserDAO.login(user);
               
     if (user.isValid())
     {
          
          HttpSession session = request.getSession(true);      
          session.setAttribute("currentSessionUser",user);
          response.sendRedirect("userLogged.jsp"); //logged-in page            
     }
          
     else
          response.sendRedirect("invalidLogin.jsp"); //error page
}
      
      
catch (Throwable theException)       
{
     System.out.println(theException);
}
       }
   }



UserBean.java(Bean class which holds user data in a bean)
Code:
package ExamplePackage;
public class UserBean {
   
    private String username;
    private String password;
    private String firstName;
    private String lastName;
    public boolean valid;
   
   
    public String getFirstName() {
       return firstName;
   }

    public void setFirstName(String newFirstName) {
       firstName = newFirstName;
   }

   
    public String getLastName() {
       return lastName;
         }

    public void setLastName(String newLastName) {
       lastName = newLastName;
         }
         

    public String getPassword() {
       return password;
   }

    public void setPassword(String newPassword) {
       password = newPassword;
   }
    public void removePassword() {
        password = null;
   }
   
         
    public String getUsername() {
       return username;
         }

    public void setUserName(String newUsername) {
       username = newUsername;
         }
    public void removeUserName() {
        username = null;
         }
    public void removeLastName() {
        lastName = null;
         }
    public void removeFirstName() {
        firstName = null;
         }
            
    public boolean isValid() {
       return valid;
   }

    public void setValid(boolean newValid) {
       valid = newValid;
   }   
}



UserDao.java(which interacts with the database to get the results)

Code:
package ExamplePackage;
import java.sql.*;

public class UserDAO    
{
   static Connection currentCon = null;
   static ResultSet rs = null;     
   public static UserBean login(UserBean bean) {
   
      //preparing some objects for connection
      Statement stmt = null;   
   
      String username = bean.getUsername();   
      String password = bean.getPassword();   
      
      String searchQuery =
            "select * from users where username='"
                     + username
                     + "' AND password='"
                     + password
                     + "'";
      
   // "System.out.println" prints in the console; Normally used to trace the process
   System.out.println("Your user name is " + username);         
   System.out.println("Your password is " + password);
   System.out.println("Query: "+searchQuery);
      
   try
   {
      //connect to DB
      currentCon = ConnectionManager.getConnection();
      stmt=currentCon.createStatement();
      rs = stmt.executeQuery(searchQuery);
      boolean more = rs.next();
      // if user does not exist set the isValid variable to false
      if (!more)
      {
         System.out.println("Sorry, you are not a registered user! Please sign up first");
         bean.setValid(false);
      }
          
      //if user exists set the isValid variable to true
      else if (more)
      {
         String firstName = rs.getString("FirstName");
         String lastName = rs.getString("LastName");
           
         System.out.println("Welcome " + firstName);
         bean.setFirstName(firstName);
         bean.setLastName(lastName);
         bean.setValid(true);
      }
   }

   catch (Exception ex)
   {
      System.out.println("Log In failed: An Exception has occurred! " + ex);
   }
      
   //some exception handling
   finally
   {
      if (rs != null)   {
         try {
            rs.close();
         } catch (Exception e) {}
            rs = null;
         }
   
      if (stmt != null) {
         try {
            stmt.close();
         } catch (Exception e) {}
            stmt = null;
         }
   
      if (currentCon != null) {
         try {
            currentCon.close();
         } catch (Exception e) {
         }

         currentCon = null;
      }
   }

return bean;
   
   }   

}


ConnectionManager.java(to establish a connection to database)
Code:
package ExamplePackage;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionManager {

   static Connection con;
   static String url;
         
   public static Connection getConnection()
   {
     
      try
      {
         String url ="jdbc:oracle:thin:@localhost:1521:XE";

         Class.forName("oracle.jdbc.driver.OracleDriver");
         
         try
         {               
            con = DriverManager.getConnection(url,"*******","*******");
                                     
         }
         
         catch (SQLException ex)
         {
            ex.printStackTrace();
         }
      }

      catch(ClassNotFoundException e)
      {
         System.out.println(e);
      }

   return con;
}
}

LogoutServelt.java(for performing logout operation)
Code:
package ExamplePackage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import ExamplePackage.UserBean;

public class LogoutServlet extends HttpServlet {
   private static final long serialVersionUID = 1L;
   public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, java.io.IOException {

   try
   {      

        UserBean user = new UserBean();
        user.removeUserName();
        user.removePassword();
         HttpSession session=request.getSession(false);
         session.removeAttribute("currentSessionUser");
         session.invalidate();
         response.sendRedirect("LoginPage.jsp");
   }      
   catch (Throwable theException)       
   {
        System.out.println(theException);
   }
  }
}






Author:
Newbie
User avatar Posts: 2
Have thanks: 0 time
Post new topic Reply to topic  [ 1 post ] 

  Related Posts  to : Login using jsp,Servlets and Database following MVC
 develop a login page- login servlet - ServletContext     -  
 How does JSP differ from Servlets?!!!     -  
 material of jsp and servlets     -  
 Servlets how to upload Files     -  
 Displaying Images using servlets     -  
 What is the terms applets and servlets mean?     -  
 help for making web pages using servlets     -  
 Data Access Object in Servlets.............     -  
 Guest Book Application Using Servlets     -  
 Servlets/JSP Website search page example     -  



Topic Tags

Servlets/JSP






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com