Home Tutorial Servlet Use Java Bean In Servlets


Share on Google+Share on Google+
Use Java Bean In Servlets
Posted on: January 9, 2010 at 12:00 AM
In this you will learn how to use Java Bean in Servlets.

Use Java Bean In Servlets

In this you will learn how to use Java Bean in Servlets. For this purpose, we have created a Bean named 'Person' and defined three variables with their setters and getters. Then we have created an object of this Bean in servlet and using the set method of bean, we have passed some values. This object is then stored into setAttribute() method of Request object and forward this request to databean.jsp using requestDispatcher to make the attributes available there. In jsp page, we have used EL to display the attribute values.

Here is the code of Person.java

public class Person {
	private String name;
	private String email;
	private long phoneNo;

	public Person() {

	public void setName(String name) {
		this.name = name;

	public String getName() {
		return name;

	public void setEmail(String email) {
		this.email = email;

	public String getEmail() {
		return email;

	public void setPhoneNo(long phoneNo) {
		this.phoneNo = phoneNo;

	public long getPhoneNo() {
		return phoneNo;


Here is the code of BeanInServlet.java

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BeanInServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		Person p = new Person();
		p.setName("Sam Dalton");
		req.setAttribute("person", p);
		RequestDispatcher rd = req.getRequestDispatcher("/jsp/beandata.jsp");
		rd.forward(req, res);

Here is the code of beandata.jsp:

<tr><td>Name is:</td><td>${person.name}</td></tr>
<tr><td>Email is:</td><td>${person.email}</td></tr>
<tr><td>PhoneNo is:</td><td>${person.phoneNo}</td></tr>

Do the following servlet mapping in WEB-XML:


Related Tags for Use Java Bean In Servlets:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 9, 2010

Recommend the tutorial

Advertisements Advertisements