Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Using HTML Forms with Servlets

In this article we will see how to work with servlet to receive data from html web form and display in the webpage.

Introduction:

Servlet is java technology provided by Oracle that is used to communicate web server and client (like web browsers) applications. Servlet as technology provides Java an API to facilitate the development of web applications. It is partially implemented by web server vender and by the application programmer.

From an application point of view, it is a java class that is created using Servlet API and instantiated by web server to process dynamic request.

Objective:

In this article, we will learn:

  • What is servlet?
  • How to receive submitted data by web client like web browser?
  • How to response to client according to submitted data?

Servlet in Detail:

Servlet is a Java API that is used to create dynamic web applications. To write a servlet application, the package named javax.servlet and its sub packages are used. At the core of Servlet API, an interface javax.servlet.Servlet provides the life cycle methods of servlet. These methods are used to initialize, manage and destroy a servlet, which are as follows:

  • init()
  • service()
  • destroy()

Whenever a user visit a url from web browser, each visit of url is considered as a request. On each request generated by web browser that hits on the server, server sends a response that depends on development strategies.

Generate a response to request submitted by the client

Figure 1: Generate a response to request submitted by the client

  • 1.0 Request for a servlet is sent to web server.
  • 1.1 ServletRequest object is created for request.
  • 1.2 Requested data is stored in the ServletRequest Object.
  • 1.3 ServletResponse object is created for the request.
  • 1.4 service() method of servlet is invoked and reference of ServletRequest & ServletResponse is provided.
  • 1.5 Servlet reads requested data from ServletRequest object.
  • 1.6 Servlet generates dynamic contents and stores them to ServletResponse object.
  • 1.7 After compilation of service() method, webserver sends the contents of ServletResponse
  • 1.8 contents of ServletResponse are sent to the client.

Listing 1: Create a HTML form page

<%@ 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>LoginInfo</title>
</head>
<body>
	<form method = "post"  action = "LoginInfo">
		Login Id: <input type = "text" name = "name"/>
		<br>
		Password: <input type = "password" name = "password"/>
		<br>
		<input type = "submit" value = "Login"/>
	</form>
</body>
</html>

This code create a form, that accepts loginid and password as two inputs and process them to the web server, one user click on login button or hits enter. The form tag defines that the data will be sent using post method. Hence, it will not be shown in the web url and will be transferred to the servlet name LoginInfo. This servlet will receive data using request object created of class HttpServletRequest.

Create a HTML Form Page

Figure 2: Create a HTML Form Page

Listing 2: Create LoginInfo Servlet to receive submitted data from HTML form

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class test
 */
       
@WebServlet(urlPatterns = "/LoginInfo")
public class LoginInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */

    public LoginInfo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
        // TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated constructor stub
		String id = request.getParameter("name");
		String pass = request.getParameter("password");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		RequestDispatcher rd = null;
		request.setAttribute(id, "name");
		if(id.equals("name") && pass.equals("pass")){
			rd = request.getRequestDispatcher("/WelcomeServlet");
			rd.forward(request, response);
		}
		else{
			out.println("<b>Invalid Login Info.</b><br>");
			rd = request.getRequestDispatcher("/LoginInfo.jsp");
			rd.include(request, response);
		}
		out.close();

	}
}

Above code defines LoginInfo servlet class that extends HttpServlet and defines doPost() and doGet() methods. The doGet() call the doPost() methods. The doPost() receives the data transferred from the html form using the method getParameter() of class HttpServletRequest. These two methods doGet() and doPost() throws exceptions:

  • ServletException
  • IOException

And accepts two parameters of type HttpServletRequest and HttpServletResponse type. The first line of method doPost() defines the response type to the client. The response type of this servlet will be Html or text content type.

The next line creates a reference variable of type PrintWriter and assigns the reference of response.getWrite() method. The next line of this method defines a reference variable of RequestDispatcher type and set an attribute using method setAttribute() of class HttpServletRequest class. Now validate the given input of client using string method equals(). If the username is equal to “name” and password is equal to “pass” the control will be moved to new servlet “WelcomeServlet” using getRequestDispatcher() and forward() methods as follows:

	rd = request.getRequestDispatcher(“/WelcomeServlet”);
	rd.forward(request, response);

If loginid and password doesn’t match, an error message will be generated “Invalid Login info” using println() method and login page will be included using include() method as follows:

	out.println(“<b>Invalid Login Info</b><br>”);
	rd.include(request,response);

In the last line of this method, the Writer stream will be close using close() method.

In this servlet, The url pattern configuration was defined using annotation as follows:

@WebServlet (urlpattern = “/LoginInfo”)

This configuration can be made using a xml file that is the deployment descriptor xml file. It is named as web.xml file.

Listing 3: Creating a web.xml file

<?xml version=”1.0” encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> 
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
	<servlet>
		<servlet-name>
			LoginInfoName
		</servlet-name>
		<servlet-class>
			LoginInfo
		</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>
			LoginInfoName
		</servlet-name>
		<url-pattern>
			/LoginInfo
		</url-pattern>
	<servlet-mapping>
</web-app>

The above table contents define the web.xml (deployment descriptor) file. The first tag <xml> defines the xml version to debugger. The next tag <web-app> is the root tag that defines the servlet class and its html form action url mapping, context parameter description, init parameter description using its tag.

The sub-tag <welcome-file-list> loads the default welcome file, while the web application starts using its sub-tag <welcome-file>. The next tag <servlet> is used to define the servlet class that is to be mapped on html form action url using sub-tag <servlet-mapping>.

The <servlet> tag uses its two sub-tags <servlet-name> and <servlet-class> to define the the name that will be used to map the url and the servlet class that is going to be mapped on this url.

<servlet>
		<servlet-name>LoginInfoName</servlet-name>
		<servlet-class>LoginInfo</servlet-class>
	</servlet>

Note: the name specified using tag <servlet-name> in <servlet> tag should be same as defined in <servlet-mapping> in order to map servlet class with the url.

The url is defined using the sub-tag <url-pattern> of tag <servlet-mapping> tag.

<servlet-mapping>
		<servlet-name>LoginInfoName</servlet-name>
		<url-pattern>/LoginInfo</url-pattern>
	<servlet-mapping>
Generate an error message, while user submits an invalid info

Figure 3: Generate an error message, while user submits an invalid info

The above figure shows an error message and loads the login page once again, if the user submits the invalid login information.

Load

Figure 4: Load WelcomeServlet, if User is validated

The above figure shows the welcome message after loading the WelcomeServlet, if user enters the valid information. The user information validates with the hard coded userid “name” and password “pass”.

Conclusion:

In this article, we learned about:

  • What is servlet, what is the need of servlet.
  • How to receive submitted data by web client like web browser?
  • How to response to client according to submitted data?


Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login