SlideShare a Scribd company logo
FULL STACK DEVELOPMENT II
Prof. UMA BHARTI , Assistant Professor
IT & Computer Science
Data Science Overview
UNIT -4
Java Struts
What you learn in this unit ?
1. Introduction
2. Features
3. Example
4. Interceptors: custom, params,execAndWait, prepare, modelDriven, exception
, fileUpload ,value stack, Action Context, Action Invocation,
5. Components
6. Struts architecture
7. struts configuration
8. Struts Validation
1. Introduction
 Struts is an open-source web application framework developed by Apache Software
Foundation, it is used to create a web application based on servlet and JSP.
 It depends on the MVC (Model View Controller) framework.
 Struts are thoroughly useful in building J2EE (Java 2 Platform, Enterprise Edition) applications
because struts take 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 persistent look and feel easier to achieve and customize across the entire application.
 A composite view is made up by using other reusable sub-views such that a small change that
happens in a sub-view is automatically updated in every composite view.
 Struts consist of a set of custom tag libraries. Struts also support utility classes.
1. Introduction
The main purpose of the struts framework is to
provision separation of concerns between the
business logic and the presentation logic (view),
making it easier to manage and develop large-
scale web applications.
Features of Struts
Struts have the following features:
•Struts encourages good design practices and modeling because the
framework is designed with “time-proven” design patterns.
•Struts is almost simple, so easy to learn and use.
•It supports many convenient features such as input validation and
internationalization.
•It takes much of the complexity out as instead of building your own MVC
framework, you can use struts.
Features of Struts
Struts have the following features:
•Struts is very well integrated with J2EE.
•Struts has large user community.
•It is flexible and extensible; it is easy for the existing web applications to adapt
the struts framework.
•Struts provide good tag libraries.
•It allows capturing input form data into JavaBean objects called Action forms.
•It also hands over standard error handling both programmatically and
declaratively.
STRUTS Example
Prerequisites:
 Before creating your Struts2 project it is important to make sure that you have the Apache Tomcat server
installed and configured with the Eclipse IDE.
• Create a dynamic web project and set it up with the struts2 framework. Refer to “
Create and Setup Struts2 Dynamic Web Application in Eclipse” for the same.
Now, if the above conditions are fulfilled and your web application is configured with the struts2 then follow
the steps given below.
STRUTS Example
Step by Step Implementation
1] web.xml file
Create a web.xml file under the webapp/WEB-INF folder and copy the following code in web.xml. This file is
created by default if you have checked the Generate web.xml deployment descriptor option at the time of
creating a dynamic web project. Now copy the following code in the web.xml file.
STRUTS Example
web.xml
file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<display-name>Struts2 Hello World Example</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
STRUTS Example
2] Result Pages
We need JSP pages to display the final
result, this page will be called by the
Struts 2 framework where a predefined
action will be called and this mapping is
defined in the struts.xml file. We are
using Struts 2 UI tags to create our JSP
pages. To create a JSP file, right-click on
the webapp folder in the project
explorer and select New >JSP File. Refer
to the below image
STRUTS Example
login.jsp file
A JSP login page to
display the username
and password input
fields and submit
button. Copy the
following code into
the login.jsp file.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body bgColor="lightBlue">
<s:form action="Welcome">
<s:textfield name="userName" label="User Name" />
<s:password name="password" label="Password" />
<s:submit value="Say Hello" />
</s:form>
</body>
</html>
STRUTS Example
welcome.jsp file
Create a welcome.jsp file
under the webapp folder.
This file displays a
welcome message to the
user. Copy the following
code into the file.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome Page</title>
</head>
<body>
<h2> Hello World Example in Struts 2</h2>
<h3> Hello <s:property value="userName"/> !!! </h3>
</body>
</html>
STRUTS Example
3] Action class: WelcomeAction.java
A Struts2 Action class is used to declare all
the business logic inside. Our application has
only one Action class whereas
our WelcomeAction class extends
ActionSupport class. It is good to extend
ActionSupport class as it provides a default
implementation for most common tasks.
Create a WelcomeAction.java file and Copy
the following code into the file.
package com.GeeksforGeeks.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class WelcomeAction extends ActionSupport {
// Java bean to hold the form parameters
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
// All struts logic goes here
public String execute() {
return SUCCESS;
}
}
STRUTS Example
4] Struts configuration file: struts.xml
We need a mapping between URL to
action mapping. The struts.xml maps
the WelcomeAction class, and
the welcome.jsp together. The
mapping tells the Struts 2 framework
which class will respond to the user’s
action (the URL), which method of
that class will be executed, and what
view to render based on the String
result that method returns. So we will
now create a struts.xml file under
the src/main/java folder. Copy the
following code into struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="WelcomeAction" />
<package name="default" extends="struts-default" namespace="/">
<action name="Welcome"
class="com.GeeksforGeeks.struts2.WelcomeAction" >
<result name="success">welcome.jsp</result>
<result name="input">login.jsp</result>
</action>
</package>
</struts>
STRUTS Example
Your project structure should now look like this:
STRUTS Example
5] Run your application
To run your application in
Eclipse: Right-click on
project -> run as -> run on
server
STRUTS Example
After you enter the
username and
password you’ll get the
following screen:
STRUTS Example
Output:
When we run our application,
you will see a web page opened
on your Eclipse IDE like this:
INTERCEPATOR
Interceptor is an object that is invoked at the
preprocessing and postprocessing of a request. In Struts
2, interceptor is used to perform operations such as
validation, exception handling, internationalization,
displaying intermediate result etc.
A
ADVANTGE OF INTERCEPATOR
8) clearSession It unbinds the HttpSession object.
9) debugging It provides support of debugging.
10) externalRef
11) execAndWait It sends an intermediate waiting page for the result.
12) exception It maps exception to a result.
13) fileUpload It provides support to file upload in struts 2.
14) i18n It provides support to internationalization and localization.
A
ADVANTGE OF INTERCEPATOR
15) jsonValidation It provides support to asynchronous validation.
16) logger It outputs the action name.
17) store It stores and retrieves action messages, action errors or field errors for action that
implements ValidationAware interface.
18) modelDriven It makes other model object as the default object of valuestack.
19) scopedModelDriven It is similar to ModelDriven but works for action that implements ScopedModelDriven.
20) params It populates the action properties with the request parameters.
21) actionMappingParams
22) prepare It performs preparation logic if action implements Preparable interface.
23) profiling It supports action profiling.
24) roles It supports role-based action.
25) scope It is used to store the action state in the session or application scope.
A
ADVANTGE OF INTERCEPATOR
26) servletConfig It provides access to maps representing HttpServletRequest and
HttpServletResponse.
27) sessionAutowiring
28) staticParams It maps static properties to action properties.
29) timer It outputs the time needed to execute an action.
30) token It prevents duplication submission of request.
31) tokenSession It prevents duplication submission of request.
32) validation It provides support to input validation.
33) workflow It calls the validate method of action class if action class implements Validateable
interface.
34) annotationWorkflow
35) multiselect
Custom Interceptor
In struts 2, we can create the custom interceptor by implementing the Interceptor
interface in a class and overriding its three life cycle method.
For creating the custom interceptor, Interceptor interface must be implemented. It has
three methods:
1. public void init() It is invoked only once and used to initialize the interceptor.
2. public String intercept(ActionInvocation ai) It is invoked at each request, it is used to
define the request processing logic. If it returns string, result page will be invoked, if
it returns invoke() method of ActionInvocation interface, next interceptor or action
will be invoked.
3. public void destroy() It is invoked only once and used to destroy the interceptor.
Example to create Custom Interceptor
In this example, we are going to create custom interceptor that converts
request processing data into uppercase letter.
You need to follow 2 steps to create custom interceptor
1. Create an interceptor (must implement Interceptor interface)
2. Define the entry of interceptor in the struts.xml file
Loaded: 4.04%
Â
Loaded: 4.04%
Â
1) Create an interceptor (must implement Interceptor interface)
By this interceptor, we are converting the name property of action
class into uppercase letter.
The getStack() method of ActionInvocation returns the reference of
ValueStack.
We are getting the value set in the name property
by findString method of ValueStack.
The set method of ValueStack sets the name property by the
specified value. In such case, we are converting the value of name
property into uppercase letter and storing it into the valuestack.
The invoke method of ActionInvocation returns the information of
next resource.
MyInterceptor.java
1.package com;
2.import com.opensymphony.xwork2.ActionInvocation;
3.import com.opensymphony.xwork2.interceptor.Interceptor;
4.import com.opensymphony.xwork2.util.ValueStack;
5.
6.public class MyInterceptor implements Interceptor{
7.
8. public void init() {}
9. public String intercept(ActionInvocation ai) throws Except
ion {
10. ValueStack stack=ai.getStack();
11. String s=stack.findString("name");
12.
13. stack.set("name",s.toUpperCase());
14. return ai.invoke();
15. }
16. public void destroy() {}
17.}
2) Define the entry of interceptor in the struts.xml file
To define the interceptor, we need to declare an interceptor first. The interceptors element of
package is used to specify interceptors. The interceptor element of interceptors is used to
define the custom interceptor. Here, we are defining the custom interceptor by upper.
The interceptor-ref subelement of action specifies the interceptor that
will be applied for this action. Here, we are specifying the defaultstack
interceptors and upper interceptor.
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="abc" extends="struts-default">
<interceptors>
<interceptor name="upper" class="com.MyInterceptor"></interceptor>
</interceptors>
<action name="login" class="com.Login">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="upper"></interceptor-ref>
<result>welcome.jsp</result>
</action>
</package>
</struts>
Other Required Resources
The other required resources are
index.jsp
Login.java
welcome.jsp
1) Create form to get input (index.jsp)
index.jsp
This jsp page creates a form using struts UI tags. It receives name from the user.
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="login">
<s:textfield name="name" label="Name"></s:textfield>
<s:submit value="login"></s:submit>
</s:form>
2) Create the action class
It is the simple action class
containing name property with
its setter and getter methods.
Login.java
package com;
public class Login {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
return "success";
}
}
3) Create view component
This jsp page displays the name input by the user.
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Welcome, <s:property value="name"/>
Params Interceptor
The params interceptor also known as parameters interceptor is used to set
all parameters on the valuestack.
It is found in the default stack bydefault. So you don't need to specify it
explicitely.
Internal working of params interceptor
It gets all parameters by calling the getParameters() method of
ActionContext and sets it on the valuestack by calling the setValue()
method of ValueStack.
Parameters of params interceptor
There are 4 parameters defined for params interceptor.
Parameter Description
ordered It is true bydefault but can be used to
top-down the property setter
behaviour.
paramNameMaxLength specifies the maximum length for the
parameter. The default length is 100
characters bydefault. The parameters
length more that 100 will be ignored.
excludeParams specifies the unallowed parameter
names. You can specify multiple
names separated with comma.
acceptParamNames specifies the accepted parameter
names.
Example of params interceptor
<action name="login" class="com.javatpoint.Login">
<interceptor-ref name="params"/>
<result name="success">login-success.jsp</result>
</action>
Struts 2 defaultStack interceptors
The params
interceptor is found
in the default stack.
You don't need to
specify interceptors
found in the default-
stack. The
defaultStack
interceptors are as
follows:
<interceptor-stack name="defaultStack">
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="chain"/>
<interceptor-ref name="debugging"/>
<interceptor-ref name="profiling"/>
<interceptor-ref name="scopedModelDriven"/>
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="staticParams"/>
<interceptor-ref name="actionMappingParams"/>
<interceptor-ref name="params">
<param name="excludeParams">dojo..*,^struts..*</param>
</interceptor-ref>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
</interceptor-stack>
execAndWait interceptor
The execAndWait interceptor also known as execute and wait interceptor is used to display the intermediate
result.
It is recommended to use for long running action.
It is not found in the default stack bydefault. So you need to specify it explicitely.
If you don't specify "wait" result, struts framework displays an intermediate result until your request is
completed. For the custom intermediate result, you need to define "wait" result in struts.xml file. In your page,
you can display processing image etc. So, it is better to specify the custom result.
Parameters of execAndWait interceptor
There are 3 parameters defined for execAndWait interceptor
Parameter Description
delay specifies the initial delay time.
Bydefault, no initial delay is set.
delaySleepInterval used only with delay. It specifies the
time interval in milliseconds to check
that background process is
completed. It is set to 100
milliseconds bydefault.
threadPriority specifies the priority of the thread.
The default is
Thread.NORM_PRIORITY.
Example of execAndWait interceptor without wait result
<action name="login" class="com.javatpoint.Login">
<interceptor-ref name="params"/>
<interceptor-ref name="execAndWait"/>
<result name="success">login-success.jsp</result>
</action>
Example of execAndWait interceptor with wait result
<action name="login" class="com.javatpoint.Login">
<interceptor-ref name="params"/>
<interceptor-ref name="execAndWait"/>
<result name="success">login-success.jsp</result>
<result name="wait">myintermediatepage.jsp</result>
</action>
myintermediatepage.jsp
Let's write the code for intermediate result. The s:url tag will forward the request to specified url.
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>wait</title>
<meta http-equiv="refresh" content="0.5;url='<s:url includeParams="all" />'">
</head>
<body>
<p>your request is processing...</p>
<img src="processing.gif"/>
</body>
</html>
Output
It will be refreshed at 0.5
seconds.
Output
It will be refreshed at 0.5
seconds.
Prepare Interceptor
The prepare interceptor calls prepre()
method on the action if it
implements Preparable interface. It calls
prepare() method before the execute()
method.
To use the prepare interceptor, you need to
implement Preparable interface in your
action class and override its method
prepare.
It is found in the default stack bydefault. So
you don't need to specify it explicitely.
Parameters of prepare interceptor
There is only 1 parameter defined for prepare
interceptor.
Parameter Description
alwaysInvokePrepare It is set to true bydefault.
Example of prepare interceptor
<action name="login" class="com.javatpoint.LoginAction">
<interceptor-ref name="params"/>
<interceptor-ref name="prepare"/>
<result name="success">login-success.jsp</result>
</action>
Action class
package com.javatpoint;
import com.opensymphony.xwork2.Preparable;
public class LoginAction implements Preparable{
private String name,password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void prepare() throws Exception {
System.out.println("preparation logic");
}
public String execute(){
System.out.println("actual logic");
return "success";
}
}
Output
ModelDriven Interceptor
The modelDriven interceptor makes other model object as the
default object of valuestack.
Bydefault, action object is the default object of valuestack.
To use the modelDriven interceptor, you need to
implement ModelDriven interface in your action class and
override its method getModel().
It is found in the default stack bydefault. So you don't need to
specify it explicitely.
Example of modelDriven interceptor
<action name="login" class="com.javatpoint.LoginAction">
<interceptor-ref name="params"/>
<interceptor-ref name="modelDriven"/>
<result name="success">login-success.jsp</result>
</action>
Full example of modelDriven interceptor
File: index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="login">
<s:textfield name="name" label="Name"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>
File: struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//
EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="abc" extends="struts-default" >
<action name="login" class="com.javatpoint.Login">
<result name="success" >/login-success.jsp</result>
<result name="error">/login-error.jsp</result>
</action>
</package>
</struts>
File: Login.java package com.javatpoint;
import com.opensymphony.xwork2.ModelDriven;
public class Login implements ModelDriven<User>{
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public User getModel(){
user=new User();
return user;
}
public String execute(){
if(user.getPassword().equals("admin")){
return "success";
}
else{
return "error";
}
}
}
File: User.java
package com.javatpoint;
public class User {
private String name,password;
//getters and setters
}
File: login-success.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Welcome, <s:property value="name"/>
File: login-error.jsp
Sorry, username or password error!
<jsp:include page="index.jsp"></jsp:include>
Output
Exception Handling
• In our web application, there might occur exception at any point.
To overcome this problem, struts 2 provides a mechanism of global exception handling where we
can display a global result to the user.
Struts 2 automatically log the uncaught exceptions and redirects the user to the error handler page.
Understanding the internal working of exception
interceptor
If there occurs exception, it is wrapped in ExceptionHolder and pushed in
the valuestack so that we can easily access exception object from the
result.
There are 3 parameters defined for exception interceptor. All are optional.
Parameter Description
logEnabled specifies log should be enabled or
not. You can pass true or false.
logLevel specifies the log level. It may be
trace, debug, info, warn, error, fatal.
Default log level is debug.
logCategory specifies the log category eg.
com.mycompany.app. The default is
com.opensymphony.xwork2.intercept
or.ExceptionMappingInterceptor..
Example of exception handling in struts 2
struts.xml <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="aa" extends="struts-default">
<global-results>
<result name="myresult">globalresult.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="myresult" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
<action name="login" class="com.Login">
<result>welcome.jsp</result>
<result name="error">error.jsp</result>
</action>
</package>
</struts>
The global-results sub-element of package specifies the global-result for this
package.
The result sub-element of global-result specifies the result page that will be
rendered to the user as a view.
The global-exception-mappings sub-element of package specifies the exception
mapping for all the actions of this package.
The exception-mapping sub-element of global-exception-mapping maps the given
result for the given exception type. In this example, we are using the Exception
which the parent of many exception classes such as IOException,
ArithmeticException etc. It means if any exception occurs, specified result will be
invoked.
globalresult.jsp
<p>Exception Name: <s:property value="exception" /> </p>
<p>Exception Details: <s:property value="exceptionStack" /></p>
Full example of exception handling
The other required resources to complete this example are as follows:
• Input page (index.jsp)
• Action class (Login.java)
• View components (globalresult.jsp, welcome.jsp and error.jsp)
1) Create index.jsp for
input
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="login">
<s:textfield name="name" label="Name"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>
2) Create the action class
Login.java
package com;
public class Login {
private String name,password;
//getters and setters
public String execute(){
if(password.equals("struts")){
int a=12/0;//If you comment this, exception will not occur
return "success";
}else
return "error";
}
3) Create view components
There are three view components globalresult.jsp that displays the exception
message, welcome.jsp that displays the welcome message with the username
and error.jsp that displays the error message.
globalresult.jsp
1.<%@ taglib uri="/struts-tags" prefix="s" %>
2.
3.Sorry an exception occured!
4.<p>Exception Name: <s:property value="exception" /> </p>
5.<p>Exception Details: <s:property value="exceptionStack" /></p>
6.<form>
7.<input type="button" value="back" onclick="history.back()">
8.</form>
welcome.jsp
1.<%@ taglib uri="/struts-tags" prefix="s" %>
2.Welcome, <s:property value="name"/>
error.jsp
Sorry username or password error!
<jsp:include page="index.jsp"></jsp:include>
File Upload
The fileUpload interceptor automatically works for all the requests that includes files.
We can use this interceptor to control the working of file upload in struts2 such as defining allowed types,
maximum file size etc.
There are 2 parameters defined for fileupload interceptor.
Parameter Description
maximumSize specifies maximum size of the
file to be uploaded.
allowedTypes specifies allowed types. It may
be image/png, image/jpg etc
It automatically adds 2 parameters in the request
:
String fileName represents the filename of the file.
String contentType specifies the content type of the file.
1) Create UserImage.jsp
index.jsp <%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>
<body>
<h2>
Struts2 File Upload & Save Example without Database
</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart
/form-data">
<s:file name="userImage" label="Image" />
<s:submit value="Upload" align="center" />
</s:form>
</body>
</html>
2) Create SuccessUserImage.jsp
SuccessUserImage.jsp
<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s"
uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>
</head>
<body>
<h2>
Struts2 File Upload Example
</h2>
User Image: <s:property value="userImage" /><br/>
Content Type:<s:property value="userImageContentType" /><br/>
File Name: <s:property value="userImageFileName" /><br/>
Uploaded Image: <img src="userimages/
<s:property value="userImageFileName"/>"
width="100" height="100" />
3) Create the action class
RegisterAction.java
package com.javatpoint;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private File userImage;
private String userImageContentType;
private String userImageFileName;
public String execute() {
try {
String filePath = ServletActionContext.getServletContext().getRealPath("/").concat("userimages");
System.out.println("Image Location:" + filePath);//see the server console for actual location
File fileToCreate = new File(filePath,userImageFileName);
FileUtils.copyFile(userImage, fileToCreate);//copying source file to new file
return SUCCESS;
}
public File getUserImage() {
return userImage;
}
public void setUserImage(File userImage) {
this.userImage = userImage;
}
public String getUserImageContentType() {
return userImageContentType;
}
public void setUserImageContentType(String userImageContentType) {
this.userImageContentType = userImageContentType;
}
public String getUserImageFileName() {
return userImageFileName;
}
public void setUserImageFileName(String userImageFileName) {
this.userImageFileName = userImageFileName;
}
4) Create struts.xml
struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="fileUploadPackage" extends="struts-default">
<action name="userImage" class="com.javatpoint.FileUploadAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">SuccessUserImage.jsp</result>
<result name="input">UserImage.jsp</result>
</action>
</package>
Output
ActionContext
The ActionContext is a container of objects in which
action is executed. The values stored in the
ActionContext are unique per thread (i.e. ThreadLocal).
So we don't need to make our action thread safe.
We can get the reference of ActionContext by calling the
getContext() method of ActionContext class. It is a static
factory method.
For example:
ActionContext context = ActionContext.getContex
t();
A valueStack is simply a stack that contains application specific
objects such as action objects and other model object.
At the execution time, action is placed on the top of the stack.
We can put objects in the valuestack, query it and delete it.
ActionInvocation
ActionInvocation represen
ts the execution state of
an action. It holds the
action and interceptors
objects.
ActionInvocation Interface
The struts framework
provides ActionInvocation
interface to deal with
ActionInvocation. It
provides many methods,
some of them can be used
to get the instance of
ValueStack, ActionProxy,
ActionContext, Result etc.
Methods of
ActionInvocation
Interface
No. Method Description
1) public ActionContext
getInvocationContext()
returns the ActionContext
object associated with the
ActionInvocation.
2) public ActionProxy
getProxy()
returns the ActionProxy
instance holding this
ActionInvocation.
3) public ValueStack getStack() returns the instance of
ValueStack.
4) public Action getAction() returns the instance of
Action associated with this
ActionInvocation.
5) public void invoke() invokes the next resource in
processing this
ActionInvocation.
6) public Result getResult() returns the instance of
Result.
Struts Architecture
The architecture and flow of struts 2 application,
is combined with many components such as
Controller, ActionProxy, ActionMapper,
Configuration Manager, ActionInvocation,
Inerceptor, Action, Result etc.
Here, we are going to understand the struts flow
by 2 ways:
struts 2 basic flow
struts 2 standard architecture and flow provided
by apache struts
Struts 2 basic flow
User sends a request for the action
Controller invokes the ActionInvocation
ActionInvocation invokes each interceptors and action
A result is generated
The result is sent back to the ActionInvocation
A HttpServletResponse is generated
Response is sent to the user
Struts standard flow (Struts architecture)
User sends a request for the action
Container maps the request in the web.xml file and gets the class
name of controller.
Container invokes the controller (StrutsPrepareAndExecuteFilter
or FilterDispatcher). Since struts2.1, it is
StrutsPrepareAndExecuteFilter. Before 2.1 it was FilterDispatcher.
Controller gets the information for the action from the
ActionMapper
Controller invokes the ActionProxy
ActionProxy gets the information of action and interceptor stack
from the configuration manager which gets the information from
the struts.xml file.
ActionProxy forwards the request to the ActionInvocation
ActionInvocation invokes each interceptors and action
A result is generated
The result is sent back to the ActionInvocation
A HttpServletResponse is generated
Configuration Files
From a Struts developer point of view,
the one required configuration file used
by the framework is web.xml.
From here, you have full control over
how Struts configures both itself and
your application. By default, Struts will
load a set of internal configuration files
to configure itself, then another set to
configure your application, however it
is possible to build an entire Struts
application without writing a single
configuration file other than web.xml.
The table lists the files that you can use
to configure the framework for your
application. Some configuration files
can be reloaded dynamically. Dynamic
reloading makes interactive
File Optional Location (relative to webapp) Purpose
web.xml no /WEB-INF/
Web deployment descriptor to
include all necessary
framework components
struts.xml yes /WEB-INF/classes/
Main configuration, contains
result/view types, action
mappings, interceptors, and so
forth
default.properties yes /WEB-INF/classes/ Framework properties
struts-default.xml yes /WEB-INF/lib/struts2-core.jar Default configuration provided
by Struts
struts-default.vm yes /WEB-INF/classes/ Default macros referenced by
velocity.properties
struts-plugin.xml yes At the root of a plugin JAR
Optional configuration files for
Plugins in the same format as
struts.xml.
struts-deferred.xml yes At the root of a plugin JAR
Optional configuration files for
Plugins, most useful for
defining extension points
velocity.properties yes /WEB-INF/classes/ Override the
default Velocity configuration
Struts 2 Validation
To avoid the wrong values, we need to perform validation on forms where user
submits some values. For example, if user writes his/her email id as abc, we need to
give error message to the user that the given email id is not correct. So that we can
have only valuable informations.
There are three ways to perform validation in struts 2.
1) By Custom Validation Here, we must implement the Validateable interface (or
extend ActionSupport class) and provide the implementation of validate method.
2) By Input Validation (built-in validators) Struts 2 provides a lot of predefined that
can be used in struts 2 application to perform validation.

More Related Content

PPTX
Struts Interceptors
PPT
strut2
PPT
Struts2.x
PPTX
Skillwise Struts.x
PPT
Strut2-Spring-Hibernate
PPTX
Struts Interceptors
strut2
Struts2.x
Skillwise Struts.x
Strut2-Spring-Hibernate

Similar to struts unit best pdf for struts java.pptx (20)

PPTX
Struts 1
PPTX
PDF
Struts 2 In Action 1st Edition Don Brown Chad Michael Davis Scott Stanlick
PDF
Java Web Programming [7/9] : Struts2 Basics
PPT
Struts Ppt 1
PDF
Introduction to Struts 1.3
PDF
Struts An Open-source Architecture for Web Applications
PPTX
Session 41 - Struts 2 Introduction
PPT
Apachecon 2002 Struts
PPT
Struts2.0basic
PDF
Struts2 tutorial
PDF
Struts2 tutorial
PPT
Struts2
PPSX
Struts 2 - Introduction
PPT
Struts2-Spring=Hibernate
PDF
Step By Step Guide For Buidling Simple Struts App
PPT
Struts 2-overview2
DOCX
Struts notes
PDF
Web Development with Apache Struts 2
PDF
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Struts 1
Struts 2 In Action 1st Edition Don Brown Chad Michael Davis Scott Stanlick
Java Web Programming [7/9] : Struts2 Basics
Struts Ppt 1
Introduction to Struts 1.3
Struts An Open-source Architecture for Web Applications
Session 41 - Struts 2 Introduction
Apachecon 2002 Struts
Struts2.0basic
Struts2 tutorial
Struts2 tutorial
Struts2
Struts 2 - Introduction
Struts2-Spring=Hibernate
Step By Step Guide For Buidling Simple Struts App
Struts 2-overview2
Struts notes
Web Development with Apache Struts 2
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Ad

Recently uploaded (20)

PPTX
udi-benefits-ggggggggfor-healthcare.pptx
PPTX
KVL KCL ppt electrical electronics eee tiet
PPTX
making presentation that do no stick.pptx
PPTX
Syllabus Computer Six class curriculum s
PPTX
sdn_based_controller_for_mobile_network_traffic_management1.pptx
PPTX
figurative-languagepowerpoint-150309132252-conversion-gate01.pptx
PPTX
DEATH AUDIT MAY 2025.pptxurjrjejektjtjyjjy
PPT
chapter_1_a.ppthduushshwhwbshshshsbbsbsbsbsh
PPTX
title _yeOPC_Poisoning_Presentation.pptx
PPTX
"Fundamentals of Digital Image Processing: A Visual Approach"
PPTX
executive branch_no record.pptxsvvsgsggs
PPTX
Sem-8 project ppt fortvfvmat uyyjhuj.pptx
PDF
Core Components of IoT, The elements need for IOT
PPTX
material for studying about lift elevators escalation
PPTX
Lecture-3-Computer-programming for BS InfoTech
PDF
Chapter -24-By Dr Sajid Ali Ansari 2021.pdf
PPTX
Embeded System for Artificial intelligence 2.pptx
PPTX
02fdgfhfhfhghghhhhhhhhhhhhhhhhhhhhh.pptx
PPTX
PROGRAMMING-QUARTER-2-PYTHON.pptxnsnsndn
PDF
Smarter Security: How Door Access Control Works with Alarms & CCTV
udi-benefits-ggggggggfor-healthcare.pptx
KVL KCL ppt electrical electronics eee tiet
making presentation that do no stick.pptx
Syllabus Computer Six class curriculum s
sdn_based_controller_for_mobile_network_traffic_management1.pptx
figurative-languagepowerpoint-150309132252-conversion-gate01.pptx
DEATH AUDIT MAY 2025.pptxurjrjejektjtjyjjy
chapter_1_a.ppthduushshwhwbshshshsbbsbsbsbsh
title _yeOPC_Poisoning_Presentation.pptx
"Fundamentals of Digital Image Processing: A Visual Approach"
executive branch_no record.pptxsvvsgsggs
Sem-8 project ppt fortvfvmat uyyjhuj.pptx
Core Components of IoT, The elements need for IOT
material for studying about lift elevators escalation
Lecture-3-Computer-programming for BS InfoTech
Chapter -24-By Dr Sajid Ali Ansari 2021.pdf
Embeded System for Artificial intelligence 2.pptx
02fdgfhfhfhghghhhhhhhhhhhhhhhhhhhhh.pptx
PROGRAMMING-QUARTER-2-PYTHON.pptxnsnsndn
Smarter Security: How Door Access Control Works with Alarms & CCTV
Ad

struts unit best pdf for struts java.pptx

  • 1. FULL STACK DEVELOPMENT II Prof. UMA BHARTI , Assistant Professor IT & Computer Science
  • 2. Data Science Overview UNIT -4 Java Struts
  • 3. What you learn in this unit ? 1. Introduction 2. Features 3. Example 4. Interceptors: custom, params,execAndWait, prepare, modelDriven, exception , fileUpload ,value stack, Action Context, Action Invocation, 5. Components 6. Struts architecture 7. struts configuration 8. Struts Validation
  • 4. 1. Introduction  Struts is an open-source web application framework developed by Apache Software Foundation, it is used to create a web application based on servlet and JSP.  It depends on the MVC (Model View Controller) framework.  Struts are thoroughly useful in building J2EE (Java 2 Platform, Enterprise Edition) applications because struts take 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 persistent look and feel easier to achieve and customize across the entire application.  A composite view is made up by using other reusable sub-views such that a small change that happens in a sub-view is automatically updated in every composite view.  Struts consist of a set of custom tag libraries. Struts also support utility classes.
  • 5. 1. Introduction The main purpose of the struts framework is to provision separation of concerns between the business logic and the presentation logic (view), making it easier to manage and develop large- scale web applications.
  • 6. Features of Struts Struts have the following features: •Struts encourages good design practices and modeling because the framework is designed with “time-proven” design patterns. •Struts is almost simple, so easy to learn and use. •It supports many convenient features such as input validation and internationalization. •It takes much of the complexity out as instead of building your own MVC framework, you can use struts.
  • 7. Features of Struts Struts have the following features: •Struts is very well integrated with J2EE. •Struts has large user community. •It is flexible and extensible; it is easy for the existing web applications to adapt the struts framework. •Struts provide good tag libraries. •It allows capturing input form data into JavaBean objects called Action forms. •It also hands over standard error handling both programmatically and declaratively.
  • 8. STRUTS Example Prerequisites:  Before creating your Struts2 project it is important to make sure that you have the Apache Tomcat server installed and configured with the Eclipse IDE. • Create a dynamic web project and set it up with the struts2 framework. Refer to “ Create and Setup Struts2 Dynamic Web Application in Eclipse” for the same. Now, if the above conditions are fulfilled and your web application is configured with the struts2 then follow the steps given below.
  • 9. STRUTS Example Step by Step Implementation 1] web.xml file Create a web.xml file under the webapp/WEB-INF folder and copy the following code in web.xml. This file is created by default if you have checked the Generate web.xml deployment descriptor option at the time of creating a dynamic web project. Now copy the following code in the web.xml file.
  • 10. STRUTS Example web.xml file <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0"> <display-name>Struts2 Hello World Example</display-name> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
  • 11. STRUTS Example 2] Result Pages We need JSP pages to display the final result, this page will be called by the Struts 2 framework where a predefined action will be called and this mapping is defined in the struts.xml file. We are using Struts 2 UI tags to create our JSP pages. To create a JSP file, right-click on the webapp folder in the project explorer and select New >JSP File. Refer to the below image
  • 12. STRUTS Example login.jsp file A JSP login page to display the username and password input fields and submit button. Copy the following code into the login.jsp file. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Login Page</title> </head> <body bgColor="lightBlue"> <s:form action="Welcome"> <s:textfield name="userName" label="User Name" /> <s:password name="password" label="Password" /> <s:submit value="Say Hello" /> </s:form> </body> </html>
  • 13. STRUTS Example welcome.jsp file Create a welcome.jsp file under the webapp folder. This file displays a welcome message to the user. Copy the following code into the file. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Welcome Page</title> </head> <body> <h2> Hello World Example in Struts 2</h2> <h3> Hello <s:property value="userName"/> !!! </h3> </body> </html>
  • 14. STRUTS Example 3] Action class: WelcomeAction.java A Struts2 Action class is used to declare all the business logic inside. Our application has only one Action class whereas our WelcomeAction class extends ActionSupport class. It is good to extend ActionSupport class as it provides a default implementation for most common tasks. Create a WelcomeAction.java file and Copy the following code into the file. package com.GeeksforGeeks.struts2; import com.opensymphony.xwork2.ActionSupport; public class WelcomeAction extends ActionSupport { // Java bean to hold the form parameters private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } // All struts logic goes here public String execute() { return SUCCESS; } }
  • 15. STRUTS Example 4] Struts configuration file: struts.xml We need a mapping between URL to action mapping. The struts.xml maps the WelcomeAction class, and the welcome.jsp together. The mapping tells the Struts 2 framework which class will respond to the user’s action (the URL), which method of that class will be executed, and what view to render based on the String result that method returns. So we will now create a struts.xml file under the src/main/java folder. Copy the following code into struts.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="WelcomeAction" /> <package name="default" extends="struts-default" namespace="/"> <action name="Welcome" class="com.GeeksforGeeks.struts2.WelcomeAction" > <result name="success">welcome.jsp</result> <result name="input">login.jsp</result> </action> </package> </struts>
  • 16. STRUTS Example Your project structure should now look like this:
  • 17. STRUTS Example 5] Run your application To run your application in Eclipse: Right-click on project -> run as -> run on server
  • 18. STRUTS Example After you enter the username and password you’ll get the following screen:
  • 19. STRUTS Example Output: When we run our application, you will see a web page opened on your Eclipse IDE like this:
  • 20. INTERCEPATOR Interceptor is an object that is invoked at the preprocessing and postprocessing of a request. In Struts 2, interceptor is used to perform operations such as validation, exception handling, internationalization, displaying intermediate result etc.
  • 21. A ADVANTGE OF INTERCEPATOR 8) clearSession It unbinds the HttpSession object. 9) debugging It provides support of debugging. 10) externalRef 11) execAndWait It sends an intermediate waiting page for the result. 12) exception It maps exception to a result. 13) fileUpload It provides support to file upload in struts 2. 14) i18n It provides support to internationalization and localization.
  • 22. A ADVANTGE OF INTERCEPATOR 15) jsonValidation It provides support to asynchronous validation. 16) logger It outputs the action name. 17) store It stores and retrieves action messages, action errors or field errors for action that implements ValidationAware interface. 18) modelDriven It makes other model object as the default object of valuestack. 19) scopedModelDriven It is similar to ModelDriven but works for action that implements ScopedModelDriven. 20) params It populates the action properties with the request parameters. 21) actionMappingParams 22) prepare It performs preparation logic if action implements Preparable interface. 23) profiling It supports action profiling. 24) roles It supports role-based action. 25) scope It is used to store the action state in the session or application scope.
  • 23. A ADVANTGE OF INTERCEPATOR 26) servletConfig It provides access to maps representing HttpServletRequest and HttpServletResponse. 27) sessionAutowiring 28) staticParams It maps static properties to action properties. 29) timer It outputs the time needed to execute an action. 30) token It prevents duplication submission of request. 31) tokenSession It prevents duplication submission of request. 32) validation It provides support to input validation. 33) workflow It calls the validate method of action class if action class implements Validateable interface. 34) annotationWorkflow 35) multiselect
  • 24. Custom Interceptor In struts 2, we can create the custom interceptor by implementing the Interceptor interface in a class and overriding its three life cycle method. For creating the custom interceptor, Interceptor interface must be implemented. It has three methods: 1. public void init() It is invoked only once and used to initialize the interceptor. 2. public String intercept(ActionInvocation ai) It is invoked at each request, it is used to define the request processing logic. If it returns string, result page will be invoked, if it returns invoke() method of ActionInvocation interface, next interceptor or action will be invoked. 3. public void destroy() It is invoked only once and used to destroy the interceptor.
  • 25. Example to create Custom Interceptor In this example, we are going to create custom interceptor that converts request processing data into uppercase letter. You need to follow 2 steps to create custom interceptor 1. Create an interceptor (must implement Interceptor interface) 2. Define the entry of interceptor in the struts.xml file Loaded: 4.04% Â Loaded: 4.04% Â
  • 26. 1) Create an interceptor (must implement Interceptor interface) By this interceptor, we are converting the name property of action class into uppercase letter. The getStack() method of ActionInvocation returns the reference of ValueStack. We are getting the value set in the name property by findString method of ValueStack. The set method of ValueStack sets the name property by the specified value. In such case, we are converting the value of name property into uppercase letter and storing it into the valuestack. The invoke method of ActionInvocation returns the information of next resource.
  • 27. MyInterceptor.java 1.package com; 2.import com.opensymphony.xwork2.ActionInvocation; 3.import com.opensymphony.xwork2.interceptor.Interceptor; 4.import com.opensymphony.xwork2.util.ValueStack; 5. 6.public class MyInterceptor implements Interceptor{ 7. 8. public void init() {} 9. public String intercept(ActionInvocation ai) throws Except ion { 10. ValueStack stack=ai.getStack(); 11. String s=stack.findString("name"); 12. 13. stack.set("name",s.toUpperCase()); 14. return ai.invoke(); 15. } 16. public void destroy() {} 17.}
  • 28. 2) Define the entry of interceptor in the struts.xml file To define the interceptor, we need to declare an interceptor first. The interceptors element of package is used to specify interceptors. The interceptor element of interceptors is used to define the custom interceptor. Here, we are defining the custom interceptor by upper. The interceptor-ref subelement of action specifies the interceptor that will be applied for this action. Here, we are specifying the defaultstack interceptors and upper interceptor.
  • 29. struts.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="abc" extends="struts-default"> <interceptors> <interceptor name="upper" class="com.MyInterceptor"></interceptor> </interceptors> <action name="login" class="com.Login"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="upper"></interceptor-ref> <result>welcome.jsp</result> </action> </package> </struts>
  • 30. Other Required Resources The other required resources are index.jsp Login.java welcome.jsp
  • 31. 1) Create form to get input (index.jsp) index.jsp This jsp page creates a form using struts UI tags. It receives name from the user. <%@ taglib uri="/struts-tags" prefix="s" %> <s:form action="login"> <s:textfield name="name" label="Name"></s:textfield> <s:submit value="login"></s:submit> </s:form>
  • 32. 2) Create the action class It is the simple action class containing name property with its setter and getter methods. Login.java package com; public class Login { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String execute(){ return "success"; } }
  • 33. 3) Create view component This jsp page displays the name input by the user. welcome.jsp <%@ taglib uri="/struts-tags" prefix="s" %> Welcome, <s:property value="name"/>
  • 34. Params Interceptor The params interceptor also known as parameters interceptor is used to set all parameters on the valuestack. It is found in the default stack bydefault. So you don't need to specify it explicitely. Internal working of params interceptor It gets all parameters by calling the getParameters() method of ActionContext and sets it on the valuestack by calling the setValue() method of ValueStack. Parameters of params interceptor
  • 35. There are 4 parameters defined for params interceptor. Parameter Description ordered It is true bydefault but can be used to top-down the property setter behaviour. paramNameMaxLength specifies the maximum length for the parameter. The default length is 100 characters bydefault. The parameters length more that 100 will be ignored. excludeParams specifies the unallowed parameter names. You can specify multiple names separated with comma. acceptParamNames specifies the accepted parameter names.
  • 36. Example of params interceptor <action name="login" class="com.javatpoint.Login"> <interceptor-ref name="params"/> <result name="success">login-success.jsp</result> </action>
  • 37. Struts 2 defaultStack interceptors The params interceptor is found in the default stack. You don't need to specify interceptors found in the default- stack. The defaultStack interceptors are as follows: <interceptor-stack name="defaultStack"> <interceptor-ref name="exception"/> <interceptor-ref name="alias"/> <interceptor-ref name="servletConfig"/> <interceptor-ref name="prepare"/> <interceptor-ref name="i18n"/> <interceptor-ref name="chain"/> <interceptor-ref name="debugging"/> <interceptor-ref name="profiling"/> <interceptor-ref name="scopedModelDriven"/> <interceptor-ref name="modelDriven"/> <interceptor-ref name="fileUpload"/> <interceptor-ref name="checkbox"/> <interceptor-ref name="staticParams"/> <interceptor-ref name="actionMappingParams"/> <interceptor-ref name="params"> <param name="excludeParams">dojo..*,^struts..*</param> </interceptor-ref> <interceptor-ref name="conversionError"/> <interceptor-ref name="validation"> <param name="excludeMethods">input,back,cancel,browse</param> </interceptor-ref> <interceptor-ref name="workflow"> <param name="excludeMethods">input,back,cancel,browse</param> </interceptor-ref> </interceptor-stack>
  • 38. execAndWait interceptor The execAndWait interceptor also known as execute and wait interceptor is used to display the intermediate result. It is recommended to use for long running action. It is not found in the default stack bydefault. So you need to specify it explicitely. If you don't specify "wait" result, struts framework displays an intermediate result until your request is completed. For the custom intermediate result, you need to define "wait" result in struts.xml file. In your page, you can display processing image etc. So, it is better to specify the custom result. Parameters of execAndWait interceptor
  • 39. There are 3 parameters defined for execAndWait interceptor Parameter Description delay specifies the initial delay time. Bydefault, no initial delay is set. delaySleepInterval used only with delay. It specifies the time interval in milliseconds to check that background process is completed. It is set to 100 milliseconds bydefault. threadPriority specifies the priority of the thread. The default is Thread.NORM_PRIORITY.
  • 40. Example of execAndWait interceptor without wait result <action name="login" class="com.javatpoint.Login"> <interceptor-ref name="params"/> <interceptor-ref name="execAndWait"/> <result name="success">login-success.jsp</result> </action>
  • 41. Example of execAndWait interceptor with wait result <action name="login" class="com.javatpoint.Login"> <interceptor-ref name="params"/> <interceptor-ref name="execAndWait"/> <result name="success">login-success.jsp</result> <result name="wait">myintermediatepage.jsp</result> </action>
  • 42. myintermediatepage.jsp Let's write the code for intermediate result. The s:url tag will forward the request to specified url. <%@ taglib uri="/struts-tags" prefix="s" %> <html> <head> <title>wait</title> <meta http-equiv="refresh" content="0.5;url='<s:url includeParams="all" />'"> </head> <body> <p>your request is processing...</p> <img src="processing.gif"/> </body> </html>
  • 43. Output It will be refreshed at 0.5 seconds.
  • 44. Output It will be refreshed at 0.5 seconds.
  • 45. Prepare Interceptor The prepare interceptor calls prepre() method on the action if it implements Preparable interface. It calls prepare() method before the execute() method. To use the prepare interceptor, you need to implement Preparable interface in your action class and override its method prepare. It is found in the default stack bydefault. So you don't need to specify it explicitely. Parameters of prepare interceptor There is only 1 parameter defined for prepare interceptor. Parameter Description alwaysInvokePrepare It is set to true bydefault.
  • 46. Example of prepare interceptor <action name="login" class="com.javatpoint.LoginAction"> <interceptor-ref name="params"/> <interceptor-ref name="prepare"/> <result name="success">login-success.jsp</result> </action>
  • 47. Action class package com.javatpoint; import com.opensymphony.xwork2.Preparable; public class LoginAction implements Preparable{ private String name,password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void prepare() throws Exception { System.out.println("preparation logic"); } public String execute(){ System.out.println("actual logic"); return "success"; } }
  • 49. ModelDriven Interceptor The modelDriven interceptor makes other model object as the default object of valuestack. Bydefault, action object is the default object of valuestack. To use the modelDriven interceptor, you need to implement ModelDriven interface in your action class and override its method getModel(). It is found in the default stack bydefault. So you don't need to specify it explicitely.
  • 50. Example of modelDriven interceptor <action name="login" class="com.javatpoint.LoginAction"> <interceptor-ref name="params"/> <interceptor-ref name="modelDriven"/> <result name="success">login-success.jsp</result> </action>
  • 51. Full example of modelDriven interceptor File: index.jsp <%@ taglib uri="/struts-tags" prefix="s" %> <s:form action="login"> <s:textfield name="name" label="Name"></s:textfield> <s:password name="password" label="Password"></s:password> <s:submit value="login"></s:submit> </s:form>
  • 52. File: struts.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1// EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="abc" extends="struts-default" > <action name="login" class="com.javatpoint.Login"> <result name="success" >/login-success.jsp</result> <result name="error">/login-error.jsp</result> </action> </package> </struts>
  • 53. File: Login.java package com.javatpoint; import com.opensymphony.xwork2.ModelDriven; public class Login implements ModelDriven<User>{ private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public User getModel(){ user=new User(); return user; } public String execute(){ if(user.getPassword().equals("admin")){ return "success"; } else{ return "error"; } } }
  • 54. File: User.java package com.javatpoint; public class User { private String name,password; //getters and setters } File: login-success.jsp <%@ taglib uri="/struts-tags" prefix="s" %> Welcome, <s:property value="name"/>
  • 55. File: login-error.jsp Sorry, username or password error! <jsp:include page="index.jsp"></jsp:include>
  • 57. Exception Handling • In our web application, there might occur exception at any point. To overcome this problem, struts 2 provides a mechanism of global exception handling where we can display a global result to the user. Struts 2 automatically log the uncaught exceptions and redirects the user to the error handler page. Understanding the internal working of exception interceptor If there occurs exception, it is wrapped in ExceptionHolder and pushed in the valuestack so that we can easily access exception object from the result.
  • 58. There are 3 parameters defined for exception interceptor. All are optional. Parameter Description logEnabled specifies log should be enabled or not. You can pass true or false. logLevel specifies the log level. It may be trace, debug, info, warn, error, fatal. Default log level is debug. logCategory specifies the log category eg. com.mycompany.app. The default is com.opensymphony.xwork2.intercept or.ExceptionMappingInterceptor..
  • 59. Example of exception handling in struts 2 struts.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="aa" extends="struts-default"> <global-results> <result name="myresult">globalresult.jsp</result> </global-results> <global-exception-mappings> <exception-mapping result="myresult" exception="java.lang.Exception"></exception-mapping> </global-exception-mappings> <action name="login" class="com.Login"> <result>welcome.jsp</result> <result name="error">error.jsp</result> </action> </package> </struts>
  • 60. The global-results sub-element of package specifies the global-result for this package. The result sub-element of global-result specifies the result page that will be rendered to the user as a view. The global-exception-mappings sub-element of package specifies the exception mapping for all the actions of this package. The exception-mapping sub-element of global-exception-mapping maps the given result for the given exception type. In this example, we are using the Exception which the parent of many exception classes such as IOException, ArithmeticException etc. It means if any exception occurs, specified result will be invoked.
  • 61. globalresult.jsp <p>Exception Name: <s:property value="exception" /> </p> <p>Exception Details: <s:property value="exceptionStack" /></p> Full example of exception handling The other required resources to complete this example are as follows: • Input page (index.jsp) • Action class (Login.java) • View components (globalresult.jsp, welcome.jsp and error.jsp)
  • 62. 1) Create index.jsp for input <%@ taglib uri="/struts-tags" prefix="s" %> <s:form action="login"> <s:textfield name="name" label="Name"></s:textfield> <s:password name="password" label="Password"></s:password> <s:submit value="login"></s:submit> </s:form> 2) Create the action class Login.java package com; public class Login { private String name,password; //getters and setters public String execute(){ if(password.equals("struts")){ int a=12/0;//If you comment this, exception will not occur return "success"; }else return "error"; }
  • 63. 3) Create view components There are three view components globalresult.jsp that displays the exception message, welcome.jsp that displays the welcome message with the username and error.jsp that displays the error message. globalresult.jsp 1.<%@ taglib uri="/struts-tags" prefix="s" %> 2. 3.Sorry an exception occured! 4.<p>Exception Name: <s:property value="exception" /> </p> 5.<p>Exception Details: <s:property value="exceptionStack" /></p> 6.<form> 7.<input type="button" value="back" onclick="history.back()"> 8.</form> welcome.jsp 1.<%@ taglib uri="/struts-tags" prefix="s" %> 2.Welcome, <s:property value="name"/> error.jsp Sorry username or password error! <jsp:include page="index.jsp"></jsp:include>
  • 64. File Upload The fileUpload interceptor automatically works for all the requests that includes files. We can use this interceptor to control the working of file upload in struts2 such as defining allowed types, maximum file size etc. There are 2 parameters defined for fileupload interceptor. Parameter Description maximumSize specifies maximum size of the file to be uploaded. allowedTypes specifies allowed types. It may be image/png, image/jpg etc
  • 65. It automatically adds 2 parameters in the request : String fileName represents the filename of the file. String contentType specifies the content type of the file.
  • 66. 1) Create UserImage.jsp index.jsp <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Upload User Image</title> </head> <body> <h2> Struts2 File Upload & Save Example without Database </h2> <s:actionerror /> <s:form action="userImage" method="post" enctype="multipart /form-data"> <s:file name="userImage" label="Image" /> <s:submit value="Upload" align="center" /> </s:form> </body> </html>
  • 67. 2) Create SuccessUserImage.jsp SuccessUserImage.jsp <%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Success: Upload User Image</title> </head> <body> <h2> Struts2 File Upload Example </h2> User Image: <s:property value="userImage" /><br/> Content Type:<s:property value="userImageContentType" /><br/> File Name: <s:property value="userImageFileName" /><br/> Uploaded Image: <img src="userimages/ <s:property value="userImageFileName"/>" width="100" height="100" />
  • 68. 3) Create the action class RegisterAction.java package com.javatpoint; import java.io.File; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import com.opensymphony.xwork2.ActionSupport; public class FileUploadAction extends ActionSupport{ private File userImage; private String userImageContentType; private String userImageFileName; public String execute() { try { String filePath = ServletActionContext.getServletContext().getRealPath("/").concat("userimages"); System.out.println("Image Location:" + filePath);//see the server console for actual location File fileToCreate = new File(filePath,userImageFileName); FileUtils.copyFile(userImage, fileToCreate);//copying source file to new file return SUCCESS; } public File getUserImage() { return userImage; } public void setUserImage(File userImage) { this.userImage = userImage; } public String getUserImageContentType() { return userImageContentType; } public void setUserImageContentType(String userImageContentType) { this.userImageContentType = userImageContentType; } public String getUserImageFileName() { return userImageFileName; } public void setUserImageFileName(String userImageFileName) { this.userImageFileName = userImageFileName; }
  • 69. 4) Create struts.xml struts.xml <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="fileUploadPackage" extends="struts-default"> <action name="userImage" class="com.javatpoint.FileUploadAction"> <interceptor-ref name="fileUpload"> <param name="maximumSize">2097152</param> <param name="allowedTypes"> image/png,image/gif,image/jpeg,image/pjpeg </param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> <result name="success">SuccessUserImage.jsp</result> <result name="input">UserImage.jsp</result> </action> </package>
  • 71. ActionContext The ActionContext is a container of objects in which action is executed. The values stored in the ActionContext are unique per thread (i.e. ThreadLocal). So we don't need to make our action thread safe. We can get the reference of ActionContext by calling the getContext() method of ActionContext class. It is a static factory method. For example: ActionContext context = ActionContext.getContex t(); A valueStack is simply a stack that contains application specific objects such as action objects and other model object. At the execution time, action is placed on the top of the stack. We can put objects in the valuestack, query it and delete it.
  • 72. ActionInvocation ActionInvocation represen ts the execution state of an action. It holds the action and interceptors objects. ActionInvocation Interface The struts framework provides ActionInvocation interface to deal with ActionInvocation. It provides many methods, some of them can be used to get the instance of ValueStack, ActionProxy, ActionContext, Result etc. Methods of ActionInvocation Interface No. Method Description 1) public ActionContext getInvocationContext() returns the ActionContext object associated with the ActionInvocation. 2) public ActionProxy getProxy() returns the ActionProxy instance holding this ActionInvocation. 3) public ValueStack getStack() returns the instance of ValueStack. 4) public Action getAction() returns the instance of Action associated with this ActionInvocation. 5) public void invoke() invokes the next resource in processing this ActionInvocation. 6) public Result getResult() returns the instance of Result.
  • 73. Struts Architecture The architecture and flow of struts 2 application, is combined with many components such as Controller, ActionProxy, ActionMapper, Configuration Manager, ActionInvocation, Inerceptor, Action, Result etc. Here, we are going to understand the struts flow by 2 ways: struts 2 basic flow struts 2 standard architecture and flow provided by apache struts Struts 2 basic flow User sends a request for the action Controller invokes the ActionInvocation ActionInvocation invokes each interceptors and action A result is generated The result is sent back to the ActionInvocation A HttpServletResponse is generated Response is sent to the user
  • 74. Struts standard flow (Struts architecture) User sends a request for the action Container maps the request in the web.xml file and gets the class name of controller. Container invokes the controller (StrutsPrepareAndExecuteFilter or FilterDispatcher). Since struts2.1, it is StrutsPrepareAndExecuteFilter. Before 2.1 it was FilterDispatcher. Controller gets the information for the action from the ActionMapper Controller invokes the ActionProxy ActionProxy gets the information of action and interceptor stack from the configuration manager which gets the information from the struts.xml file. ActionProxy forwards the request to the ActionInvocation ActionInvocation invokes each interceptors and action A result is generated The result is sent back to the ActionInvocation A HttpServletResponse is generated
  • 75. Configuration Files From a Struts developer point of view, the one required configuration file used by the framework is web.xml. From here, you have full control over how Struts configures both itself and your application. By default, Struts will load a set of internal configuration files to configure itself, then another set to configure your application, however it is possible to build an entire Struts application without writing a single configuration file other than web.xml. The table lists the files that you can use to configure the framework for your application. Some configuration files can be reloaded dynamically. Dynamic reloading makes interactive File Optional Location (relative to webapp) Purpose web.xml no /WEB-INF/ Web deployment descriptor to include all necessary framework components struts.xml yes /WEB-INF/classes/ Main configuration, contains result/view types, action mappings, interceptors, and so forth default.properties yes /WEB-INF/classes/ Framework properties struts-default.xml yes /WEB-INF/lib/struts2-core.jar Default configuration provided by Struts struts-default.vm yes /WEB-INF/classes/ Default macros referenced by velocity.properties struts-plugin.xml yes At the root of a plugin JAR Optional configuration files for Plugins in the same format as struts.xml. struts-deferred.xml yes At the root of a plugin JAR Optional configuration files for Plugins, most useful for defining extension points velocity.properties yes /WEB-INF/classes/ Override the default Velocity configuration
  • 76. Struts 2 Validation To avoid the wrong values, we need to perform validation on forms where user submits some values. For example, if user writes his/her email id as abc, we need to give error message to the user that the given email id is not correct. So that we can have only valuable informations. There are three ways to perform validation in struts 2. 1) By Custom Validation Here, we must implement the Validateable interface (or extend ActionSupport class) and provide the implementation of validate method. 2) By Input Validation (built-in validators) Struts 2 provides a lot of predefined that can be used in struts 2 application to perform validation.