Share on Google+Share on Google+

Use Java Bean In Servlets

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

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

	public Person() {

	public void setName(String name) { = name;

	public String getName() {
		return name;

	public void setEmail(String 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

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");
		p.setEmail("[email protected]");
		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>${}</td></tr>
<tr><td>Email is:</td><td>${}</td></tr>
<tr><td>PhoneNo is:</td><td>${person.phoneNo}</td></tr>

Do the following servlet mapping in WEB-XML:



Posted on: January 9, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.