User Login in JSP

Every website and software in the world is having login facility. Login gives access rights to user and defines their role in website and application. Nobody can access website if they failure in proving their identity on website or application.
Registration is first step by login to website. We will keep focus on only user login in JSP.

User login contain two fields, first one important User ID. This is unique ID provided by site owner or software application itself or most of provide facility to choose user id themselves on their website of web application.

Second is password, it is secret field and user have to keep remember without sharing with anybody. This field gives authentication to user to login on the website. User ID and password keep isolate one user to other users.

We have three forms of JSP pages.

login.jsp take input from user, mainly user id and password then submitted to server for further processing. This process handles with database. Database has a SQL table name usermaster. Usermaster table is having number of fields which are not using in login process. We need user id, password, user type, user level, first name, last name.
User type field in database explain user type as e.g. admin role, power user role, moderator role, end user role. User levels field explain about permission defined to user. Read, write, update, view are permission on user can work accordingly to these permission. This certainly is not using in current login facility. This can be useful after user login successfully and work in application.

SQL usermaster Table

CREATE TABLE `usermaster` (
  `sUserID` varchar(45) NOT NULL,
  `sEmail` varchar(250) NOT NULL,
  `sFirstName` varchar(45) NOT NULL,
  `sLastName` varchar(45) NOT NULL,
  `iDOB` datetime NOT NULL,
  `cGender` varchar(45) NOT NULL,
  `iCountryID` int(10) unsigned NOT NULL,
  `iCityID` varchar(45) NOT NULL,
  `iUserType` varchar(45) DEFAULT NULL,
  `iUserLevel` varchar(45) DEFAULT NULL,
  `sPassword` varchar(45) NOT NULL,
  `sForgetPassword` varchar(45) DEFAULT NULL,
  `sContact` bigint(20) unsigned NOT NULL,
  `sCreatedBy` varchar(45) DEFAULT NULL,
  `dCreatedDate` datetime DEFAULT NULL,
  `sModifiedBy` varchar(45) DEFAULT NULL,
  `sModifiedDate` datetime DEFAULT NULL,
  `sStatus` varchar(45) NOT NULL,
  PRIMARY KEY (`sUserID`),
  UNIQUE KEY `sEmail` (`sEmail`)
);

login.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%
String error=request.getParameter("error");
if(error==null || error=="null"){
 error="";
}
%>
<html>
<head>
<title>User Login JSP</title>
<script>
    function trim(s) 
    {
        return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
    }

    function validate()
    {
        if(trim(document.frmLogin.sUserName.value)=="")
        {
          alert("Login empty");
          document.frmLogin.sUserName.focus();
          return false;
        }
        else if(trim(document.frmLogin.sPwd.value)=="")
        {
          alert("password empty");
          document.frmLogin.sPwd.focus();
          return false;
        }
    }
</script>
</head>

<body>
<div><%=error%></div>
<form name="frmLogin" onSubmit="return validate();" action="doLogin.jsp" method="post">
User Name <input type="text" name="sUserName" /><br />
Password <input type="password" name="sPwd" /><br />
<input type="submit" name="sSubmit" value="Submit" />
</form>
</body>
</html>

 

doLogin.jsp mainly deals with database to check user id and password is matched with user trying to provide to get access from the server.

Our password field is encrypted with mysql password function. To decrypt password we have to use mysql password function again. If you are using Oracle or other database password function come with different name. Only user knows exact password and anybody can find out real password of the user. This increases the security of the system and reduces the hacking.

doLogin.jsp

<%@ page language="java" import="java.sql.*" errorPage="" %>
<%

    Connection conn = null;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root", "");
    
    ResultSet rsdoLogin = null;
    PreparedStatement psdoLogin=null;
    
    String sUserID=request.getParameter("sUserName");
    String sPassword=request.getParameter("sPwd");
    String message="User login successfully ";
    
    try{
    String sqlOption="SELECT * FROM usermaster where"
                    +" sUserID=? and sPassword=password(?) and sStatus='A'";
    
    psdoLogin=conn.prepareStatement(sqlOption);
    psdoLogin.setString(1,sUserID);
    psdoLogin.setString(2,sPassword);
    
    rsdoLogin=psdoLogin.executeQuery();
    
    if(rsdoLogin.next())
    {
      String sUserName=rsdoLogin.getString("sFirstName")+" "+rsdoLogin.getString("sLastName");
     
      session.setAttribute("sUserID",rsdoLogin.getString("sUserID"));
      session.setAttribute("iUserType",rsdoLogin.getString("iUserType"));
      session.setAttribute("iUserLevel",rsdoLogin.getString("iUserLevel"));
      session.setAttribute("sUserName",sUserName);
     
      response.sendRedirect("success.jsp?error="+message);
    }
    else
    {
      message="No user or password matched" ;
      response.sendRedirect("login.jsp?error="+message);
    }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    
    
    /// close object and connection
    try{
         if(psdoLogin!=null){
             psdoLogin.close();
         }
         if(rsdoLogin!=null){
             rsdoLogin.close();
         }
         
         if(conn!=null){
          conn.close();
         }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

%>

doLogin.jsp match user id and password with database record. If record is matched with user field and password. It will set user id, user type, user level, first name, last name in session. This can access from session in further in application. It will finish processing and return to success.jsp page.

success.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java"%>
<html>
<head>
<title>Successfully Login by JSP</title>
</head>

<body>
Successfully login by JSP<br />
Session Value<br />
<%
out.print("UserName :"+session.getAttribute("sUserID")+"<br>");
out.print("First & Last Name :"+session.getAttribute("sUserName"));
%>
</body>
</html>

If user id and password is not matched, it will return back to login.jsp page and print error message to user, user id and password is not matched.

The example of login is given with source code, login.jsp, doLogin.jsp and success.jsp.

Bookmark  

 

22 Responses to “User Login in JSP”

  1. ara says:

    this is the warning .

    “No user or password matched”

    how the solve ? my database i’, already import username and password .

    thx :)

  2. bouritos says:

    any response for above problem???

  3. rohan says:

    “No user or password matched”

    This message prints when user name and password do not match with each other. If you sure user name and password you entered are correct, then this may be problem of “password()” function mysql.

    either you are using old password of mysql.
    you can change it by my.cnf of mysql old_password=0

  4. sad_man says:

    Class.forName(”com.mysql.jdbc.Driver”).newInstance();

    i keep on getting error for the above coding. pls help

  5. phani kumar says:

    thankssssssssssssssss

    my problem was solved…..

  6. vishard says:

    hii
    in project which i directly enter values to database during comparison it is doing good.

    but when i try to insert values from form by “insert into * value()”compare it, entry is going into database BUT on comparison it does not compare it. is there some kind of conversion i have to do or not.

    my database fields are of varchar();

  7. amita says:

    String sqlOption=”SELECT * FROM usermaster where”
    +” sUserID=? and sPassword=password(?) and sStatus=’A'”;

    password() mysql function convert normal string text into a encrypted string

    try to check select password(’test’) query’s output

  8. kaolei says:

    thankssssssssssssssss

    my problem was solved….. too.

    and more

    How to “Logout”

  9. Anis says:

    Hello,
    I accessed the first time to login.jsp with a good username/password (username is anix1), after that I accessed with a wrong couple username/password. In a third time, I tried to access to success.jsp, it outputs :
    Successfully login by JSP
    Session Value
    UserName :anix1
    How to deal with this problem
    thank you

  10. Anis says:

    Hello,
    Now it is ok for me, I used
    session.removeAttribute(\\&quot;sUserID\\&quot;);
    session.invalidate();
    in the beginning of login.jsp
    and
    session = request.getSession(false);
    if(session != null &amp;&amp; session.getAttribute(\\&quot;sUserID\\&quot;)!=null)
    in the beginning of success.jsp
    all you improvements are welcome
    Thanks

  11. Paolo says:

    how to use cookies here?

    and I want ask , if i use oracle 10g what is configuration for conn statement?
    conn = DriverManager.getConnection (?????????)

    thanks.

  12. Susana says:

    Very good

  13. vignesh says:

    In jsp When i logging in the web page ist directed to intended page it remains at the same page after loading it doest throw any error tooo….pls let me knw…….

  14. OZZYCOCA says:

    Could u pls explai how to deal with the connection issue when you are using MS access…thanks

  15. sumit says:

    in doLogin.jsp

    correct this …

    String sqlOption=”SELECT * FROM usermaster where”
    +” sUserID=? and sPassword=? and sStatus=’A'”;

  16. Pankaj says:

    String sqlOption=”SELECT * FROM usermaster where”
    +” sUserID=? and sPassword=password(?) and sStatus=’A'”;

    this is fine I donot see any problem on this. sPassword=password(?) is mysql command no problem with it

    =correct this …

    =String sqlOption=”SELECT * FROM usermaster where”
    =+” sUserID=? and sPassword=? and sStatus=’A’”;

  17. kingGe says:

    Thank you so much….

    It helped me alot.

  18. hIUG says:

    hi there:

    I’ve tried this example but i get the “No user or password matched” message even when i writte a correct username/password. I’ve also tried to sustitute:

    String sqlOption=”SELECT * FROM usermaster where”
    +” sUserID=? and sPassword=password(?) and sStatus=’A’”;

    with this:

    String sqlOption=”SELECT * FROM usermaster where”
    +” sUserID=? and sPassword=? and sStatus=’A’”;

    But it doesn’t work aniway…

    How can i solve this?????

  19. anuj says:

    can you tell me that which mysql you are using and operating system.

    Linux operation system’s mysql use old password. You need to configure mysql my.ini or my.cnf file in /etc/ folder.

  20. Sheeyla says:

    Good code! thanks it worked pretty well for me!

  21. Sheeyla says:

    How can I use the UserLevel attribute in accessing following pages?

    I have my database with user roles like “admin” or “limitado”… If a user clicks on a page I don´t want them to see, how can I stop them by using the UserLevel attribute?

    Thanks

  22. ivan says:

    i still got error after write this code, in file doLogin.

    how to solve this problem ?

Leave a Reply

Security Code:

 

  Random Post