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
Advertisement
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");
		p.setEmail("sam2222@gmail.com");
		p.setPhoneNo(1111111111);
		req.setAttribute("person", p);
		RequestDispatcher rd = req.getRequestDispatcher("/jsp/beandata.jsp");
		rd.forward(req, res);
	}
}

Here is the code of beandata.jsp:

<html>
<body>
<table>
<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>
</table>
</body>
</html>

Do the following servlet mapping in WEB-XML:

<servlet>
<servlet-name>BeanInServlet</servlet-name>
<servlet-class>BeanInServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BeanInServlet</servlet-name>
<url-pattern>/BeanInServlet</url-pattern>
</servlet-mapping>
Advertisement

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
 

 

 

DMCA.com