Showing posts with label Servlet. Show all posts
Showing posts with label Servlet. Show all posts

Login application using jsp servlet and mysql database

Today we are going to create a simple web login application using JSP, servlet and mysql database. In order to create an application we are going to use the following software.

  1. MySql database
  2. Eclipse IDE
  3. Tomcat server
Firstly, lets create a database and a table in mysql. Turn on the database connection and open the mysql command prompt and paste the below code.

create database form;

use form;

CREATE  TABLE `form`.`login` (
  `user` VARCHAR(20) NOT NULL ,
  `password` VARCHAR(20) NOT NULL ,
  PRIMARY KEY (`user`) ); 
INSERT INTO `form`.`login` (`user`, `password`) VALUES ('Admin', 'passw0rd');

Now, open up the Eclipse IDE and create a dynamic web project and create the project structure as per the screen shot below.



Lets create the front end with two basic jsp pages.

index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
</head>
<body>
    <form action="loginServlet" method="post">
        <fieldset style="width: 300px">
            <legend> Login to App </legend>
            <table>
                <tr>
                    <td>User ID</td>
                    <td><input type="text" name="username" required="required" /></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="userpass" required="required" /></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login" /></td>
                </tr>
            </table>
        </fieldset>
    </form>
</body>
</html>


welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
    <h3>Login successful!!!</h3>
    <h4>
        Hello,
        <%=session.getAttribute("name")%></h4>
</body>
</html>


Now, lets create the login DAO which will enable us to connect our login application with mysql database and execute the query to the DB.

LoginDao.java
package com.amzi.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginDao {
    public static boolean validate(String name, String pass) {        
        boolean status = false;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "form";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "password";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager
                    .getConnection(url + dbName, userName, password);

            pst = conn
                    .prepareStatement("select * from login where user=? and password=?");
            pst.setString(1, name);
            pst.setString(2, pass);

            rs = pst.executeQuery();
            status = rs.next();

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (pst != null) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return status;
    }
}


Now, we are going to create the servlet which will capture the input parameter from the jsp and validate it against the LoginDao.

LoginServlet.java
package com.amzi.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
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 com.amzi.dao.LoginDao;

public class LoginServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

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

        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
        
        String n=request.getParameter("username");  
        String p=request.getParameter("userpass"); 
        
        HttpSession session = request.getSession(false);
        if(session!=null)
        session.setAttribute("name", n);

        if(LoginDao.validate(n, p)){  
            RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");  
            rd.forward(request,response);  
        }  
        else{  
            out.print("<p style=\"color:red\">Sorry username or password error</p>");  
            RequestDispatcher rd=request.getRequestDispatcher("index.jsp");  
            rd.include(request,response);  
        }  

        out.close();  
    }  
} 


Finally, lets configure the web.xml file for servlet and welcome file configuration.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
    version="2.5">
    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.amzi.servlets.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/loginServlet</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


That's all it takes to create a simple web login application. This is not the ideal login application as it needs lot of modification such as security etc. Anyways, for now let's run the project on the tomcat server and test the application.



Now, let's input the invalid data and check the result.



Now, I am using the correct credentials which will match with the database result and redirect the page to the welcome file.

Note: The URL is internally redirecting the page to the welcome.jsp file since we are using the forward method. If instead we would have used redirect method, in that case we can see the request URL in the browser.


Download Code

Upload image file into database using java servlet, jdbc and mysql

In this example we are going to create a project which will enable users to upload the image into the database.
First of all turn on mysql database connection and open the mysql command line and paste the following sql script and create the new database as well as table.

create database AppDB;

use AppDB;

CREATE TABLE `contacts` (
  `contact_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `photo` mediumblob,
  PRIMARY KEY (`contact_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1


Now, lets create a dynamic web project into the eclipse and design the structure as follows:



Now, let's create the front end using the jsp pages.
uploadImage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
    <h1>Upload any image to mysql DB</h1>
    <form method="post" action="fileUpload"
        enctype="multipart/form-data">
        <table>
            <tr>
                <td>First Name:</td>
                <td><input type="text" name="firstName" size="10"
                    required="required" /></td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td><input type="text" name="lastName" size="10"
                    required="required" /></td>
            </tr>
            <tr>
                <td>Choose Image:</td>
                <td><input type="file" name="photo" size="10"
                    required="required" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="Submit"></td>
                <td><input type="reset" value="Clear" /></td>
            </tr>
        </table>
    </form>
</body>
</html>


submit.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success</title>
</head>
<body>
    <h3><%=request.getAttribute("Message")%></h3>
</body>
</html>


db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/AppDB
user=root
password=password 


DbUtil.java

package com.amzi.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DbUtil {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null)
            return connection;
        else {
            try {
                Properties prop = new Properties();
                InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("/db.properties");
                prop.load(inputStream);
                String driver = prop.getProperty("driver");
                String url = prop.getProperty("url");
                String user = prop.getProperty("user");
                String password = prop.getProperty("password");
                Class.forName(driver);
                connection = DriverManager.getConnection(url, user, password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return connection;
        }

    }
}


UploadServlet.java

package com.amzi.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.amzi.util.DbUtil;

@WebServlet("/fileUpload")
@MultipartConfig(maxFileSize = 16177215) // upload file up to 16MB
public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = -1623656324694499109L;
    private Connection conn;

    public UploadServlet() {
        conn = DbUtil.getConnection();
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        // gets values of text fields
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");

        InputStream inputStream = null;

        // obtains the upload file part in this multipart request
        Part filePart = request.getPart("photo");
        if (filePart != null) {
            // debug messages
            System.out.println(filePart.getName());
            System.out.println(filePart.getSize());
            System.out.println(filePart.getContentType());

            // obtains input stream of the upload file
            inputStream = filePart.getInputStream();
        }

        String message = null; // message will be sent back to client

        try {
            // constructs SQL statement
            String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, firstName);
            statement.setString(2, lastName);

            if (inputStream != null) {
                // fetches input stream of the upload file for the blob column
                statement.setBlob(3, inputStream);
            }

            // sends the statement to the database server
            int row = statement.executeUpdate();
            if (row > 0) {
                message = "Image is uploaded successfully into the Database";
            }
        } catch (SQLException ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        }
        // sets the message in request scope
        request.setAttribute("Message", message);

        // forwards to the message page
        getServletContext().getRequestDispatcher("/submit.jsp").forward(
                request, response);
    }
}


Now, we are ready to run the project and once we run the project we are able to view the following result.





Click here to download the code.

You may also like...

Check username availability using Java, JSP, AJAX, MySQL, JDBC, Servlet

Login application using jsp servlet and mysql database

JSF login and register application

 

 

Redirect request from servlet using sendRedirect method

In this example we are going to understand the method sendRedirect which is available in HttpServletResponse object. This method will take a String value as an input parameter. Essentially this String can be Servlet, jsp or html page. Checkout the example below for batter understanding.

Create a dynamic web project in your Eclipse IDE. Under src folder create two java servlets as defined below.

DemoServlet.java

package com.java.servlets;

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

@WebServlet("/Demo")//This is url pattern for this servlet
//Servlet 3.0 doesn't require to be mapped in web.xml
public class DemoServlet extends HttpServlet {

    private static final long serialVersionUID = -4111596859324406153L;

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
       
        System.out.println("Inside DemoServlet doGet method");
        //Calling servlet which has the name testing
        res.sendRedirect("testing");
    }
}


TestingServlet.java

package com.java.servlets;

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

@WebServlet("/testing")//This is url pattern for this servlet
public class TestingServlet extends HttpServlet {

    private static final long serialVersionUID = -4111596859324406153L;

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        System.out.println("Inside TestingServlet doGet method");
        res.sendRedirect("http://www.google.com");
        //or this can be any jsp or html page created under WebContent folder
        //res.sendRedirect("index.jsp");
    }
}


We don't need web.xml configuration as we are using servlet 3.0. So, once you done coding you can go ahead and deploy the project on the server and hit the below url on your browser.

http://localhost:8080/HelloWorld/Demo

As soon as we hit the url first of all the Demo servlet is going to be invoked. Now, Demo servlet is calling the testing servlet using sendRedirect method in it. Therefore, testing servlet is going to be invoked in next step. Again this servlet also has sendRedirect method in it and that is calling the google homepage so, finally the page is going to be redirected to the google home page.
Note: In the end result the browser url is going to be changed to the google url.

Servlet JSP based login example

Here, we are gonna build a login screen which will take the hardcoded username and password value from servlet.

Before we proceed make sure you have following software up and running.
  1. Eclipse IDE
  2. Tomcat server
First of all, create the dynamic web project on your Eclipse IDE and under WebContent folder create a new jsp file and name it login.jsp

login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Login Page</title>
</head>
<body>
    <form action="TestServlet" method="post">
        <fieldset>
            <legend>User login</legend>
            <table>
                <tr>
                    <td>User Name:</td>
                    <td><input type="text" name="user" /></td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td><input type="password" name="pass" /></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login" /></td>
                </tr>
            </table>
        </fieldset>
    </form>
</body>
</html>


Upon successful login we are going to redirect the page to the success page. So, lets create the success page.

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Success Page</title>
</head>
<body>
    <h1 align="center">Welcome to the world of servlets!</h1>
    <h3 align="center" style="color: blue">Created by Amzi...</h3>
</body>
</html>


Now, lets create a servlet which will handle the client request. For this particular example only the doPost method is required however, I am writing doGet, init and destroy method as well just for the sake of batter understanding of the example. Under the src folder lets create the new servlet.

TestServlet.java

package com.java.amzi;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String redirect = "test.jsp";
    private static final String success = "success.jsp";

    public TestServlet() {
        super();
        System.out.println("Inside the constructor of the servlet");
    }

    public void init(ServletConfig config) throws ServletException {
        System.out.println("In the init method!");
    }

    public void destroy() {
        System.out.println("The destroy method is called!");
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        System.out.println("Inside the doGet method");
        String user = request.getParameter("user");
        System.out.println(user);
        String pass = request.getParameter("pass");
        
        if (user.equals("Admin") && pass.equalsIgnoreCase("passw0rd"))
            response.sendRedirect(success);
        else {
            System.out.println("inside the else part");
            response.sendRedirect(redirect);
        }
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Inside the doPost method");
        doGet(request, response);
    }
}


That is all required to run this example so, now go ahead and deploy the project on your tomcat server and the screen will look as per below sceenshot.



Enter the correct username and password

Now have a look at the console.


Related Post:

Login application using jsp servlet and mysql database 

JSF login and register application

 

Check username availability using Java, JSP, AJAX, MySQL, JDBC, Servlet


Hey guys, today we are gonna be developing the username availability application based on the real world scenario and using the technologies which are used across almost all the major IT firms.

Before we begin writing the code I'd assume that you guys have following software installed.

  1. Eclipse IDE
  2. Tomcat app server
  3. MySQL Database


Alright, first of all we are going to start the DB and will create the database and the table. After that we can enter some test values. Check the script below.
MySQL Script:
create database students;

create table users(
 uid int primary key 
        auto_increment,
 uname varchar(20) unique
 );

INSERT INTO `students`.`users` 
(`uid`, `uname`) VALUES ('1', 
'Amjad');INSERT INTO 
`students`.`users` (`uid`, 
`uname`) VALUES ('2', 'Amzi');


Create a dynamic web project in your IDE workspace and the project structure should look something like this.

Next are going to create the view using jsp, the view will consist of a simple text box which will check if the input string value is 3 character long or not. If yes then it will go ahead and make a query and will check the availability of the username.

index.jsp


Username Availability


 


 
 


Now, we are going to write a servlet which will create a database connection and make a query to it.
CheckAvailability.java
package com.amzi.servlets;

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

public class CheckAvailability extends HttpServlet {

 private static final long serialVersionUID = -734503860925086969L;

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String connectionURL = "jdbc:mysql://localhost:3306/students"; // students is my database name
            Connection connection = null;
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(connectionURL, "root", "password");
            String uname = request.getParameter("uname");
            PreparedStatement ps = connection.prepareStatement("select uname from users where uname=?");
            ps.setString(1,uname);
            ResultSet rs = ps.executeQuery();
             
            if (!rs.next()) {
                out.println(""+uname+" is avaliable");
            }
            else{
            out.println(""+uname+" is already in use");
            }
            out.println();

        } catch (Exception ex) {
            out.println("Error ->" + ex.getMessage());
        } finally {
            out.close();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}


Also, we can configure the deployment descriptor as follows.
web.xml


    
        check
        com.amzi.servlets.CheckAvailability
    
    
        check
        /check
    
    
        
            30
        
    
    
        index.jsp
        
    


Note: In addition to these code we also need jquery library and mysql connector jar file. Just in case you are unable to find those, you may click here to get the complete source code.

Now, we are all set to deploy and test the code on the server. We can hit the below url
http://localhost:8080/UserAvailability/
And, the page will look something like this