Integrating JavaBeans with JSP Pages
Course: Advanced Java Training
Topic: Integrating JavaBeans with JSP Pages
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to JavaBeans and JSP Integration
JavaBeans are reusable Java classes that encapsulate data using properties and accessor methods. JavaServer Pages (JSP) is a server-side technology used to generate dynamic web pages. Integrating JavaBeans with JSP allows developers to separate data handling from presentation and display application information without placing large amounts of Java code inside JSP pages.
For example, in a student management application, a JavaBean can store a student's name, email address, student ID, and course. A JSP page can access these properties and display them in an HTML document.
JSP provides standard actions such as <jsp:useBean>, <jsp:setProperty>, and <jsp:getProperty> to work with JavaBeans. Expression Language (EL) also provides a concise way to access bean properties.
Why Integrate JavaBeans with JSP?
- To separate application data from presentation code.
- To reuse Java objects across different web pages and components.
- To simplify displaying dynamic information.
- To reduce Java scriptlets inside JSP pages.
- To make applications easier to maintain, test, and extend.
- To transfer information between Servlets, JSP pages, and service classes.
2. Learning Objectives
After completing this topic, learners should be able to:
- Understand how JavaBeans and JSP work together.
- Create JavaBean classes suitable for JSP integration.
- Use the
<jsp:useBean> action to locate or create a bean.
- Set bean properties using
<jsp:setProperty>.
- Retrieve property values using
<jsp:getProperty>.
- Access JavaBean properties using Expression Language.
- Understand bean scopes and their lifetimes.
- Integrate JavaBeans with HTML forms and Servlets.
- Troubleshoot common JSP and JavaBean integration problems.
3. Understanding the Relationship Between JavaBeans and JSP
JavaBeans and JSP have different responsibilities within a web application. JavaBeans hold structured data and expose properties, while JSP pages display information through HTML and JSP expressions.
| Component |
Responsibility |
Example |
| JavaBean |
Stores and exposes application data. |
Student.java |
| JSP |
Displays dynamic content to the user. |
student.jsp |
| Servlet |
Processes requests and coordinates application logic. |
StudentServlet.java |
| Service Layer |
Performs application-specific business operations. |
StudentService.java |
| DAO or Repository |
Handles database operations. |
StudentDAO.java |
A typical application flow is:
Browser
|
v
HTML Form
|
v
Servlet Controller
|
v
JavaBean Object
|
v
JSP Page
|
v
Dynamic HTML Response
In a real application, the Servlet may call a service or DAO before creating or populating the bean. The JSP then renders the data passed to it.
4. Creating a JavaBean for JSP Integration
Before using a JavaBean in JSP, create a Java class that follows the conventional JavaBean design patterns. Typically, the class has private fields, a public no-argument constructor, and public getter and setter methods.
Example: Student.java
package com.example.model;
public class Student {
private int studentId;
private String studentName;
private String course;
private String email;
public Student() {
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Explanation
studentId stores the student's unique identifier.
studentName stores the student's name.
course stores the enrolled course.
email stores the student's email address.
- The no-argument constructor supports conventional bean instantiation.
- Getter methods allow JSP and other components to retrieve values.
- Setter methods allow the application to populate or modify values.
The class belongs to the com.example.model package. Its fully qualified name is therefore com.example.model.Student.
5. Using the jsp:useBean Action
The <jsp:useBean> action declares a JavaBean for use in a JSP page. It searches the specified scope for an existing bean with the given ID. If a compatible bean is not found, it creates one using the specified class and stores it in that scope.
Syntax
<jsp:useBean id="beanName"
class="package.ClassName"
scope="request" />
Example
<jsp:useBean id="student"
class="com.example.model.Student"
scope="request" />
This statement makes a Student bean available under the name student in request scope.
Important Attributes
| Attribute |
Description |
Example |
| id |
Specifies the bean name used in the JSP. |
id="student" |
| class |
Specifies the fully qualified Java class name. |
class="com.example.model.Student" |
| scope |
Defines the scope in which the bean is located or stored. |
scope="request" |
| type |
Can declare the reference type when used with supported attribute combinations. |
type="com.example.model.Student" |
The default scope is page. A bean declared with page scope is available only within the current JSP page. The class must be available to the web application's class loader and must meet the construction requirements of the selected JSP action.
6. Setting JavaBean Properties with jsp:setProperty
The <jsp:setProperty> action assigns a value to a JavaBean property by invoking the corresponding setter method. The property name must match the JavaBean property, and a compatible setter must exist.
Syntax
<jsp:setProperty name="beanName"
property="propertyName"
value="propertyValue" />
Example
<jsp:useBean id="student"
class="com.example.model.Student"
scope="request" />
<jsp:setProperty name="student"
property="studentName"
value="Amit Sharma" />
<jsp:setProperty name="student"
property="course"
value="Advanced Java" />
The JSP assigns the value Amit Sharma to the studentName property and Advanced Java to the course property.
Setting a Property from a Request Parameter
The param attribute allows a bean property to receive the value of an HTTP request parameter.
<jsp:setProperty name="student"
property="studentName"
param="studentName" />
If the request contains a parameter named studentName, JSP passes its value to the bean's corresponding setter. If the parameter is absent, the property is not updated by this action.
Automatically Mapping Request Parameters
The wildcard property value can be used to populate matching bean properties from request parameters.
<jsp:setProperty name="student" property="*" />
This action attempts to match request parameter names to bean property names and invoke the relevant setters. It is convenient for simple demonstrations, but production applications should validate and allowlist submitted fields rather than blindly binding all matching parameters.
7. Retrieving JavaBean Properties with jsp:getProperty
The <jsp:getProperty> action retrieves a JavaBean property through its getter method and writes the resulting value into the response.
Syntax
<jsp:getProperty name="beanName"
property="propertyName" />
Example
<jsp:getProperty name="student"
property="studentName" />
<jsp:getProperty name="student"
property="course" />
If the bean contains the values Amit Sharma and Advanced Java, those values are written into the JSP response.
Important Points
- The bean must be available under the specified name and scope.
- The property must be readable through a compatible getter.
- The property name is case-sensitive in the JSP action.
- The resulting value is converted to text for output.
- Untrusted values must be escaped appropriately before being rendered in HTML.
8. Accessing JavaBeans with Expression Language
Expression Language (EL) provides a concise way to read bean properties in JSP. It reduces the need for Java scriptlets and is commonly used to display dynamic data.
Example
<p>Student ID: ${student.studentId}</p>
<p>Student Name: ${student.studentName}</p>
<p>Course: ${student.course}</p>
<p>Email: ${student.email}</p>
In the expression ${student.studentName}, JSP resolves the bean named student and accesses its studentName property through the appropriate property-access mechanism.
Comparing Property Access Methods
| Method |
Example |
Purpose |
| JSP standard action |
<jsp:getProperty name="student" property="course" /> |
Retrieves and outputs a bean property. |
| Expression Language |
${student.course} |
Concise property access in JSP templates. |
| Java scriptlet |
<% out.print(student.getCourse()); %> |
Executes Java code inside a JSP; generally avoided for presentation logic. |
Expression Language is generally preferable for simple property access because it keeps JSP markup readable. However, EL expressions do not automatically escape all untrusted output in every context.
9. Complete Example: Integrating JavaBeans with JSP
This example demonstrates a basic student information page using a JavaBean and JSP. It assumes that the Student class has already been created and compiled.
Step 1: Student.java
package com.example.model;
public class Student {
private String studentName;
private String course;
private String email;
public Student() {
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Step 2: student.jsp
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<jsp:useBean id="student"
class="com.example.model.Student"
scope="page" />
<jsp:setProperty name="student"
property="studentName"
value="Amit Sharma" />
<jsp:setProperty name="student"
property="course"
value="Advanced Java" />
<jsp:setProperty name="student"
property="email"
value="[email protected]" />
<h1>Student Details</h1>
<p>Name: ${student.studentName}</p>
<p>Course: ${student.course}</p>
<p>Email: ${student.email}</p>
</body>
</html>
Expected Output
Student Details
Name: Amit Sharma
Course: Advanced Java
Email: [email protected]
This example initializes a bean directly in the JSP. In a larger application, a Servlet or service would normally retrieve or prepare the student information and pass the bean to the JSP for display.
10. Integrating JavaBeans with HTML Forms
JavaBeans can be used to organize values submitted through HTML forms. A registration form collects user input, a Servlet validates the data, and a bean carries the accepted values to the presentation layer.
HTML Form: student-form.html
<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
</head>
<body>
<h1>Student Registration</h1>
<form action="registerStudent" method="post">
<label for="studentName">Name:</label>
<input type="text" id="studentName"
name="studentName" required>
<label for="course">Course:</label>
<input type="text" id="course"
name="course" required>
<label for="email">Email:</label>
<input type="email" id="email"
name="email" required>
<button type="submit">Register</button>
</form>
</body>
</html>
Servlet: StudentServlet.java
package com.example.web;
import java.io.IOException;
import com.example.model.Student;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/registerStudent")
public class StudentServlet extends HttpServlet {
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("studentName");
String course = request.getParameter("course");
String email = request.getParameter("email");
if (name == null || name.isBlank()
|| course == null || course.isBlank()
|| email == null || email.isBlank()) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Required fields are missing"
);
return;
}
Student student = new Student();
student.setStudentName(name.trim());
student.setCourse(course.trim());
student.setEmail(email.trim());
request.setAttribute("student", student);
request.getRequestDispatcher("/student-details.jsp")
.forward(request, response);
}
}
This Servlet uses Jakarta Servlet APIs. Older Java EE projects may use the javax.servlet package instead. The correct imports depend on the Servlet container and application version.
JSP: student-details.jsp
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Registration Details</title>
</head>
<body>
<h1>Registration Details</h1>
<p>Name: ${student.studentName}</p>
<p>Course: ${student.course}</p>
<p>Email: ${student.email}</p>
</body>
</html>
For this example, the Student class must be compiled and available to the web application. The Servlet stores the bean in request scope, and the JSP accesses the same request attribute through EL.
Processing Flow
- The user enters details in the HTML form.
- The browser submits the form using HTTP POST.
- The Servlet reads and validates the parameters.
- The Servlet creates and populates the Student bean.
- The bean is stored as a request attribute.
- The Servlet forwards the request to the JSP page.
- The JSP reads the bean properties and generates the response.
11. Understanding Bean Scopes in JSP
The scope attribute determines where the bean is stored and how long it remains available.
| Scope |
Description |
Example Use |
| page |
Available within the current JSP page during processing. |
Temporary display data. |
| request |
Available throughout the current request, including a forward. |
Displaying submitted form information. |
| session |
Available across requests associated with the same HTTP session. |
Shopping cart or user workflow data. |
| application |
Shared across the web application through ServletContext. |
Shared application-level information. |
Page Scope
<jsp:useBean id="student"
class="com.example.model.Student"
scope="page" />
The bean is available only within the current JSP page's processing.
Request Scope
<jsp:useBean id="student"
class="com.example.model.Student"
scope="request" />
The bean is available during the current request. A forwarded JSP can access a bean created or stored by the Servlet.
Session Scope
<jsp:useBean id="student"
class="com.example.model.Student"
scope="session" />
The bean can be reused across requests within the same session. Use session scope only when necessary, and avoid sharing sensitive information unnecessarily.
Application Scope
<jsp:useBean id="sharedInfo"
class="com.example.model.SharedInfo"
scope="application" />
The bean is shared across users and requests. Application-scoped mutable objects require careful thread-safety design. User-specific information should not be stored in a shared application bean.
12. Initializing a Bean During Creation
The body of a <jsp:useBean> action can contain initialization actions. These nested actions execute when the bean is newly created by that useBean action, not when an existing compatible bean is found in the specified scope.
Example
<jsp:useBean id="student"
class="com.example.model.Student"
scope="request">
<jsp:setProperty name="student"
property="studentName"
value="Amit Sharma" />
<jsp:setProperty name="student"
property="course"
value="Advanced Java" />
</jsp:useBean>
This example creates and initializes the Student bean when no matching bean exists in request scope. If the bean already exists, the nested initialization actions are not executed.
13. Common Errors During JavaBeans and JSP Integration
| Error |
Possible Cause |
Solution |
| Bean class not found |
Incorrect package name or class not available to the application. |
Verify the fully qualified class name and compiled class location. |
| Bean cannot be instantiated |
Missing or inaccessible no-argument constructor. |
Provide an appropriate public no-argument constructor. |
| Property not found |
Incorrect property name or missing setter/getter. |
Check property naming and accessor methods. |
| Bean value is null |
Bean not populated or stored under a different attribute name. |
Verify the attribute name, scope, and property assignment. |
| Values disappear after redirect |
Request attributes do not persist into a new request. |
Use an appropriate workflow and suitable persistent storage. |
| Conversion error |
Request value cannot be converted to the property's data type. |
Validate and convert values before assigning them. |
| Unexpected data shared between users |
Incorrect use of application scope or shared mutable state. |
Use an appropriate scope and protect shared state. |
| Untrusted content appears in HTML |
Output is rendered without proper encoding. |
Use context-appropriate HTML escaping. |
14. Best Practices for JavaBeans and JSP
- Keep JavaBean fields private and use clear accessor methods.
- Use descriptive property names that follow JavaBean conventions.
- Use JSP for presentation rather than placing complex business logic in the page.
- Use Servlets or controllers to handle requests and coordinate processing.
- Validate user input before assigning it to beans or processing it further.
- Use request scope for data needed only during the current request.
- Use session scope only for information that must persist across requests.
- Avoid storing user-specific mutable data in application scope.
- Escape untrusted output to reduce cross-site scripting risks.
- Keep database operations in DAO or repository classes.
- Prefer Expression Language for straightforward property access.
- Use consistent package names and deploy compiled classes correctly.
15. JavaBeans with JSP vs. Java Scriptlets
Older JSP applications sometimes use scriptlets to create objects and call their methods directly. Using JavaBeans with JSP standard actions or EL provides a cleaner approach for simple data access.
| Aspect |
Java Scriptlets |
JavaBeans with JSP Actions and EL |
| Code organization |
Java logic can become mixed with HTML. |
Separates reusable data objects from presentation markup. |
| Readability |
May become difficult to maintain in large pages. |
Usually clearer for property access. |
| Reusability |
Code may be duplicated across JSP pages. |
The same bean class can be reused by multiple components. |
| Maintenance |
Changes may require editing several JSP pages. |
Bean properties can be managed in a dedicated Java class. |
| Recommended use |
Primarily legacy JSP code. |
Preferred for conventional property access in JSP applications. |
16. Practical Exercises
- Create a Product JavaBean with productId, productName, price, and category properties.
- Use
<jsp:useBean> to create or locate a Product bean.
- Set the product properties using
<jsp:setProperty>.
- Display the properties using
<jsp:getProperty>.
- Rewrite the display page using Expression Language.
- Create an HTML registration form and populate a Student bean through a Servlet.
- Test the differences between page scope, request scope, and session scope.
- Intentionally misspell a property name and identify the resulting error.
- Add input validation and handle missing form parameters.
- Build a simple student information page using a Servlet, JavaBean, and JSP.
17. Interview Questions and Answers
Q1. What is the purpose of integrating JavaBeans with JSP?
Answer: It allows application data to be organized into reusable Java objects and displayed in JSP pages while keeping data handling separate from presentation.
Q2. What is the purpose of jsp:useBean?
Answer: It locates a compatible bean in the specified scope or creates and stores a new bean if one does not already exist.
Q3. What does jsp:setProperty do?
Answer: It sets a bean property by invoking the corresponding setter method.
Q4. What does jsp:getProperty do?
Answer: It retrieves a bean property through its getter method and writes the resulting value to the response.
Q5. How does Expression Language access JavaBean properties?
Answer: EL uses expressions such as ${student.studentName} to resolve a bean and access its properties.
Q6. What is the default scope of jsp:useBean?
Answer: The default scope is page.
Q7. Can a Servlet pass a JavaBean to a JSP?
Answer: Yes. A Servlet can store the bean as a request attribute using request.setAttribute() and forward the request to a JSP.
Q8. What is the difference between request and session scope?
Answer: Request scope is limited to the current request, while session scope can preserve data across multiple requests associated with the same HTTP session.
Q9. Why should complex business logic be avoided in JSP?
Answer: Keeping business logic in service or controller components improves separation of concerns, readability, testing, and maintainability.
Q10. What does property="*" do in jsp:setProperty?
Answer: It attempts to map matching request parameter names to bean properties. Production applications should validate and restrict which submitted fields can be bound.
Q11. What happens if a JavaBean does not have the expected setter?
Answer: The JSP action cannot set that property as intended and may produce an error. The property name and setter method should be checked.
Q12. Does Expression Language automatically escape HTML output?
Answer: No. EL provides property access, but untrusted values still require appropriate output encoding.
18. Quick Revision Checklist
- JavaBeans encapsulate related data in reusable Java classes.
- JSP provides standard actions for working with JavaBeans.
<jsp:useBean> locates or creates a bean.
<jsp:setProperty> sets a bean property.
<jsp:getProperty> retrieves and outputs a property.
- Expression Language provides concise property access.
- The default bean scope is page.
- Servlets can populate beans and pass them to JSP through request attributes.
- Input validation and output encoding remain essential.
- Business logic and database operations should be kept in suitable application layers.
19. Conclusion
Integrating JavaBeans with JSP pages is an important concept in traditional Java web application development. JavaBeans organize application data into reusable objects, while JSP displays that data using standard actions and Expression Language. Understanding bean creation, property access, request handling, and scope management helps developers create web applications that are easier to maintain and extend.
To learn more about Java web development, explore the Advanced Java Training course at JustAcademy.
Register for a course demo to learn more about the training options.
Visit the JustAcademy website for additional learning resources.