JSP (Javaserver Pages)
JSP (Javaserver Pages)
hello.JSP :
You will see the same output, but it will take longer! But only the first time. If you reload it
again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java file,
compiled, and loaded. This compilation only happens once, so after the first load, the file
doesn’t take long to load anymore. (But every time you change the JSP file, it will be re-
compiled again.)
Of course, it is not very useful to just write HTML pages with a .jsp extension! We now
proceed to see what makes JSP so useful.
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Scriptlet tag
This tag allow user to insert java code in JSP. The statement which is written will be moved
to jspservice() using JSP container while generating servlet from JSP. When client make a
request, JSP service method is invoked and after that the content which is written inside the
scriptlet tag executes.
<html>
<body>
</body>
</html>
Example
Java code
<html>
<body>
<form action="hello.jsp">
<!-- move the control to hello.jsp when Submit button is click -->
Enter Username:
</form>
</body>
</html>
Jsp code
pageEncoding="UTF-8"%>
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
charset=UTF-8">
</head>
<body>
<%
String name=request.getParameter("username");
out.print("Hello "+name);
%>
</body>
</html>
Expression tag
is one of the scripting elements in JSP. Expression Tag in JSP is used for writing your content
on the client-side. We can use this tag for displaying information on the client’s browser. The
JSP Expression tag transforms the code into an expression statement that converts into a
value in the form of a string object and inserts into the implicit output object.
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Sum</title>
</head>
<body>
</body>
</html>
Declaration tag
<html>
<head>
<title>Greetings</title>
</head>
<body>
</body>
</html>
Implicit objects are a set of Java objects that the JSP Container makes available to developers
on each page. These objects may be accessed as built-in variables via scripting elements and
can also be accessed programmatically by JavaBeans and Servlets.JSP provide you Total 9
implicit objects which are as follows
3. config: This is the object of ServletConfig class associated with the page.
5. session: This is the object of HttpSession class associated with the request.
6. page context: This is the object of PageContext class that encapsulates the
use of server-specific features. This object can be used to find, get or remove
an attribute.
7. page object: The manner we use the keyword this for current object, page
object is used to refer to the current translated servlet class.
8. exception: The exception object represents all errors and exceptions which is
accessed by the respective jsp. The exception implicit object is of
type java.lang.Throwable.
9. out: This is the PrintWriter object where methods like print and println
help for displaying the content to the client.
request Object
The JSP request is an implicit object which is provided by HttpServletRequest.
In the servlet, we have to first import javax.servlet.http.HttpServletRequest
then we have to create its object for taking input from any HTML form as.
Syntax :
import javax.servlet.http.HttpServletRequest;
"http://www.w3.org/TR/html4/loose.dtd ">
<html>
<head>
</head>
<body>
response object
This is the HttpServletResponse object associated with the response to the client. The
response object also defines the interfaces that deal with creating new HTTP headers.
Through this object the JSP programmer can add new cookies or date stamps, HTTP status
codes, etc.
pageEncoding="UTF-8"%>
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<%
String name=request.getParameter("username");
%>
</body>
</html>
Directives in JSP
JSP directives are the elements of a JSP source code that guide the web container on how to
translate the JSP page into its respective servlet.
There are three different JSP directives available. They are as follows:
Page Directives : JSP page directive is used to define the properties applying the JSP
page, such as the size of the allocated buffer, imported packages, and
classes/interfaces, defining what type of page it is, etc. The syntax of JSP page
directive is as follows:
Different properties/attributes :
The following are the different properties that can be defined using page directive :
contentType: This defines the format of data that is being exchanged between the
client and the server. It does the same thing as the setContentType method in servlet
used to.
Syntax:
<%@page contentType="value"%>
info: Defines the string which can be printed using the ‘getServletInfo()’ method.
Syntax:<%@page info="value"%>
<% = getServletInfo()%>
Java Server Pages declares 9 implicit objects, the exception object being one of them. It is an
object of java.lang.Throwable class, and is used to print exceptions. However, it can only be
used in error pages.
The page directive in JSP provides two attributes to be used in exception handling. They’re:
errorPage: Used to site which page to be displayed when exception occurred.
Syntax :
isErrorPage: Used to mark a page as an error page where exceptions are displayed.
Syntax :
<%@page isErrorPage="true"%>
<html>
<head>
<body>
<form action="a.jsp">
</form>
</body>
</html>
int x = Integer.parseInt(num1);
int y = Integer.parseInt(num2);
%>
This is another way of specifying the error page for each element, but instead of using the
errorPage directive, the error page for each page can be specified in the web.xml file, using
the <error-page> element. The syntax is as follows:
<web-app>
<error-page>
<exception-type>Type of Exception</exception-type>
</error-page>
</web-app>
<html>
<head>
<body>
<form action="a.jsp">
Number1:<input type="text" name="first" >
</form>
</body>
</html>
<%
int x = Integer.parseInt(num1);
int y = Integer.parseInt(num2);
int z = x / y; // dividing
%>
<web-app>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
Components of MVC
Controller
Model
View
MVC Architecture Design
Controller:
The controller is the component that enables the interconnection between the views and the
model so it acts as an intermediary. The controller doesn’t have to worry about handling data
logic, it just tells the model what to do. It processes all the business logic and incoming
requests, manipulates data using the Model component, and interact with the View to render
the final output.
Responsibilities:
View:
The View component is used for all the UI logic of the application. It generates a user
interface for the user. Views are created by the data which is collected by the model
component but these data aren’t taken directly but through the controller. It only interacts
with the controller.
Responsibilities:
Model:
The Model component corresponds to all the data-related logic that the user works with. This
can represent either the data that is being transferred between the View and Controller
components or any other business logic-related data. It can add or retrieve data from the
database. It responds to the controller’s request because the controller can’t interact with the
database by itself. The model interacts with the database and gives the required data back to
the controller.
Responsibilities:
Pagination is a sequence of pages that are connected and have similar content. Pagination is a
technique for splitting a list of multiple records into subsists. For example, you search with a
keyword on Google and receive tens of thousands of results. It is important to note that even
when the content on a section of a page is split into distinct pages, we will still define that as
pagination.
Pagination in Java
To divide a large number of records into multiple parts, we use pagination. It allows users to
display a part of records only. Loading all records on a single page may take time, so it is
always recommended to created pagination. In java, we can develop pagination examples
easily. In this pagination example, we are using the MySQL database to fetch records.
CRUD OPERATIONS:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2,
value3,...)
first_name varchar(50),
last_name varchar(50),
city_name varchar(50),
email varchar(50),
);
CREATE
create-table.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
statement.executeUpdate(query);
catch (Exception e)
%>
</body>
</html>
INSERT
<!DOCTYPE html>
<html>
<body>
<form method="post" action="process.jsp">
First name:<br>
<br>
Last name:<br>
<br>
City name:<br>
<br>
Email Id:<br>
<br><br>
</form>
</body>
</html>
process.jsp
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
try
Class.forName("com.mysql.jdbc.Driver");
Statement st=conn.createStatement();
catch(Exception e)
System.out.print(e);
e.printStackTrace();
%>
Retrieve
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
String id = request.getParameter("userid");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
%>
<!DOCTYPE html>
<html>
<body>
<table border="1">
<tr>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
</tr>
<%
try{
statement=connection.createStatement();
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("first_name") %></td>
<td><%=resultSet.getString("last_name") %></td>
<td><%=resultSet.getString("city_name") %></td>
<td><%=resultSet.getString("email") %></td>
</tr>
<%
connection.close();
} catch (Exception e) {
e.printStackTrace();
%>
</table>
</body>
</html>
Update:
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
String id = request.getParameter("id");
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
%>
<html>
<body>
<table border="1">
<tr>
<td>id</td>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
<td>update</td>
</tr>
<%
try{
statement=connection.createStatement();
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("id") %></td>
<td><%=resultSet.getString("first_name") %></td>
<td><%=resultSet.getString("last_name") %></td>
<td><%=resultSet.getString("city_name") %></td>
<td><%=resultSet.getString("email") %></td>
<td><a href="update.jsp?id=<%=resultSet.getString("id")%>">update</a></td>
</tr>
<%
connection.close();
} catch (Exception e) {
e.printStackTrace();
%>
</table>
</body>
</html>
DELETE
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
%>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<table border="1">
<tr>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
<td>Action</td>
</tr>
<%
try{
statement=connection.createStatement();
resultSet = statement.executeQuery(sql);
int i=0;
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("fname") %></td>
<td><%=resultSet.getString("lname") %></td>
<td><%=resultSet.getString("city_name") %></td>
<td><%=resultSet.getString("email") %></td>
</tr>
<%
i++;
connection.close();
} catch (Exception e) {
e.printStackTrace();
%>
</table>
</body>
</html>
delete.jsp
<%@page import="java.sql.*,java.util.*"%>
<%
String id=request.getParameter("id");
try
{
Class.forName("com.mysql.jdbc.Driver");
Statement st=conn.createStatement();
catch(Exception e)
System.out.print(e);
e.printStackTrace();
%>
Co-3
JavaServer Faces (JSF) is a framework developed by Oracle for building web applications
in Java. It simplifies the development of user interfaces (UIs) by providing a set of reusable
UI components and a standardized way to handle user interactions.
MVC Architecture
JSF adheres to the Model-View-Controller (MVC) design pattern, which separates the
application logic into three interconnected components:
1. Model:
o The model holds the state of the application and responds to requests from the
view.
2. View:
o In JSF, views are usually defined using XHTML files, which describe how the
UI components (like buttons, text fields, and tables) should be displayed to the
user.
o The view retrieves data from the model and presents it to the user, while also
capturing user input to send back to the model.
3. Controller:
Rich Set of UI Components: JSF comes with a library of standard components (e.g.,
forms, tables, buttons) and integrates easily with third-party component libraries (like
PrimeFaces) that offer additional features.
Data Binding: JSF allows for easy binding between UI components and managed
bean properties. This means that changes in the UI can automatically reflect in the
underlying data model and vice versa.
1. User Interaction: A user interacts with the UI (e.g., filling out a form).
2. Request Processing: When the user submits the form, JSF captures the request and
routes it to the appropriate managed bean (the controller).
3. Business Logic Execution: The managed bean processes the request, possibly
updating the model with the new data.
4. View Update: After processing, JSF prepares the response, updating the view with any
data changes (e.g., showing a success message).
5. Rendering: The updated view is rendered back to the user, displaying the latest
information.
JSF's ability to connect UI widgets, data sources, and server-side event handlers is one of its
key features, enabling the creation of dynamic and interactive web applications.
1. UI Widgets
In JSF, UI widgets are the components that users interact with in a web application. These
include elements like buttons, text fields, checkboxes, dropdown lists, and tables. JSF
provides a rich set of standard components, and you can also create custom components.
2. Data Sources
Data sources in JSF refer to the underlying data models that hold the application’s data. This
can include simple JavaBeans, databases, or any other data storage mechanism. In JSF, these
data models are typically represented as managed beans.
Example: A managed bean named UserBean could have a property name to hold the
user’s input:
@ManagedBean
return name;
this.name = name;
}
3. Event Handlers
Event handlers in JSF are methods in managed beans that respond to user actions, such as
button clicks or form submissions. These handlers can contain business logic to process the
data and perform operations like validation, data manipulation, or navigation to another page.
Life cycle
Phase 1: Restore view
JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a
request.
During this phase, JSF builds the view, wires event handlers and validators to UI components
and saves the view in the FacesContext instance. The FacesContext instance will now contain
all the information required to process a request.
After the component tree is created/restored, each component in the component tree uses the
decode method to extract its new value from the request parameters. Component stores this
value. If the conversion fails, an error message is generated and queued on FacesContext.
This message will be displayed during the render response phase, along with any validation
errors.
If any decode methods event listeners called renderResponse on the current FacesContext
instance, the JSF moves to the render response phase.
If the local value is invalid, JSF adds an error message to the FacesContext instance, and the
life cycle advances to the render response phase and displays the same page again with the
error message.
After the JSF checks that the data is valid, it walks over the component tree and sets the
corresponding server-side object properties to the components' local values. JSF will update
the bean properties corresponding to the input component's value attribute.
During this phase, JSF handles any application-level events, such as submitting a
form/linking to another page.
After the content of the view is rendered, the response state is saved so that subsequent
requests can access it and it is available to the restore view phase.
Managed Beans is a Java bean managed by JSF framework. Managed bean contains the
getter and setter methods, business logic, or even a backing bean (a bean contains all the
HTML form value).
Managed beans works as Model for UI component. Managed Bean can be accessed from JSF
page.
<managed-bean>
<managed-bean-name>helloWorld</managed-bean-name>
<managed-bean-class>com.example.test.HelloWorld</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Using Annotation
@RequestScoped
@ManagedBean Annotation
@ManagedBean marks a bean to be a managed bean with the name specified in name
attribute. If the name attribute is not specified, then the managed bean name will default to
class name portion of the fully qualified class name. In our case, it would be helloWorld.
Scope Annotations
Scope annotations set the scope into which the managed bean will be placed. If the scope is
not specified, then bean will default to request scope.
@RequestScoped
Bean lives as long as the HTTP request-response lives. It gets created upon a HTTP
1
request and gets destroyed when the HTTP response associated with the HTTP request is
finished.
@NoneScoped
2 Bean lives as long as a single EL(Expression Language) evaluation. It gets created upon
an EL evaluation and gets destroyed immediately after the EL evaluation.
@ViewScoped
Bean lives as long as the user is interacting with the same JSF view in the browser
3
window/tab. It gets created upon a HTTP request and gets destroyed once the user
postbacks to a different view.
@SessionScoped
Bean lives as long as the HTTP session lives. It gets created upon the first HTTP request
4
involving this bean in the session and gets destroyed when the HTTP session is
invalidated.
@ApplicationScoped
Bean lives as long as the web application lives. It gets created upon the first HTTP request
5 involving this bean in the application (or when the web application starts up and the
eager=true attribute is set in @ManagedBean) and gets destroyed when the web
application shuts down.
@CustomScoped
6 Bean lives as long as the bean's entry in the custom Map, which is created for this scope
lives.
Navigation
Navigation rules are those rules provided by JSF Framework that describes which view is to
be shown when a button or a link is clicked.
Navigation rules can be defined in JSF configuration file named faces-config.xml. They can
be defined in managed beans.
Navigation rules can contain conditions based on which the resulted view can be shown.
Implicit Navigation
JSF 2.0 provides auto view page resolver mechanism named implicit navigation. In this
case, you only need to put view name in action attribute and JSF will search the
correct view page automatically in the deployed application.
<h:form>
</h:form>
Here, when Page2 button is clicked, JSF will resolve the view name, page2 as page2.xhtml
extension, and find the corresponding view file page2.xhtml in the current directory.
Auto Navigation in Managed Bean
@RequestScoped
return "page1";
Get view name in action attribute of any JSF UI Component using managed bean.
<h:form>
</h:form>
Here, when Page1 button is clicked, JSF will resolve the view name, page1 as page1.xhtml
extension, and find the corresponding view file page1.xhtml in the current directory.
Conditional Navigation
Using managed bean, we can very easily control the navigation. Look at the following code
in a managed bean.
@RequestScoped
//this managed property will read value from request parameter pageId
@ManagedProperty(value = "#{param.pageId}")
if(pageId == null) {
return "home";
if(pageId.equals("1")) {
return "page1";
}else if(pageId.equals("2")) {
return "page2";
}else {
return "home";
<h:form>
</h:commandLink>
</h:commandLink>
</h:form>
import javax.ejb.Stateless;
@Stateless
public class CalculatorBean implements CalculatorRemote
{
@Override
public int add(int a, int b)
{
return a + b;
}
@Override
public int subtract(int a, int b)
{
return a - b;
}
}
o Stateful: A Stateful Session Bean (SFSB) is another type of Enterprise
JavaBean (EJB) in Java EE, which is designed to maintain state across multiple
method calls and transactions for a single client. Unlike stateless session
beans, stateful session beans are used when there is a need to keep
conversational state, meaning the bean retains data across method calls
made by the same client.
import javax.ejb.Stateful;
@Stateful
public class ShoppingCartBean implements ShoppingCart
{
private List<String> items = new ArrayList<>();
@Override
public void addItem(String item)
{
items.add(item);
}
@Override
public void removeItem(String item)
{
items.remove(item);
}
@Override
public List<String> getItems()
{
return items;
}
@Override
public void checkout()
{
// Perform checkout logic, such as processing payment and order
items.clear();
}
}
import javax.ejb.Singleton;
import javax.ejb.Lock;
import javax.ejb.LockType;
@Singleton
public class AppConfigBean
{
private String config;
@PostConstruct
public void init()
{
// Load initial configuration
config = "Default Configuration";
}
@Lock(LockType.READ)
public String getConfig()
{
return config;
}
@Lock(LockType.WRITE)
public void updateConfig(String newConfig)
{
config = newConfig;
}
@PreDestroy public void cleanup()
{
// Perform any cleanup actions before shutdown
System.out.println("Cleaning up singleton bean resources.");
}
}
Application Server
1. JBoss (WildFly):
o An open-source, widely-used Java EE application server that supports EJB
and other enterprise technologies. JBoss/WildFly is known for its flexibility
and robust performance in handling enterprise applications.
2. GlassFish:
o The reference implementation for Java EE (now Jakarta EE). It’s open-source
and provides a full-featured EJB container. GlassFish is often used for learning
or testing Java EE features.
3. WebLogic:
o A commercial application server from Oracle, known for its high performance
and strong support for large-scale, distributed enterprise applications. It
provides excellent clustering, high availability, and scalability features.
4. WebSphere:
o IBM’s enterprise application server that supports EJB, along with a host of
other enterprise services. It is known for its strong integration with enterprise-
level middleware and database solutions.
5. Apache TomEE:
Component Portability
EJB (Enterprise JavaBeans) refers to the ability of EJB components to be easily deployed
and executed across different Java EE-compliant application servers without modification.
This portability is one of the core goals of EJB, allowing developers to write business logic
once and deploy it in any application server that adheres to the Java EE specification.
How Component Portability Works in EJB:
1. Standardized Specification:
o which ensures that any application server implementing the specification must
follow a set of well-defined APIs and behaviors. This means that an EJB
component written according to the specification will work on any compliant
server (e.g., WildFly, WebLogic, GlassFish).
The EJB Component Model defines how business components, or Enterprise JavaBeans
(EJBs), are developed within an enterprise application. These components are managed by
the EJB container within an application server, providing services like transaction
management, security, concurrency, and persistence. The EJB component model simplifies
enterprise-level development by abstracting away the complexity of building distributed,
scalable, and secure applications.
Key Components of the EJB Component Model:
1. Session Beans:
o Types:
Stateless Session Beans: Do not retain state across method calls. They
are used for operations that do not require client-specific data to be
stored between invocations.
o MDBs are used to process asynchronous messages. They listen for messages
sent via messaging services (such as JMS – Java Message Service) and
perform background tasks when messages are received.
4. EJB Interfaces:
o EJBs are accessed through interfaces that define the contract between the
client and the business logic:
Local Interface: Used when the client and the bean are in the same
application or JVM.
Remote Interface: Allows remote clients to invoke EJB methods from
outside the application server or from a different JVM.
6. Transaction Management:
7. Lifecycle Management:
8. Security:
9. Dependency Injection:
EJB supports dependency injection through the @EJB annotation, allowing the
container to automatically inject references to other EJBs or resources (like data
sources) into the bean.
Java beans incorporate a set of objects into one accessible object that can be accessed
easily from any application. This single accessible object is maintainable,
customizable, and reusable. The setter/getter method and the single public constructor
are used to govern that single accessible object. We can update and read the value of
any variable of any object by using the setter and getter, respectively.
The EJB architecture has two main layers, i.e., Application Server and EJB
Container,
In the above diagram, the logical representation of how EJBs are invoked and
deployed by using RMI(Remote Method Invocation) is defined. The containers of the
EJB cannot be self-deployed. In order to deploy the containers, it requires the
Application server.
Application Server
In the EJB architecture, the Application server is the outermost layer that holds or
contains the Container to be deployed. The application layer plays an important role
in executing the application developed using the beans. It provides the necessary
environment to execute those applications. Some most popular application servers are
Web-logic, Tomcat, JBoss, Web-sphere, Wildfly, and Glass-finish. The main tasks of
the application server are:
1. Manage Interfaces
Container
In EJB architecture, the Container is the second outermost layer. It is a very important
layer for enterprise beans that are contained in it. For the enterprise bean, the
Container provides various supporting services, which are as follows:
o It provides support for transactional services such as registering the objects, assign
remote interfaces, purge the instances.
o It provides support for monitoring the object's activities and coordinating distributed
components.
o It provides support for managing the Life-cycle of beans and their concurrency.
Beans
Java beans of the enterprise are installed in the Container in the same way as a Plain
old java object (POJO) is installed and registered to the Container. For developing
secured, large scale and robust business applications, beans provide business logic.
Types of EJB
There are three types of Enterprise Java Beans or EJB available, which are as
follows:
1. Stateless Enterprise Java Beans
Stateless EJB
In order to implement the stateless business logic, the stateless EJBs are primarily
used. Storing a user's physical address into an inventory system's database is an
example of the stateless EJB. In addition, a stateless bean would be perfect for this
type of business logic because it is not necessary to have more than two forms on the
user interface at all stages of the transaction.
StatelessBeanExample.java
Advertisement
1. package com.javatpoint.ejbarchitecture;
2. import javax.ejb.Stateless;
3.
4. @Stateless
6. }
Stateful EJB
The Stateful EJB is just opposite to the Stateless EJB. The Stateful EJBs are used
when we have to maintain the state of the application on the backend during the user
session. The shopping cart of an online shopping application is an example of
the Stateful EJB.
StatelessBeanExample.java
1. package com.javatpoint.ejbarchitecture;
2. import javax.ejb.Stateful;
3.
4. @Stateful
6. }
Message-driven EJB
Another special type of EJB that is used for sending and receiving messages from
message brokers implements the JMS specification. The systems based on the broker
are loosely coupled. The components that communicate through the broker have the
advantage of not waiting for one request to finish before submitting another request
because the broker by nature is asynchronous.
MessageDrivenBeanExample.java
1. package com.javatpoint.ejbarchitecture;
2. import javax.ejb.MessageDriven;
3. import javax.jms.MessageListener;
4. import javax.jms.Message;
5. import javax.ejb.ActivationConfigProperty;
6.
10. })
12.
14. }
15. public void onMessage(Message message) {
17. }
18. }
S.No. EJB JB
3. Business Method Invocation: The client calls business methods on the bean.
2. State Maintenance: The bean maintains state information for the client.
3. Business Method Invocation: The client calls methods, and the bean retains its
state.
4. Removal: The bean is removed when the session ends or the client invokes the
remove() method.
Singleton Bean:
2. Business Method Invocation: The client calls methods, accessing the same
instance.
EJB clients
are components or applications that interact with Enterprise JavaBeans (EJBs) to utilize their
business logic and services. Clients can be either local or remote, depending on their location
relative to the EJB server. Here’s a detailed overview of EJB clients, their types, and how
they interact with EJBs.
o Local clients run in the same Java Virtual Machine (JVM) as the EJB
container. They can access EJBs directly without using network protocols,
making the invocation faster and more efficient.
o Example: A servlet running on the same application server can be a local client
to session beans.
o Remote clients run in different JVMs and need to communicate with the EJB
container over a network. Remote clients use remote interfaces for method
calls.
o The EJB container exposes remote interfaces using RMI (Remote Method
Invocation), making it possible for clients to invoke methods as if they were
local.
Although POJOs existed before, they play a more important role in the programming
methodology of Java. now create EJB applications with persistence capabilities by using
enterprise beans and entities created from POJOs.
The POJO programming model enables you to unit test outside of the application server,
making the whole programming experience smoother.
A simple POJO
public class Test {
String name;
/**
**/
public Test(){
name = "Jane";
To create an EJB 3.0 bean, inject a component defining annotation at the class level. The
following example turns a POJO into a stateless session bean by adding the @Stateless
annotation.
@Stateless
String name;
/**
**/
public Test () {
name = "jane";
In a real application, the POJO needs additional business logic. The fundamental idea of
using POJOs in the context of the Java EE specification is to associate Metadata about
your component to be associated directly in your POJO. This approach reduces the
number of artifacts you need to deal with and makes it easier to ensure the integrity of
your Metadata.
EJB 3.0 provides option to define database entity relationships/mappings like one-to-
one, one-to-many, many-to-one, and many-to-many relationships.
Book_Author − Book Author table, having linkage of above mentioned Book and
Author table.
Create Tables
Create a table book, author, book_author in default database postgres.
book_id integer,
name varchar(50)
);
author_id integer,
name varchar(50)
);
book_id integer,
author_id integer
);
@Entity
@Table(name="author")
...
}
@Entity
@Table(name="book")
...
@Entity
...
, fetch = FetchType.EAGER)
return authors;
...
}
JAX-RS Example Jersey
We can create JAX-RS example by jersey implementation. To do so, you need to load
jersey jar files or use maven framework.
In this example, we are using jersey jar files for using jersey example for JAX-RS.
1. Hello.java
2. web.xml
3. index.html
4. HelloWorldClient.java
The first 3 files are created for server side and 1 application for client side.
File: Hello.java
1. package com.javatpoint.rest;
2. import javax.ws.rs.GET;
3. import javax.ws.rs.Path;
4. import javax.ws.rs.Produces;
5. import javax.ws.rs.core.MediaType;
6. @Path("/hello")
7. public class Hello {
9. @GET
10. @Produces(MediaType.TEXT_PLAIN)
13. }
15. @GET
16. @Produces(MediaType.TEXT_XML)
19. }
20.
22. @GET
23. @Produces(MediaType.TEXT_HTML)
27. }
28. }
File: web.xml
3. xmlns="http://java.sun.com/xml/ns/javaee"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
6. id="WebApp_ID" version="3.0">
7. <servlet>
9. <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
10. <init-param>
11. <param-name>jersey.config.server.provider.packages</param-name>
12. <param-value>com.javatpoint.rest</param-value>
13. </init-param>
14. <load-on-startup>1</load-on-startup>
15. </servlet>
16. <servlet-mapping>
18. <url-pattern>/rest/*</url-pattern>
19. </servlet-mapping>
20. </web-app>
File: index.html
Now run this application on server. Here we are using Tomcat server on port 4444. The
project name is restfuljersey.
After running the project, you will see the following output:
JAX-RS Client Code
The ClientTest.java file is created inside the server application. But you can run client
code by other application also by having service interface and jersey jar file.
Advertisement
File: ClientTest.java
1. package com.javatpoint.restclient;
2. import java.net.URI;
3. import javax.ws.rs.client.Client;
4. import javax.ws.rs.client.ClientBuilder;
5. import javax.ws.rs.client.WebTarget;
6. import javax.ws.rs.core.MediaType;
7. import javax.ws.rs.core.UriBuilder;
8. import org.glassfish.jersey.client.ClientConfig;
15. System.out.println(target.path("rest").path("hello").request().accept(MediaT
ype.TEXT_PLAIN).get(String.class));
16. System.out.println(target.path("rest").path("hello").request().accept(MediaT
ype.TEXT_XML).get(String.class));
17. System.out.println(target.path("rest").path("hello").request().accept(MediaT
ype.TEXT_HTML).get(String.class));
18. }
20. //here server is running on 4444 port number and project name is restfuljersey
22. }
23. }
Output:
This how-to shows you how to do this using an example in which you create an app that
retrieves Wikipedia pages from a REST service. The resulting app is available for
download.
Creating a published REST service on top of the system you want to integrate with is
outside the scope of this how-to; for instructions on how to do this, refer to the
configuration of your non-Mendix Platform.
If the system you want to integrate into your app has the functionality for exposing its
data to REST services, you can integrate it easily into your Mendix app using consume
REST service. Each system has a different JSON structure based on internal data
models.
You are going to use the Wikipedia REST service as an example in this how-to. It allows
you to retrieve the summary of a Wikipedia page – in this case information about a
country. This service can be reached
at https://en.wikipedia.org/api/rest_v1/page/summary/{title}, where {title} is the title of
a page.
We will start by providing to Studio Pro an example of what the REST service returns:
3. Copy the whole JSON snippet. Make sure that you select the Raw Data tab to
copy the whole code structure.
6. In the JSON Structure dialog box, paste the JSON snippet in the General tab
and click Refresh. This analyzes the structure of the JSON snippet that we can
use later.
7. Click OK.
An import mapping specifies how the JSON relates to entities. You can map the JSON
to any entity you like. The following steps describe how to generate the entities and
create an import mapping:
1. Right-click the module in the Project Explorer and select Add other > Import
Mapping.
2. Enter a Name for the import mapping: Import_mapping and click OK.
3. In the Select schema elements for import mapping dialog box, click the radio
button for JSON structure and then click Select.
6. Click OK. The Import_mapping document is displayed and the JSON structure
is on the right.
8. A pop-up box is displayed informing you that can See the details for the changes
that have been applied. You can click Details to see details of the mapping to the
entities that are generated to match the JSON structure.
The service takes the title of the page as an input and it returns the summary of the
page from Wikipedia.
In this section, you will create an entity that represents this input and associate it with
its summary.
6. On the Attributes tab, click New to add a string attribute and name it Title.
7. Click OK.
11. In the Map entity ‘Summary from the object element ‘Summary dialog box, Set
association to Yes and select the RESTconsume_input_Summary for
the Association to have the import mapping set the association:
You will now call the REST service in a microflow to build the integration with
Wikipedia. The microflow takes Input as the input parameter and sets the
associated Summary.
1. Right-click the module and select Add > Microflow and accept the
default Name Microflow for the name of the microflow and click OK.
2. From the tool bar, drag a Parameter object to the microflow document.
3. Click Select for the Data type and select the Input entity as the input parameter.
Click OK.
4. Right-click the mouse and select Insert > Activity to insert an activity to the
microflow. Double-click the activity and select the Call REST service to change
the activity.
5. In the Call REST dialog box, click Edit for the Location and add the following
to Template: https://en.wikipedia.org/api/rest_v1/page/summary/{1}, with the
parameter being the Title attribute from the Input parameter $Input/Title.
Click OK.
6. In the Response tab, the response has to be mapped using the import mapping.
For Response handling select Apply import mapping.
7. For Mapping, click Select and double-click Import_mapping. For the Parameter,
select Input.
8. For Output select Yes for Store in variable and specify Summary for the Variable
name.
9. Click OK.
10. Right-click after the Call REST service object and select Insert > Activity and
double-click it and change it to a Change object.
12. For Refresh in client, select Yes. This ensures that the summary is displayed on
the screen.
17. Click OK. You have created microflow that takes the title of an article as input
and associates it with its summary.
You have successfully consumed a REST service and created a microflow to show the
results. The rest of this how-to describes how to use this microflow in an app so that you
can see the REST call in action.
Creating a Page
2. Right-click the [Unknown] bar and click, Select entity. Select the Input entity.
4. For the Name, enter CreateInput. Note that when this page loads, it needs a
new Input object – you will define the CreateInput microflow that creates this
object in Filling In the Create Input Microflow.
5. Click OK.
6. From Container widgets, add a new Table with one row and two columns.
8. From the Project Explorer, drag Microflow into the right column.
9. Double-click the Microflow button and in the Edit Action Button dialog box,
enter Get summary for the caption of the button.
10. Add a Data view below the table (inside the other data view).
11. From the Connector, drag the Summary entity onto the [Unknown] bar.
13. From this data view, delete all the fields except Extract.
Now all that is left is to have the CreateInput microflow create a new Input object.
4. For Entity, click Select and double-click Input, then click OK.