Open In App

Servlet – Form

Last Updated : 02 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A web page is the combination of many input elements such as label, text box, checkbox, options, images, etc., It can be prepared by enclosing all the input elements inside an “HTML FORM” on the server-side with java servlet. Usually, an HTML form collects data from the user via these input elements and lets us see how they will be sent to the server-side by using HTTP GET/POST methods.

Flow:

  1. Request will be sent from HTML form
  2. It will be sent as either GET/POST method in the Java servlet side
  3. Response will be provided from servlet as an HTML form

Following tags need to be known to handle the flow

Tag Name

Usage

<Form> To create a form in an HTML page and it encloses all the input elements.
<input> To create a text box or password or submit etc.,
<select> To create dropdown 
<textarea> To create a textarea

Along with the form tag, we have to specify the method either as “GET” or “POST”. Usually sensitive data has to be passed as “POST” because, in the URL, the parameters are not sent as query parameters. Hence for sending sensitive information like “Password”, “Post” method is the good approach. Moreover 

  • In the “Post” method, we can pass many parameters.
  • Post methods are not bookmarked
  • There is no possibility of remaining in the browser history and also cannot be cached and hence safer

“POST” method is used to create or update the resources

POST /<formname.html> HTTP/1.1  <!-- It can be a jsp or any frontend application -->

HOST : <Your ipaddress or host name>
param1=value1&param2=value2

“Get” method is best suited if we are passing only limited parameters and moreover as the parameters are seen outside, it is not well suited for sending sensitive parameters

GET /<forname.html>?param1=value1&param2=value2 <!-- It can be a jsp or any frontend application -->
  • The “Get” method can be cached, bookmarked, and remain in history
  • It is not suitable for sending sensitive information and also it has length restrictions
  • It is generally used to retrieve a certain set of data.

Additionally, along with the form tag, we need to set the action tag. It will contain the “URL of the servlet”

1. name 
method=”GET/POST”: Used to send the form data as an HTTP POST/GET request to the server. 
Generally, form submission containing sensitive data should be done in HTTP POST method.

2. action=”URL of the servlet”: Used to specify relative URL of the servlet 
and it  is responsible for collecting form data and process accordingly.

Sample snippet of the form data;

HTML




<form name="<name of the form>" method="get/post" action="<formServlet>">
    EmailId: <input type="text" name="emailID"/> <br/>
    Password: <input type="password" name="yourPassword"/> <br/>
    <input type="submit" value="NEXT" />
</form>


We can beautify a form by means of CSS (Cascading StyleSheet) and also validate the form by means of Javascript. Client-side validations are handled in javascript. Let us do this for a sample login form. As we need to handle the validation, we can have the inputs via a JSP file

register.jsp

HTML




<%@ 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>Registration Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1;}
  
input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
  
button {
  background-color: #04AA6D;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
}
  
button:hover {
  opacity: 0.8;
}
  
.cancelbutton {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}
  
.container {
  padding: 16px;
}
  
span.psw {
  float: right;
  padding-top: 16px;
}
.seldiv {
  background: #04AA6D;
  height: 50px;
  width:200px;
  border-radius: 15px;
  padding:20px;
  font-size:22px;
  color:#fff;  
}
  
.optiondiv {
  background: #04AA6D;
  height: 120px;
  width:400px;
  border-radius: 15px;
  padding:20px;
  font-size:15px;
  color:#fff;  
}
  
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbutton {
     width: 100%;
  }
}
</style>
<script type="text/javascript">
function ValidateEmail(emailId)
{
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(emailId.value.match(mailformat))
    {
        return true;
    }
    else
    {
        alert("You have entered an invalid email address!");
        document.getElementById('yourEmailID').focus();
        return false;
    }
}
</script>
</head>
    
<body>
    <form action="registerServlet" method="post" onclick="ValidateEmail(document.getElementById('yourEmailID'))">
  <div class="container">
    <label for="username"><b>Email</b></label>
    <input type="text" placeholder="Please enter your email" name="yourEmailID" id = "yourEmailID" required>
    <label for="user"><b>User Name</b></label>
    <input type="text" placeholder="Please enter your username" name="userName" id = "userName" required>
  
    <label for="password"><b>Password</b></label>
    <input type="password" placeholder="Please enter Password" name="yourPassword" id="yourPassword" required>
  <div class="seldiv">
    <label>Gender: </label>
    <select name = "gender" id="gender">
        <option value="male">MALE</option>
        <option value="female">FEMALE</option>
    </select
  </div
<br>
  <div class="optiondiv">
        
<p>Please select your favorite language:</p>
  
      <input type="radio" id="java" name="favoriteLanguage" value="JAVA">
      <label for="java">JAVA</label><br>
      <input type="radio" id="python" name="favoriteLanguage" value="PYTHON">
      <label for="python">PYTHON</label><br>
      <input type="radio" id="ruby" name="favoriteLanguage" value="RUBY">
      <label for="ruby">RUBY</label
   </div>
    <button type="submit">Register</button>
    <label>
      <input type="checkbox" checked="checked" name="rememberme"> Remember me
    </label>
  </div>
 </form>
</body>
</html>


In the above code

<!-- This will produce a dropdown containing MALE and FEMALE values
<label>Gender: </label>
<select name = "gender" id="gender">
    <option value="male">MALE</option>
  <option value="female">FEMALE</option>
</select>
<!-- This will produce different options containing JAVA/PYTHON/RUBY as favorite languages -->
 <p>Please select your favorite language:</p>
  <input type="radio" id="java" name="favoriteLanguage" value="JAVA">
  <label for="java">JAVA</label><br>
  <input type="radio" id="python" name="favoriteLanguage" value="PYTHON">
  <label for="python">PYTHON</label><br>
  <input type="radio" id="ruby" name="favoriteLanguage" value="RUBY">
  <label for="ruby">RUBY</label> 

Output:

Output

Front-end email validation is done via the “ValidateEmail” method in the register.jsp file. We can split CSS in separate fill and javascript into separate files and include them also.

<script type="text/javascript">
function ValidateEmail(emailId)
{
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(emailId.value.match(mailformat))
    {
        return true;
    }
    else
    {
        alert("You have entered an invalid email address!");
        document.getElementById('yourEmailID').focus();
        return false;
    }
}
</script>

We will get error messages if the email id is not in a proper format. Once the front-end validations are over, the form is submitted to the corresponding servlet that is mentioned in the action tag. 

RegisterServlet.java

Java




import java.io.IOException;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
  
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
         
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // We can able to get the form data by means of the below ways. 
        // Form arguments should be matched and then only they are recognised
        String userName = request.getParameter("userName");
        String yourEmailID = request.getParameter("yourEmailID");
        String yourPassword = request.getParameter("yourPassword");
        String gender = request.getParameter("gender");
        String favoriteLanguage = request.getParameter("favoriteLanguage");
        System.out.println("gender.." + gender);
        System.out.println("favoriteLanguage.." + favoriteLanguage);
          
        // Here the business validations goes. As a sample, 
        // we can check against a hardcoded value or pass the
        // values into a database which can be available in local/remote  db
        // For easier way, let us check against a hardcoded value
        if (userName != null && yourEmailID != null &&  yourPassword != null ) {
            // We can redirect the page to a welcome page
            // Need to pass the values in session in order 
            // to carry forward that one to next pages
            HttpSession httpSession = request.getSession();
            httpSession.setAttribute("emailId", yourEmailID);
            httpSession.setAttribute("gender", gender);
            httpSession.setAttribute("favoriteLanguage", favoriteLanguage);
            request.getRequestDispatcher("welcome.jsp").forward(request, response);
        }
    }
}


Welcome.jsp

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<%
    String gender = (String)session.getAttribute("gender");
    String genderTitle = null;
  
    if (gender != null && gender.equalsIgnoreCase("female")) {
        genderTitle = "Ms/Mrs.";
    } else {
        genderTitle = "Mr.";
    }
    %>
Welcome <%= genderTitle %> <%=session.getAttribute("emailId") %>
<br>
Your Resume has been added under <%= session.getAttribute("favoriteLanguage")  %> POOL
</body>
</html>


Output:

Output

The explanation for form concept via video:

This video explains the difference between the “Onsubmit” and “OnClick” events too.

Conclusion

A form is considered as the input place for collecting the desired information from users. It can be present in any front-end files like HTML/JSP etc., and in that, if it is placed in JSP(Java server pages), we can handle javascript validations easily. Javascript validations need to be handled on the client-side itself. Hence JSP kind of page is good. According to the form tag requests, either the “POST” or “GET” method will be executed and again the response is written back in JSP pages. In order to carry the form data from one page to another “session” is used.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads