Friday, June 21, 2019

Request Dispatcher Servlet example in creating simple Login Form


Use Request Dispatcher Servlet in creating simple Login Form


We are going to create a Login Form Here. At the end of this section, you will be able to use Request Dispatcher Servlet to forward the request to another webpage based on your inputs.


Let us Start Step by Step:

Step 1: 


Create a Dynamic Web Project in IDE. For Example, here I am using eclipse to create a Dynamic Web Project.

If you do not have eclipse use below link to download the eclipse for Enterprise Edition.:
https://www.eclipse.org/downloads/packages/release/kepler/sr2/eclipse-ide-java-ee-developers






Give Proper Name to your project according to you.

Here in the Target runtime (Picture below), you can see Apache Tomcat v8.5. It is Server which is required to run Dynamic Web Applications or Enterprise Applications.


If it is not present or shown Empty then you have to Download the Server
i.e Apache Tomcat or Weblogic or any other server and have to link in the New RunTime Button Link.





Next Click on Next and Finish.


Below is the Final Structure of the project.





You need to create below files:


1. Login and Success Servlet Class.


2. home and success.jsp for the login page and if credentials are correct then forward it to the success page.



Step 2:


Create home.jsp file under webContent.








Content of home.jsp file.

It contains the code for Simple Login Form.

<form action="Login" method="post">

Here action means when user submit this form then Login Servlet will be invoked and it find the post method in the Login Servlet


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

      <h1>Login form</h1>
      <div>
            <form action="Login" method="post">
                  <table>
                        <tr>
                              <td>Name :</td>
                 <td><input type="text" name="userName" />                                  </td>
                        </tr>
                        <tr>
                              <td>Password :</td>
                <td><input type="password" name="userPass"/></td>
                        </tr>
                        <tr>
                 <td><input type="submit" value="login" /></td>
                        </tr>
                  </table>
            </form>
      </div>

</body>

</html>

home.jsp file snapshot





Step 3:


Create Login.java Servlet











Login Servlet:


package com.studyskymate.dinesh.servlet.login;

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

import javax.servlet.RequestDispatcher;
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("/Login")
public class Login extends HttpServlet {
      private static final long serialVersionUID = 1L;
      
    public Login() {
        super();
    }

      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           
             response.setContentType("text/html"); 
             PrintWriter out = response.getWriter(); 
             String name=request.getParameter("userName"); 
             String password=request.getParameter("userPass"); 
             
       if(name.equals("dinesh") && password.contentEquals("1234") )               {
        RequestDispatcher rd  =request.getRequestDispatcher("success");

    //To handle it you need to create success servlet which we will create in next step
         rd.forward(request, response);
        }else {
       out.print("Sorry Invalid UserName or Password !");
       RequestDispatcher rd=request.getRequestDispatcher("/home.jsp");
           rd.include(request, response);
             }
             
      }


}


----------------------------------------------------------------------------------------------------------

Step 4
Create Success.java Servlet Similarly:

It will Invoke Login Servlet and if username and password are correct then it will forward the request to Success.jsp

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

import javax.servlet.RequestDispatcher;
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("/success")
public class Success extends HttpServlet {
      private static final long serialVersionUID = 1L;

    public Success() {
        super();
    }


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

          response.setContentType("text/html");
          PrintWriter out= response.getWriter();
      RequestDispatcher rd=request.getRequestDispatcher("/success.jsp");
          rd.forward(request, response);
      }


}

-----------------------------------------------------------------------------------------------------------------


Step 5.

Create success.jsp to capture the response from Success Servlet.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<div>
<h1>Welcome   <font color="red"><%=request.getParameter("userName") %> </font> </h1>
<h2>You are Valid User</h2>
<a href="/WebProject/home.jsp"><button type="button">Home Page</button></a>
</div>

</body>
</html>


----------------------------------------------------------------------


Step 6

web.xml file.

6.1 create web.xml file under WEB-INF folder if not present.
6.2 Add welcome file home.jsp or your index file statement in the web.xml
as below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>WebProject</display-name>
  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>
</web-app>


--------------------------------------------------------------------


Step 7: 
Run your project on Server.










Below Login Form will open after running the server at your browser.






Enter the correct Username and password.
In my case, it is dinesh and 1234 because I have provided these validations in Login Servet.
Now It will Invoke Login Servlet and if username and password is correct then it will forward the request to Successjsp






In the case of Wrong credentials, it will include the output of login servlet and forward the request to home.jsp




Thanks



No comments:

Post a Comment

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > <...

Followers

Search This Blog

Popular Posts