Use Java Bean In Servlets


 

Use Java Bean In Servlets

In this you will learn how to 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 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("[email protected]");
		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>

Ads