You are on page 1of 33

MERI

SESSION(2017-2018)

ASSIGNMENT OF J2EE

GUIDED BY MrS. Samyuktha mutteni

SUBMITTED BY-

NAME- Vishal Bhardwaj

Enrollment no.-01615124416

COURSE-MCA(le) 5th SEMSETER

Teacher signature- ____________________Remark-________________


ASSIGNMENTS-1

S.No. NAME OF THE ACTIVITY Remark Signature Of


teacher
1. Differentiate between two tier, three tier and
n-tier architecture.
2. Differentiate between enterprise architecture
and MVC architecture.
3. Define Servlet. Explain the lifecycle of a servlet
with help of a diagram.
4. Write a short note on generic servlet and HTTP
servlet.
5. Explain the various session tracking
techniques.
6. Define directive, explain different type of JSP
directives.
7. what are the design strategies of JSP.
8. Define struts, explain the application of struts.
9.
10.
Enterprise Computing in java

Assignment -1
Q.1 Differentiate between two tier, three tier and n-tier architecture.

Ans- The J2EE platform is a multi-tiered system. A tier is a logical or functional partitioning of a system.

1) 2-Tier Architecture

User Interface/Display is Client --> Data Base, Data and Business Logic is Database

Def:The 2-tier is based on Client Server architecture. The two-tier architecture is like client server
application. The direct communication takes place between client and server. There is no intermediate
between client and server. Because of tight coupling a 2 tiered application will run faster.

Architecture:

The above figure shows the architecture of two-tier. Here the direct communication between client and
server, there is no intermediate between client and server.

The Two-tier architecture is divided into two parts:

1) Client Application (Client Tier)


2) Database (Data Tier)

On client application side the code is written for saving the data in the SQL server database. Client sends
the request to server and it process the request & send back with data. The main problem of two tier
architecture is the server cannot respond multiple request same time, as a result it cause a data integrity
issue.

Advantages:

1. Easy to maintain and modification is bit easy


2. Communication is faster
Disadvantages:

1. In two tier architecture application performance will be degrade upon increasing the users.
2. Cost-ineffective

2) 3-Tier Architecture

User Interface/Display is Client -->Business or Database Logic --> Data Base, Data is Database

Def:3-tier architecture typically comprises a presentation tier, a business or data access tier, and
a data tier.

Architecture:

Three layers in the three tier architecture are as follows:

1) Client layer
2) Business layer
3) Data layer

1) Client layer:

It is also called as Presentation layer which contains UI part of our application. This layer is used for the
design purpose where data is presented to the user or input is taken from the user. For example
designing registration form which contains text box, label, button etc.

2) Business layer:

In this layer all business logic written likes validation of data, calculations, data insertion etc. This acts as
a interface between Client layer and Data Access Layer. This layer is also called the intermediary layer
helps to make communication faster between client and data layer.
3) Data layer:

In this layer actual database is comes in the picture. Data Access Layer contains methods to connect
with database and to perform insert, update, delete, get data from database based on our input data.

Advantages

1. High performance, lightweight persistent objects


2. Scalability – Each tier can scale horizontally
3. Performance – Because the Presentation tier can cache requests, network utilization is
minimized, and the load is reduced on the Application and Data tiers.
4. High degree of flexibility in deployment platform and configuration
5. Better Re-use
6. Improve Data Integrity
7. Improved Security – Client is not direct access to database.
8. Easy to maintain and modification is bit easy, won’t affect other modules
9. In three tier architecture application performance is good.

Disadvantages

1. Increase Complexity/Effort

3) Multi-Tier or n Tier Architecture

User Interface/Display is Client -->Business or Database Logic --> Data Base, Data is Database

Client:

Tier-1 Client Tier

Applets, HTML,php, JavaScript, Application Clients etc

Middle Tier:

Tier-2 Presentation Tier

a) HTML, CSS, GIF Files etc (static content) available in Web Server

b) JSPs, Servlets, Tags etc (dynamic content) available in Application server

Tier-3 Business Tier

EJB, Java Classes, Business Objects etc available in Application server

Tier-4 Integration Tier

JMS, JDBC, Connectors (JCA), etc available in Application server

Note: It may be more than 4 Tier as per Architecture


Database Tier:

Tier-N Resource/Data Tier

Databases like RDBMS, XML, EXCEL, ERP &CRM systems, Legacy Systems etc

The advantages of a 3-tiered or n-tiered application: 3-tier or multi-tier

Advantages:

a. Managing data is independent from the physical storage

b. Migration to new graphical environments is faster

c. It is possible to make changes on the presentation level without affecting the other two (business or
data access layer)

d. As each tier is independent it is possible to use different sets of developers

e. Since the client doesn’t have direct access to the database business logic is more secure

f. When one tier fails there is no data loss, because you are always secure by accessing the other tier.

Disadvantages:

a. It is more complex structure

b. More difficult to set up and maintain it as well

c. The physical separation of the tiers may affect the performance between the three

d. It is more difficult to built a 3-tier application


Q.2 Differentiate between enterprise architecture and MVC architecture.

Ans-

J2EE Architecture

J2EE multi-tiered applications are generally considered to be three tiered applications because they are
distributed over three different locations:

 client machines
 the J2EE server machine
 the database or legacy machines at the back end

 Three-tiered applications that run in this way extend the standard two-tiered client and server
model by placing a multithreaded application server between the client application and back-
end storage.
J2EE Containers

 The application server maintains control and provides services through an interface or
framework known as a container.
 There are five defined container types in the J2EE specification.
 Three of these are server-side containers:
1. The server itself, which provides the J2EE runtime environment and the other two
containers.
2. An EJB container to manage EJB components.
3. A Web container to manage servlets and JSP pages.

 The other two container types are client-side:


1. An application container for stand-alone GUIs, console.
2. An applet container, meaning a browser, usually with the Java Plug-in.

J2EE Components

 J2EE applications are made up of components.


 A J2EE component is a self-contained functional software unit that is assembled into a J2EE
application with its related classes and files and that communicates with other components.
 J2EE Components:
1. Client components run on the client machine, which correlate to the client containers.
2. Web components - servlets and JSP pages.
3. EJB Components - Entity Beans, Session Beans.

Model 2 (MVC) Architecture


Model 2 is based on the MVC (Model View Controller) design pattern. The MVC design pattern consists
of three modules model, view and controller.

Model The model represents the state (data) and business logic of the application.

View The view module is responsible to display data i.e. it represents the presentation.

Controller The controller module acts as an interface between view and model. It intercepts all the
requests i.e. receives input and commands to Model / View to change accordingly.

Advantage of Model 2 (MVC) Architecture


o Navigation control is centralized Now only controller contains the logic to determine the next
page.
o Easy to maintain
o Easy to extend
o Easy to test
o Better separation of concerns

Disadvantage of Model 2 (MVC) Architecture


o We need to write the controller code self. If we change the controller code, we need to
recompile the class and redeploy the application.
Q.3 Define Servlet. Explain the lifecycle of a servlet with help of a diagram.

Ans-

Def: Servlets came into the Java world to help develop Web Applications. Web applications run over the
web and are consumed by end user. It should not be confused with Web Services, which are consumed
by a program as opposed to end user. A typical example of Web Application would be a Shopping Kart
Application, which can be accessed over HTTP protocol from a web browser.

What are Servlet?

1. A Servlet is a Java program that runs on a Web Container. The Web Container is capable of
handling HTTP requests and responses.
2. Servlets act as an inter-mediatory interface between HTTP requests originated from Web
Browsers (IE, Chrome etc) and Java Applications hosted on Application Servers.
3. Servlet runs as a light-weight thread instead of a separate OS process. This is opposed to a CGI
script in which a new OS process is created for each request, making it heavy-weight and
impacting performance.
4. Servlets can be used to collect form inputs from a page
5. Servlet specification is released by Oracle, which vendors implement to create their own Web
Containers.
6. Most popular Open Source Web Containers are: Apache Tomcat, Jetty and Glassfish.
7. A Servlet can run on any web container as it is developed using a common Servlet-API.
8. We must import javax.servlet.*; javax.servlet.http.*; in order to create a servlet.

Servlet Container

1. The most popular Servlet Container today is Tomcat. It is very light-weight and easy to develop
and deploy applications on Tomcat.
2. Originally Tomcat was built by Sun MicroSystems, and later was handed over to the Apache
Software Foundation in October 1999.
3. It can be easily integrated with all popular IDE's (like Eclipse, NetBeans etc) and promotes ease
of development.

Servlet Life Cycle


The life cycle contains the following steps:

1. Load Servlet Class.


2. Create Instance of Servlet.
3. Call the servlets init() method.
4. Call the servlets service() method.
5. Call the servlets destroy() method.

1. init() method:-

 The servlet is initialized by calling the init () method.


 The init method is called only one time,when servlet is first created,never call again for each
user request.
 The init() method simply create or load some data that will be used overall life of the servlet.

public void init() throws ServletException {


//initialize code....
}

2. service()method:-

 The servlet container calls the service() method to handle requests coming from the client or
browsers and to write the formatted response back to the client.

 The service() method checks the HTTP request type such as GET ,POST etc and calls doGet,
doPost etc.
public void service (ServletRequest request,

ServletResponse response) throws ServletException, IOException


{
}

doGet() Method:-

 GET is HTTP method. it works to tell server to get a resource and send it server.
 it should be handled by doGet() method.

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException


{
// Servlet code
}

doPost() Method:-

 POST ,you can request something and at same time send form data to server.
 it should be handled by doPost() method.

public void doPost (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException


{
// Servlet code

3. destroy() method :-

 The destroy() method is called only one time at the end of the life cycle of a servlet.
 It gives opportunity to clean up any resource such as Memory,thread etc.

public void destroy()


{
// Finalization code...
}
Q.4 Write a short note on generic servlet and HTTP servlet.

Ans-Generic servlet

Des:

 It is abstract class.
 GenericServlet implements the Servlet, ServletConfig, Serializable interfaces.
 It implements some lifecycle methods.
 GenericServlet may be directly extended by a servlet, Even though it's more common to extend
a protocol-specific subclass such as HttpServlet.

Method Description

void log(String s) It writes the specified message to a servlet log file.

void log(String s, It writes an explanatory message and a stack trace for a given Throwable exception
Throwable e) to the servlet log file.

HTTP servlet

Des:
 It is an abstract class and extends the Generic Servlet.
 To create your own Servlet, you need to subclass HttpServlet.
 A subclass of HttpServlet must override at least one methods listed below:

Method Description

protected void doGet( Called by the server through service() to allow a servlet to handle a GET request.
HttpServletRequest req, Parameters: Object HttpServletRequest(req) that contains the request the client has
HttpServletResponse made of the servlet. Object of HttpServletResponse(resp) that contains the response
resp) the servlet sends to the client
throws
ServletException,
IOException

protected void doPost( Called by the server through service() to allow a servlet to handle a POST request.
HttpServletRequest req, Parameters: Object of HttpServletRequest(req) that contains the request the client has
HttpServletResponse made of the servlet. Object of HttpServletResponse that contains the response the
resp) servlet sends to the client.
throws ServletException,
IOException
Method Description

protected long Returns last modified time in miliseconds.


getLastModified(
HttpServletRequest req)

protected void doHead(


HttpServletRequest req,
HttpServletResponse
resp)
throws ServletException,
IOException

protected void doPut( Called by the server to allow a servlet to handle a PUT requests. Parametrs: Object of
HttpServletRequest req, HttpServletRequest(req)that contains the request the client made of the servlet.
HttpServletResponse Object of HttpServletResponse(resp) that contains the response the servlet returns to
resp) the client.
throws ServletException,
IOException.

protected void doTrace( Called by the server to allow a servlet to handle a TRACE request.
HttpServletRequest req,
HttpServletResponse
resp)
throws ServletException,
IOException

protected void service( Receives standard HTTP and responds by calling doXXX() method defined in the
HttpServletRequest req, servlet.
HttpServletResponse
resp)
throws ServletException,
IOException

doOptions protected Called by the server to allow a servlet to handle a OPTIONS request.
void doOptions(
HttpServletRequest req,
HttpServletResponse
resp)
throws ServletException,
IOException
HttpServlet GenericServlet
HttpServlet defines a HTTP protocol specific GenericServlet defines a generic, protocol-independent
servlet. servlet.

It inherit generic servlet class. It implements servlet interface.

It use doGet and doPost method instead of It use service method.


service.
Q.5 Explain the various session tracking techniques.

Ans-Des:

 HTTP is a stateless protocol ,where each request and response both is independent of other web
interactions.
 it is necessary to save state information so that information can be collected from several
interactions between a browser and a server. Sessions provide such a mechanism.
 A new session is created if one does not already exist.

 It is required to implement session management capabilities that link both the authentication
and access control modules commonly available in web applications.

Approaches to Session-Tracking:-

1. Session API
2. URL -rewriting
3. Cookies
4. Hidden Form Field

1. Session API(HttpSession interface)


Java Servlet API provides an interface called HttpSession that can be used to keep track of sessions in
the Current servlet context.

Method Description

HttpSession This method is use to reterive the current the HttpSession that is associated with
s=request.getSession() user. if session does not exist,then a session can be created by using getSession(true)

boolean b=s.IsNew(); returns the Value true If the new Session ID has been created and has not been sent
the client.

s.invalidate() Returns nothing and it is used to destroy the existing session.

long l=s.getCreationTime(); This function returns the time when the session was created in miliseconds.

long This function returns the previous time a request was made with same sessionId.
l=s.getLastAccessedTime();
Method Description

s.setAttribute("userid",a) Used to set session attribute in session Object.

Object Used t reterive the set Attribute value.


o=s.getAtribute("userid");

Setting Session timeout:


You don't have to use them to get rid of stale (inactive) sessions.
The container can do it for you.

Three ways a session can die:

1. It times out.
2. You call invalidate() on the session object.
3. The application goes down (Crashes or is undeployed).

Configure Session Time out in DD:


<session-config>
<session-timeout>15</session-timeout> //15 min
</session-config>
or
session.setMaxInactiveInterval (20*60); //20 minute

2. URL-rewritting
 If Client Cookie is disable so Session API fails .
 If client won't take cookies, you can use URL rewriting as a back up.
 URL rewriting is a better way to maintain sessions when the browsers don't support cookie So
URL rewriting is a better way to maintain sessions
 Now put the session ID with URL.
 It likes http://abc.com/email.do; jsessionid="0AAB678C99D1E415",

response.encodeURL ("/WelcomeServlet"); response.encodeRedirectURL ("/WelcomeServlet");


3. Cookies

What is Cookie?

 Cookies are small text files that are used by a Web server to keep track of users.
 A cookie has value in the form of key-value pairs.
 They are created by the server and sent to the client with the HTTP response headers.
 javax.servlet.http.Cookie class is used to represent a cookie.

 To create cookie object:

Cookie ck = new Cookie("key","value");

 To add cookie to browser:

Response.addCookie(ck); // addCookie method takes cookie objects as argument

 To get cookie:

Cookie ck[]=request.getCookies();
 A server can send one or more cookies to the client.

 A web-browser, which is the client software, is expected to support 20 cookies per host and the
size of each cookie can be a maximum of 4 bytes each.

Cookie Method Description

Cookie c=new Cookie("userpref","red"); Creating a cookie Object.

c.setMaxAge(int); This method is used to specify the maximum amount of time for which the
client browser retain the cookie value.

HttpServletResponse.addCookie(c); To send cookie client.

Cookie Reterive all cookies.


c[]=HttpServletResponse.getCookies.
Cookie Method Description

c.getName() To reterive cookie name.

4. Using Hidden Form Fields

 Hidden form fields is simplest session tracking techniques.


 It can be used to keep track of users by placing hidden fields in a form.
 The values that have been entered in these fields are sent to the server when the user submits
the form.
 For Example:

<input type="hidden" name="text1" value=20>


Q.6 Define directive, explain different type of JSP directives.

Ans-

Def:The jsp directives are messages that tell the web container how to translate a JSP page into the
corresponding servlet.

There are three types of directives:

 page directive
 include directive
 taglib directive

Syntax of JSP Directive

<%@ directive attribute="value" %>

JSP page directive

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

<%@ page attribute="value" %>

Attributes of JSP page directive


 import
 contentType
 extends
 info
 buffer
 language
 isELIgnored
 isThreadSafe
 autoFlush
 session
 pageEncoding
 errorPage
 isErrorPage

1)import
The import attribute is used to import class,interface or all the members of a package.It is similar to
import keyword in java class or interface.
Example of import attribute
<html>
<body>

<%@ page import="java.util.Date" %>


Today is: <%= new Date() %>

</body>
</html>

2)contentType

The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP
response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute


<html>
<body>

<%@ page contentType=application/msword %>


Today is: <%= new java.util.Date() %>

</body>
</html>

3)extends

The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely
used.

4)info

This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.

Example of info attribute


<html>
<body>

<%@ page info="composed by Sonoo Jaiswal" %>


Today is: <%= new java.util.Date() %>

</body>
</html>

The web container will create a method getServletInfo() in the resulting servlet.For example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}

5)buffer

The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The
default size of the buffer is 8Kb.

Example of buffer attribute


<html>
<body>

<%@ page buffer="16kb" %>


Today is: <%= new java.util.Date() %>

</body>
</html>

6)language

The language attribute specifies the scripting language used in the JSP page. The default value is "java".

7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is
false i.e. Expression Language is enabled by default. We see Expression Language later.

<%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use
isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it false,
the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding
to a request before passing another request to it.If you make the value of isThreadSafe attribute like:

<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

public class SimplePage_jsp extends HttpJspBase


implements SingleThreadModel{
....... }
9)errorPage

The errorPage attribute is used to define the error page, if exception occurs in the current page, it will
be redirected to the error page.

Example of errorPage attribute


//index.jsp
<html>
<body>

<%@ page errorPage="myerrorpage.jsp" %>

<%= 100/0 %>

</body>
</html>

10)isErrorPage

The isErrorPage attribute is used to declare that the current page is the error page.

Note: The exception object can only be used in the error page.

Example of isErrorPage attribute


//myerrorpage.jsp
<html>
<body>

<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>


The exception is: <%= exception %>

</body>
</html>
Q.7 what are the design strategies of JSP.

Ans-Design Strategies
Des-
• Many dozens of design strategies have been developed for web applications.

• There are introduces two :


1. Page-centric : Requests are made to JSPs, and the JSPs respond to clients.

2. Dispatcher : Requests are sent to JSPs or servlets that then forward the requests to another JSP or
servlet.

In both cases, the goal is to separate logic from presentation and to separate as many concerns in the
logic as possible.

• This is a simple design to implement.


• The JSP author can generate pages easily.

• Two variants :
– Page-View
– Page-View with a Bean.
• Does not scale up very well to large web sites.

• Often results in a lot of Java code in the JSP


– JSP authors must be Java programmers
– Design is hard to see
– Hard to maintain.
(2) Dispatcher Design
• A “dispatcher” accepts requests and routes them to the correct place
• Front-end JSP (or servlet) looks at a portion of the request, and then chooses the correct place to
forward it.
• This is more sophisticated than the page-centric:
– More flexible and scalable.
– More overhead that is wasted with small applications.

• Three versions
– Mediator-View
– Mediator
-Composite View
–Service to Workers
(2-A) Mediator-View Design
• The Mediating JSP sends requests to a JSP.
• The JSP sets and gets beans and creates a response page.

(2-B) Mediator-Composite Design


• The mediator-view helps with dynamically changing data, but sometimes the structure around the
data changes.
• Consider a web site that sells books, CDs, and videos – The title, author and price form the data – The
structure will be different with each type of item.
• With a mediator-view, the JSP has to be changed to introduce new types of products.
• The mediator-composite architecture allows nesting of JSPs and HTML …
(2-B) Mediator-Composite Design cont…
• In this architecture, the JSP makes direct calls to the business logic modules.
• This creates a tight coupling between the JSP and the execution or business logic.
• In the next architecture, the JSP is separated further from the business logic modules.

(2-C) Service to Workers Design


• The mediator sends requests to “worker beans”.
• The worker beans use the back-end software to populate the beans with data.
• The JSPs then take the data and create output pages.
• This method breaks up the “view” and the “controller”.
• Useful when many methods are needed to generate the data.
Q.8 Define struts, explain the application of struts.

Ans-Des:

 Struts2 is a free Open Source Framework.


 Apache Struts2 was originally known as WebWork 2. After working independently for several
years, the WebWork and Struts communities joined forces to create Struts2.
 It is based on MVC2 Architecture.
 In Struts 2 FilterDispatcher does the job of Controller.
 Model contains the data and the business logic.
 In Struts 2 the model is implemented by the Action component.
 View is the presentation component of the MVC Pattern.
 In Struts 2 View is implemented by JSP
 Struts 2 are a pull-MVC framework. I.e. the data that is to be displayed to user has to be pulled
from the Action. The "pull" comes from the views ability to pull data from an action using Value
Stack/OGNL.
 Struts 2 Action class are plain POJO objects thus simplifying the testing of the code.

Steps to create Struts 2 Application Example

In this example, we are creating the struts 2 example without IDE. We can simply create the struts 2
application by following these simple steps:

1. Create the directory structure


2. Create input page (index.jsp)
3. Provide the entry of Controller in (web.xml) file
4. Create the action class (Product.java)
5. Map the request with the action in (struts.xml) file and define the view components
6. Create view components (welcome.jsp)
7. load the jar files
8. start server and deploy the project

1) Create the directory structure

The directory structure of struts 2 is same as servlet/JSP. Here, struts.xml file must be located in the
classes folder.
2) Create input page (index.jsp)

This jsp page creates a form using struts UI tags. To use the struts UI tags, you need to specify uri /struts-
tags. Here, we have used s:form to create a form, s:textfield to create a text field, s:submit to create a
submit button.

index.jsp

1. <%@ taglib uri="/struts-tags" prefix="s" %>


2. <s:form action="product">
3. <s:textfield name="id" label="Product Id"></s:textfield>
4. <s:textfield name="name" label="Product Name"></s:textfield>
5. <s:textfield name="price" label="Product Price"></s:textfield>
6. <s:submit value="save"></s:submit>
7. </s:form>
1. <%@ taglib uri="/struts-tags" prefix="s" %>
2. <s:form action="product">
3. <s:textfield name="id" label="Product Id"></s:textfield>
4. <s:textfield name="name" label="Product Name"></s:textfield>
5. <s:textfield name="price" label="Product Price"></s:textfield>
6. <s:submit value="save"></s:submit>
7. </s:form>

3) Provide the entry of Controller in (web.xml) file

In struts 2, StrutsPrepareAndExecuteFilter class works as the controller. As we know well, struts 2 uses
filter for the controller. It is implicitly provided by the struts framework.
web.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <web-app>
3. <filter>
4. <filter-name>struts2</filter-name>
5. <filter-class>
6. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
7. </filter-class>
8. </filter>
9. <filter-mapping>
10. <filter-name>struts2</filter-name>
11. <url-pattern>/*</url-pattern>
12. </filter-mapping>
13. </web-app>
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app>
3. <filter>
4. <filter-name>struts2</filter-name>
5. <filter-class>
6. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
7. </filter-class>
8. </filter>
9. <filter-mapping>
10. <filter-name>struts2</filter-name>
11. <url-pattern>/*</url-pattern>
12. </filter-mapping>
13. </web-app>

4) Create the action class (Product.java)

This is simple bean class. In struts 2, action is POJO (Plain Old Java Object). It has one extra
method execute i.e. invoked by struts framework by default.

Product.java

1. package com.javatpoint;
2.
3. public class Product {
4. private int id;
5. private String name;
6. private float price;
7. public int getId() {
8. return id;
9. }
10. public void setId(int id) {
11. this.id = id;
12. }
13. public String getName() {
14. return name;
15. }
16. public void setName(String name) {
17. this.name = name;
18. }
19. public float getPrice() {
20. return price;
21. }
22. public void setPrice(float price) {
23. this.price = price;
24. }
25.
26. public String execute(){
27. return "success";
28. }
29. }
1. package com.javatpoint;
2.
3. public class Product {
4. private int id;
5. private String name;
6. private float price;
7. public int getId() {
8. return id;
9. }
10. public void setId(int id) {
11. this.id = id;
12. }
13. public String getName() {
14. return name;
15. }
16. public void setName(String name) {
17. this.name = name;
18. }
19. public float getPrice() {
20. return price;
21. }
22. public void setPrice(float price) {
23. this.price = price;
24. }
25.
26. public String execute(){
27. return "success";
28. }
29. }
5) Map the request in (struts.xml) file and define the view components

It is the important file from where struts framework gets information about the action and decides
which result to be invoked. Here, we have used many elements such as struts, package, action and
result.

struts element is the root elements of this file. It represents an application.

package element is the sub element of struts. It represents a module of the application. It generally
extends the struts-defaultpackage where many interceptors and result types are defined.

action element is the sub element of package. It represents an action to be invoked for the incoming
request. It has name, class and method attributes. If you don't specify name attribute by default
execute() method will be invoked for the specified action class.

result element is the sub element of action. It represents an view (result) that will be invoked. Struts
framework checks the string returned by the action class, if it returns success, result page for the action
is invoked whose name is success or has no name. It has name and type attributes. Both are optional. If
you don't specify the result name, by default success is assumed as the result name. If you don't specify
the type attribute, by default dispatcher is considered as the default result type. We will learn about
result types later.

struts.xml

1. <?xml version="1.0" encoding="UTF-8" ?>


2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
3. Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
4. <struts>
5. <package name="default" extends="struts-default">
6.
7. <action name="product" class="com.javatpoint.Product">
8. <result name="success">welcome.jsp</result>
9. </action>
10.
11. </package>
12. </struts>
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
3. Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
4. <struts>
5. <package name="default" extends="struts-default">
6.
7. <action name="product" class="com.javatpoint.Product">
8. <result name="success">welcome.jsp</result>
9. </action>
10.
11. </package>
12. </struts>

6) Create view components (welcome.jsp)

It is the view component the displays information of the action. Here, we are using struts tags to get the
information.

The s:property tag returns the value for the given name, stored in the action object.

welcome.jsp

1. <%@ taglib uri="/struts-tags" prefix="s" %>


2.
3. Product Id:<s:property value="id"/><br/>
4. Product Name:<s:property value="name"/><br/>
5. Product Price:<s:property value="price"/><br/>
1. <%@ taglib uri="/struts-tags" prefix="s" %>
2.
3. Product Id:<s:property value="id"/><br/>
4. Product Name:<s:property value="name"/><br/>
5. Product Price:<s:property value="price"/><br/>

7) Load the jar files

To run this application, you need to have the struts 2 jar files. Here, we are providing all the necessary
jar files for struts 2. Download it and put these jar files in the lib folder of your project.

8) start server and deploy the project

Finally, start the server and deploy the project and access it.