Java Servlet Bean Example
Servlets are modules of the Java code that run in a server application to answer the client requests. In this tutorial, we will explain how to handle the JavaBean in a Servlet.
1. Introduction
Servlet is a Java program which exists and executes in the J2EE servers and is used to receive the HTTP protocol request, process it and send back the response to the client. Servlets make use of the Java standard extension classes in the packages javax.servlet
and javax.servlet.http
. Since Servlets are written in the highly portable Java language and follow a standard framework, they provide a means to create the sophisticated server extensions in a server and operating system in an independent way.
Typical uses for HTTP Servlets include:
- Processing and/or storing the data submitted by an HTML form
- Providing dynamic content i.e. returning the results of a database query to the client
- Managing state information on top of the stateless HTTP i.e. for an online shopping cart system which manages the shopping carts for many concurrent customers and maps every request to the right customer
As Servlet technology uses the Java language, thus web applications made using Servlet are Secured, Scalable, and Robust. Now, open up the Eclipse Ide and let’s see how to use the Java Bean in the Servlets.
2. Java Servlet Bean Example
Here is a step-by-step guide for implementing the Servlet framework in Java.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.
Select the ‘Maven Web App’ Archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaServletBeanEx</groupId> <artifactId>JavaServletBeanEx</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
We can start adding the dependencies that developers want like Servlets, Junit etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependencies for the Servlet API. The rest dependencies will be automatically resolved by the Maven framework and the updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaServletBeanEx</groupId> <artifactId>JavaServletBeanEx</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>JavaServletBeanEx Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.2 Java Class Creation
Let’s create the required Java files. Right-click on src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: com.jcg.servlet
.
Once the package is created in the application, we will need to create the controller class. Right-click on the newly created package: New -> Class
.
A new pop window will open and enter the file name as: Employee
. The Model class (i.e. JavaBean) will be created inside the package: com.jcg.servlet
.
Repeat the step (i.e. Fig. 8) and enter the filename as: BeanInServlet
. The Servlet Controller class will be created inside the package: com.jcg.servlet
.
3.2.1 Implementation of Bean Class
In order to learn the use of JavaBeans in the Servlets, we have created a bean named Employee
and defined 4
variables with their setters and getters. We will use the object of this bean in the Servlet controller class. Let’s see the simple code snippet that follows this implementation.
Employee.java
package com.jcg.servlet; public class Employee { private int emp_id; private String emp_name; private String emp_email; private long emp_phone; public int getEmp_id() { return emp_id; } public void setEmp_id(int emp_id) { this.emp_id = emp_id; } public String getEmp_name() { return emp_name; } public void setEmp_name(String emp_name) { this.emp_name = emp_name; } public String getEmp_email() { return emp_email; } public void setEmp_email(String emp_email) { this.emp_email = emp_email; } public long getEmp_phone() { return emp_phone; } public void setEmp_phone(long emp_phone) { this.emp_phone = emp_phone; } }
3.2.2 Implementation of Servlet Controller Class
In the controller class, we have created an object of the Employee
bean and passed some values by using the setter methods of the bean class. This object is then stored into setAttribute()
method of the HttpServletRequest
object. We forward this request object to the beanData.jsp
by using the Request Dispatcher to make the attributes available there.
Let’s see the simple code snippet that follows this implementation.
BeanInServlet.java
package com.jcg.servlet; import java.io.IOException; 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("/beanInServlet") public class BeanInServlet extends HttpServlet { private static final long serialVersionUID = 1L; // This Method Is Called By The Servlet Container To Process A 'GET' Request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { handleRequest(request, response); } public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Employee eObj = new Employee(); eObj.setEmp_id(101); eObj.setEmp_name("Java Code Geeks"); eObj.setEmp_email("support@javacodegeeks.com"); eObj.setEmp_phone(302244); /**** Storing Bean In Session ****/ request.getSession().setAttribute("emp", eObj); RequestDispatcher rd = request.getRequestDispatcher("/beanData.jsp"); rd.forward(request, response); } }
3.3 Creating JSP Views
Servlet supports many types of views for different presentation technologies. These include – JSP
, HTML
, XML
etc. So let us write a simple view in JavaServletBeanEx/src/main/webapp/
and add the following code to it:
beanData.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!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=UTF-8"> <title>Java Bean In Servlet 3.0</title> </head> <body> <center> <h2>Java Bean In Servlet 3.0</h2> <c:choose> <c:when test="${empty emp}"> <h3>Currently, there are no employees.</h3> </c:when> <c:otherwise> <table id="beanTable"> <tr> <td>Employee Id:</td><td>${emp.emp_id}</td> </tr> <tr> <td>Name:</td><td>${emp.emp_name}</td> </tr> <tr> <td>Email Address:</td><td>${emp.emp_email}</td> </tr> <tr> <td>Phone No.:</td><td>${emp.emp_phone}</td> </tr> </table> </c:otherwise> </c:choose> </center> </body> </html>
4. Run the Application
As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.
5. Project Demo
Open your favorite browser and hit the following URL. The output page will be displayed.
http://localhost:8085/JavaServletBeanEx/
Server name (localhost) and port (8085) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!
That’s all for this post. Happy Learning!!
6. Conclusion
In this section, developers learned how to use the JavaBean in the Servlets. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers were looking for.
7. Download the Eclipse Project
This was an example of JavaBean in Servlets.
You can download the full source code of this example here: JavaServletBeanEx
Hi there, thanks a lot for your tutorial.
The snake-case variables names in the Bean class is a best practice? Usually in Java the variables names should be lower-camel-case by conventions, right?
Yes, Igor. Thanks and have a great day.
You’re missing “implements java.io.serializable” in your Employee class to be a Javabean
public class Employee implements java.io.Serializable {…}