Java EE Core Concepts: Beans, Struts, JSP, EJB, MVC, CRUD
JavaBeans: Components & Core Concepts
JavaBeans are reusable software components that adhere to a specific set of conventions and guidelines defined by Sun Microsystems (now Oracle). They are essentially Java classes that encapsulate data and functionality, making them easily accessible and manageable. JavaBeans follow the principle of “Write Once, Run Anywhere” and can be integrated seamlessly into various Java development frameworks.
- Reusability: JavaBeans are designed to be reusable, enabling developers to create components that can be used in multiple projects.
- Interoperability: JavaBeans can be easily integrated with various Java development frameworks, enhancing interoperability between different components and systems.
- IDE Support: Integrated Development Environments (IDEs) provide extensive support for JavaBeans, including automated code generation for getters and setters, making development faster and more efficient.
JavaBean Properties: Accessors & Mutators
1. getPropertyName(): Suppose the property name is FullName; you will be required to use getFullName()
as the method name to read the full name of a person. An accessor is the name given to this method. Properties of this method include:
- It doesn’t take any argument.
- It is public in nature.
- It is prefixed with the term ‘get’.
2. setPropertyName(): Suppose the property name is FullName, setFullName()
is the method name that you need to use to write the full name. A mutator is the name of this method. Mentioned below are the properties of this method:
- It takes some argument.
- It is public in nature.
- It is prefixed with the term ‘set’.
BDK Introspection in JavaBeans
Introspection in the Java Beans Development Kit (BDK) refers to the capability of a Java program to examine the properties, methods, and events of a JavaBean at runtime. This mechanism allows tools and applications to discover and utilize the features of a Bean dynamically, without prior knowledge of its specific implementation. The java.beans.Introspector
class is central to this process. It analyzes a Bean’s class and superclasses, identifying properties, events, and methods based on design patterns or explicit BeanInfo
classes.
Apache Struts Web Application Framework
Struts is an open-source web application framework developed by the Apache Software Foundation. It is used to create web applications based on Servlet and JSP technologies. It depends on the MVC (Model-View-Controller) framework. Struts is thoroughly useful in building J2EE (Java 2 Platform, Enterprise Edition) applications because it takes advantage of J2EE design patterns. Struts follows these J2EE design patterns, including MVC and JSP custom tag libraries. In Struts, the composite view manages the layout of its sub-views and can implement a template, making a consistent look and feel easier to achieve and customize across the entire application.
Struts Framework Architecture
Struts is a powerful open-source framework for building Java web applications based on the Model-View-Controller (MVC) design pattern. Its architecture is designed to promote separation of concerns, making applications more maintainable and scalable.
- Filter Dispatcher (Front Controller): This is the entry point for all requests in a Struts application.
- Actions: Actions are Java classes that contain the business logic to handle user requests.
- Results and Result Types: A Result represents the outcome of an Action’s execution. It specifies what should happen after the Action is performed.
- Interceptors: Interceptors are powerful components that allow you to implement cross-cutting concerns, such as logging, security, validation, and transaction management, in a reusable way.
- Tag Libraries: Struts provides a rich set of custom JSP tag libraries that simplify the development of dynamic web pages.
Key Classes in Struts Applications
In a Struts application, the main classes are the Action Servlet, Action Form, Action Class, Action Mapping, and Action Forward. These classes work together to handle user requests, process data, and control the flow of the application.
- Action Servlet: This is the front controller that intercepts all requests and passes them to the appropriate Action class.
- Action Form: This class represents the form data submitted by the user and is used to bind form values to the Action class.
- Action Class: This class implements the business logic of the application and handles the processing of user requests.
- Action Mapping: This class maps a URL to a specific Action class and Action method.
- Action Forward: This class specifies where the control should be forwarded after the Action class has processed the request.
JavaServer Pages (JSP) Technology
JSP technology is used to create web applications, just like Servlet technology. It can be thought of as an extension to Servlets because it provides more functionality than Servlets, such as Expression Language, JSTL, etc. A JSP page consists of HTML tags and JSP tags. JSP pages are easier to maintain than Servlets because we can separate design and development. It provides some additional features such as Expression Language, Custom Tags, etc.
JSP Page Lifecycle Stages
- Translation: JSP to Servlet source code.
- Compilation: Servlet source code to bytecode.
- Class Loading: Loading the Servlet class.
- Instantiation: Creating an instance of the Servlet.
- Initialization: Calling
jspInit()
(once). - Request Processing: Calling
_jspService()
for each request. - Destruction: Calling
jspDestroy()
(once).
Types of JSP Tags
- Directive Tags: These tags provide instructions to the JSP container and affect how the JSP page is processed.
- Scripting Tags: These tags allow embedding Java code within a JSP page.
- Action Tags: These tags provide predefined actions that can be performed within a JSP page.
- Custom Tags: These are user-defined tags that extend the functionality of JSP. They are created using tag libraries and provide a way to encapsulate complex logic and reuse it across multiple JSP pages.
JSP Expression Language (EL)
The JSP Expression Language (EL) is a concise and powerful scripting language used within JavaServer Pages to simplify the access and manipulation of application data, thereby reducing the need for verbose Java scriptlets. Enclosed within ${}
delimiters, EL provides a straightforward syntax for retrieving attributes from various scopes (page, request, session, application), accessing properties of JavaBeans, working with collections and arrays, utilizing implicit objects that provide access to request parameters, headers, cookies, and context information, and performing basic arithmetic and logical operations directly within the JSP.
EL vs. Traditional JSP Scripting
The JSTL Expression Language (EL) simplifies JSP development by providing a concise syntax (${}
) for accessing application data, unlike verbose traditional scripting elements (<% %>
, <%= %>
). EL focuses on data retrieval from scopes, JavaBeans, and implicit objects, promoting cleaner JSPs and better separation of presentation from Java logic. Scripting elements, while offering full Java power within JSPs, often lead to cluttered, less maintainable code and blur the lines between presentation and business logic. EL is designed for both developers and designers, enhancing readability and maintainability compared to the more Java-centric scripting elements.
Stateful vs. Stateless Session Beans
Stateful Session Beans: These beans maintain a conversational state with the client. Each client gets a unique instance of the bean, and the bean retains the client’s data across multiple method calls. This is useful for scenarios where information needs to be preserved throughout a session, such as shopping carts or multi-step processes. The state is typically managed by the EJB container, which may passivate (store to disk) and activate (restore from disk) the bean as needed.
Stateless Session Beans: These beans do not maintain any client-specific state. All instances of a stateless session bean are identical and can be used interchangeably by any client. Because they do not hold state, they are pooled by the EJB container and reused for different client requests, making them more efficient for operations that do not require maintaining state. Each method invocation is independent and doesn’t rely on previous interactions.
Servlet vs. JSP: Key Differences
Feature | Servlet | JSP |
---|---|---|
Response Time | Faster, shorter response time. | Slower, due to initial conversion and compilation. |
Code Base | Java-based code. | HTML-based code with embedded Java. |
Coding Difficulty | Harder to code, HTML written in Java. | Easier to code, Java coded in HTML. |
MVC Role | Acts as the controller. | Acts as the view to present output. |
service() Method | Can be overridden. | Cannot be overridden. |
Understanding HTTP Sessions
A Session serves as a mechanism to maintain state about a specific user’s interaction with a web application across multiple HTTP requests, which are inherently stateless. When a user first accesses the application, a unique HttpSession
object is created on the server, and a session identifier (typically a JSESSIONID
cookie) is sent to the user’s browser to associate subsequent requests with this particular session. This allows the application to store user-specific data as attributes within the HttpSession
, such as login status, shopping cart contents, or preferences, making it accessible throughout the user’s browsing session.
Web Cookies Explained
Cookies are small text files that web servers send to a user’s browser, and the browser stores them locally. These cookies are then automatically included with subsequent requests sent back to the same server. They serve as a mechanism for the server to remember information about the user across multiple, otherwise stateless, HTTP requests. Common uses include maintaining login sessions, tracking user preferences, storing shopping cart contents, and website analytics.
Enterprise JavaBeans (EJB) Fundamentals
Enterprise JavaBeans (EJB) is one of several Java APIs for the standard manufacture of enterprise software. EJB is a server-side software component that encapsulates the business logic of an application. The Enterprise JavaBeans specification yields a runtime domain for web-related software elements, including computer reliability, Java Servlet Lifecycle (JSL) management, transaction procedures, and other web services. The EJB specification is a subset of the Java EE specification. The EJB specification was originally developed by IBM in 1997 and later adopted by Sun Microsystems in 1999 and enhanced under the Java Community Process. The EJB specification aims to provide a standard way to implement the server-side business software typically found in enterprise applications.
Benefits of Enterprise JavaBeans
- The EJB container yields system-level services to enterprise beans, allowing the bean developer to focus on solving business problems.
- Since the beans, rather than the clients, contain the application’s business logic, the client developer can focus on the presentation of the client.
- Enterprise JavaBeans are portable elements, allowing the application assembler to build new applications from existing beans.
Types of Enterprise JavaBeans
- Session Bean: A Session Bean contains business logic that can be invoked by local, remote, or web service clients.
- Message-Driven Bean: Like a Session Bean, it contains business logic, but it is invoked by passing messages.
- Entity Bean: It represents state that can be persisted in the database. It is deprecated and now replaced with JPA (Java Persistence API).
EJB Lifecycle Management
- Stateless Session Beans: Instances are typically pooled, serve client requests without maintaining state across calls, and return to the pool for reuse.
- Stateful Session Beans: A unique instance is created for each client, maintaining client-specific state across method invocations, and can be passivated/activated by the container for resource management before eventual removal.
- Message-Driven Beans (MDBs): Instances are pooled to process asynchronous messages, with the container invoking the
onMessage()
method upon message arrival, and then returning the instance to the pool.
Model-View-Controller (MVC) Design Pattern
MVC (Model-View-Controller) is a pattern in software design commonly used to implement user interfaces, data, and controlling logic. It emphasizes a separation between the software’s business logic and display. This “separation of concerns” provides for a better division of labor and improved maintenance. Some other design patterns are based on MVC, such as MVVM (Model-View-ViewModel), MVP (Model-View-Presenter), and MVW (Model-View-Whatever).
- Model: The model defines what data the app should contain. If the state of this data changes, then the model will usually notify the view (so the display can change as needed) and sometimes the controller (if different logic is needed to control the updated view).
- View: The view defines how the app’s data should be displayed. In our shopping list app, the view would define how the list is presented to the user, and receive the data to display from the model.
- Controller: The controller contains logic that updates the model and/or view in response to input from the users of the app.
CRUD Operations in Java EE
- Utilize JPA in Session Beans: Perform CRUD operations (persist, find, merge, remove) on entity beans within stateless or stateful Session Beans, leveraging the injected
EntityManager
for database interaction. - Ensure Transaction Management: Wrap CRUD operations within transactional boundaries (CMT or BMT) to guarantee data consistency and atomicity.
- Implement Validation in Service Layer: Validate entity data within the Session Bean (service layer) before persistence to maintain data integrity.
- Consider Data Access Objects (DAOs): Optionally introduce a DAO layer for abstraction between Session Beans and JPA, improving testability and decoupling persistence logic.