Simple Login Authentication Application with Session using JSP / JSTL


Notice: Undefined offset: 0 in /home/techtofu/public_html/wp-content/plugins/download-manager/wpdm-functions.php on line 374

Download the Netbeans project –


This is a very basic example on how to login and logout with JSP using session. I did this on Netbeans 7.3.1 in Linux ubuntu 13.10.
Requirements
1. Netbeans 7.3.1
2. mysql server installed (Check how to install mysql server in linux )

Follow these steps –
1. Create a database in mysql of name “test”

create database test;

2. Create a table in “test” database of name “users”

create table users(
     user_id varchar (50),
     password varchar (50),
     fname varchar (50),
     lname varchar (50),
     email varchar (50),
     primary key(user_id));

3. Insert data in users table
Default ID is “amma” and password is “amma123”. Use this data for login.

insert into users values('amma','amma123','Ram','Sharma','techtofun@gmail.com');

Now open your Netbens. Create a new web project and make sure that your database is connected to mysql server. Select the “test” database in you Netbeans and establish connection.

4. index.html
Create a file “index.html” in Netbeans and paste the code given below. This page contains link to login.html and reg.html page.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>ml 
    <body>
        <a href="login.html">Login</a><br/>
        <a href="reg.html">Registration</a>
    </body>
</html>

5. login.html
Create a file “login.html” in Netbeans and paste the code given below. In this page user gives his ID and password

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form action="login.jsp" method="post">
            Id : <input type="text" name="id"/>
            password :<input type="password" name="pwd" />
            <input type="submit" />
        </form>
    </body>
</html>

6. login.jsp
Create a file “login.jsp” in Netbeans and paste the code given below. This page check the ID and password given by user in login.html page, with the ID and passwords stored in database. If ID and password matches then user transfered to FirstPage.jsp .

<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%
String id=request.getParameter("id");
String pwd=request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = 
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","amma");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from users where user_id='"+id+"'");
if(rs.next())
{
if(rs.getString(2).equals(pwd))
{
session.setAttribute("userid", id);
response.sendRedirect("FirstPage.jsp");
}
else
{
out.println("Invalid ID/Password <a href='index.html'>try again</a>");
}
}
%>

In getCoonnection() “test” is my database name, “root” is my user name in mysql and “amma” is my password for root user in mysql.

DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","amma");

7. FirstPage.jsp
Create a file “FirstPage.jsp” in Netbeans and paste the code given below. User enters this page if he successfully login.

<%
    out.println("first page");
    if((session.getAttribute("userid")== null ) || (session.getAttribute("userid")== "")){
     %>You are not logged in</br>
    <a href="login.html">Please Login</a>   
   <% } else {
        %>
        Welcome <%=session.getAttribute("userid") %>
        <a href="logout.jsp">Log out</a>
        <%
        }
    %>

8. reg.html
Create a file “reg.html” in Netbeans and paste the code given below. This page contains the fields for user to register a new account.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form action="reg.jsp" method="post">
            Id : <input type="text" name="id"/>
            Password :<input type="password" name="pwd" />
            Email :<input type="text" name="email" />
            First name :<input type="text" name="fname" />
            Last name :<input type="text" name="lname" />
            
            <input type="submit" />

        </form>
    </body>
</html>

9. reg.jsp
Create a file “reg.jsp” in Netbeans and paste the code given below. In this page details get stored in database provided by user in reg.html page .

<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%
String id=request.getParameter("id");
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
out.println(id);
out.println(pwd);
out.println(fname);
out.println(lname);
out.println(email);
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = 
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","amma");
Statement st= con.createStatement();
ResultSet rs;
PreparedStatement pst;
pst=con.prepareStatement("insert into users(user_id,password,fname,lname,email) VALUES (?, ?, ?, ?,?)");
pst.setString(1,id);
pst.setString(2,pwd);
pst.setString(3,fname);
pst.setString(4,lname);
pst.setString(5,email);

int i= pst.executeUpdate();
pst.clearParameters();
if(i>0){
    response.sendRedirect("welcome.jsp");
}else{
    response.sendRedirect("index.html");
}
%>

10. welcome.jsp
Create a file “welcome.jsp” in Netbeans and paste the code given below.

<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%
out.println("Registration is Successful."); 
out.println("Please Login Here <a href='login.html'>Go to Login</a>");
%>

11. logout.jsp
Create a file “logout.jsp” in Netbeans and paste the code given below. This page logs out user and destroy the session.

<%
session.setAttribute("userid", null);
session.invalidate();
response.sendRedirect("index.html");
%>

Download the Netbeans project –
After downloading the project. Extract the zip file and store the extracted folder in Netbeans project folder. In the “reg.jsp” and “login.jsp” file change the user name and password to your computer mysql database user name and password.

4 comments on “Simple Login Authentication Application with Session using JSP / JSTL

  1. BHargavi

    This code is working properly thanq………. so much for u
    I was new to jsp it helps me learn

    Reply
  2. anurag

    code is very simple and self-explanatory.thanks. but 1 thing, everything is working fine but if i enter wrong credentials while logging, nothing happens – just a blank page is displayed instead of the FirstPage.jsp

    Reply
  3. S lakshmikanth reddy

    in the same code i want to place forgot password and i want to get or to change password can you send me the code

    Reply
    1. robin Post author

      Hello,
      I have provided you the basic code, you can enhance it in anyway you want. If you get stuck somewhere then you can always ask me.
      Thanks,
      Robin

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *