Back to: Java Struts Tutorials
Java Struts 2 Components
In this article, I am going to discuss Java Struts 2 Components. Please read our previous article where we discussed Model 1 and Model 2 (MVC) Architecture. At the end of this article, you will understand the following pointers in detail which are related to Java Struts 2 Components.
- Action Beans
- Action servlets
- ActionForm beans and Custom Tags
- Value Stack / OGNL
- Results / Result types
- View technologies
- Action context
Let us understand the need and use of the above struts components one by one in detail.
What is the Bean tag?
- It is used to create an instance of a bean in a JSP page.
- It is a combination of the set and push tags.
- The bean should have a no-argument constructor.
What is/are the syntax of Action Beans?
In JSP form –
<s:bean name=”org.apache.struts2.example.counter.SimpleCounter” var=”counter”>
<s:param name=”foo” value=”BAR” />
The value of foot is : <s:property value=”foo”/>, when inside the bean tag <br />
In Freemarker form –
[@s.bean name=”org.apache.struts2.example.counter.SimpleCounter” var=”counter”]
[s:param name=”foo” value=”BAR”/]
The value of foo is : [s:property value=”foo”/], when inside the bean tag.
ActionServlet in Struts2 framework is used to develop the Model-View-Controller (MVC) based on web application which is basically designing for the pattern which is commonly called as “Model 2”. In this process, all the requests to the server move through the controller and the responsibility of the controller is to hand over all the requests. Struts Flow start and then call to process() method which is necessary to service the request from the user.
The tasks that are assigned to the ActionServlet are as follows:
- It identifies the substring that will be used to select an action process from the incoming request URI.
- The substring is used to map the Java class name of the corresponding dispatcher.
- For a particular dispatcher if a request is made the first time, then that class is instantiated and it will be cached for future usage.
- Otherwise, the properties of an ActionForm Bean are associated with the mapping.
- The execute method of the dispatcher is called while providing the access to the mapping that was used before, any relevant form-bean (if present), and the request as well as the response that was passed to the controller by the servlet container.
ActionForm is a java bean that combines one or more than one ActionMappings. It maintains the session state for web applications. The ActionForm object is populated automatically on the server side when data is entered on a client-side.
What are Custom tags?
These are user-defined tags. They isolate business logic from JSP pages and also removes the possibility of scriptlet tags. Due to the use of custom tags the same business logic can be used.
Why do we use Custom tags?
- Eliminating the need for scriptlet tag the non-existence of any scriptlet tags gives a good coding approach.
- Separation of business logic from JSP isolates business logic from JSP pages, which makes the maintenance much easier.
- Re-usability Due to the use of custom tags the same business logic can be used repeatedly.
How to use Custom Tags?
1. <prefix:tagname attr1=value1….attrn=valuen />
2. <prefix:tagname attr1=value1….attrn=valuen >
What is an Interceptor?
At the time of preprocessing and postprocessing of a request, the interceptor object is called. Many features are implemented in Struts 2 using interceptors such as – validation, exception handling, file uploading, etc.
Why Interceptor is used?
To delete any concern like validation, exception handling, logging, etc. from the application, there is no need for the redeployment of the application, what we need to do is that just eliminate the entry from the struts.xml file.
What are the different kinds of default interceptors?
- alias – converts similar types of parameters that have disparate names between requests.
- chain – makes the properties of preceding action that are available in the current action and also used with chain result type.
- checkbox – used to handle the checkboxes in the sequence manner. And through this, we can easily identify the unchecked checkboxes.
- cookie – used to add a cookie to the current action.
- conversionError – used to add conversion errors to the action’s field errors.
- createSession – used to create the HttpSession object if it doesn’t exist.
- clearSession – releases the HttpSession object.
- debugging – used to provide support for debugging.
- execAndWait – used to send an intervening waiting page for the result.
- exception – used to guide an exception to a result.
- fileUpload – used to provide support to file upload in struts 2.
- i18n – used to provide support to internationalization and localization.
- jsonValidation – provides support to asynchronous support.
- logger – used to find out the action name.
- store – used to store and repossess action messages, action errors for action that implements the ValidationAware interface.
- modelDriven – used to make other model objects as the default object of valuestack.
- scopedModelDriven – same as ModelDriven but works only for action that implements ScopedModelDriven.
- params – colonizes the action properties with the request parameters.
- prepare – used to perform preparation logic if action implements a Preparable interface.
- profiling – used to support action profiling.
- roles – used to support role-based action.
- scope – used to store the action state in the session or application scope.
- servletConfig – used to provide access to maps that represent HttpServletRequest and HttpServletResponse.
- staticParams – pointing the static properties to action properties.
- timer – gives the output to the time that needed to execute an action.
- token – prevents imitation submission of the request.
- tokenSession – prevents imitation submission of the request.
- validation – used to provide support to input validation.
- workflow – can call the validate method of action class if any action class implements Validateable interface.
How to configure Interceptors?
In the Struts.xml file –
<package name="default" extends="struts-default"> <interceptors> <interceptor name="timer" class=".."/> <interceptor name="logger" class=".."/> </interceptors> <action name="login" class="tutorial.Login"> <interceptor-ref name="timer"/> <interceptor-ref name="logger"/> <result name="input">login.jsp</result> <result name="success" type="redirectAction">/secure/home</result> </action> </package>
What is ValueStack?
A ValueStack is simply a stack that contains application-specific objects such as Action object, Model object, Named objects, and Temporary objects. Though the action is placed at the top of the stack during the execution time.
What are the methods that are used in ValueStack?
findValue(String expr): To find a value for a specific expression
Syntax: public Object findValue(String expr)
findString(String expr): To find a string for a specified expression
Syntax: public String findString(String expr)
peek(): It returns the object which is at the top of the stack without removing it
Syntax: public Object peek()
pop(): It returns the object which is at the top of the stack and removes it from the stack
Syntax: public Object pop()
push(Object o): Put the specified object on the top of the stack
Syntax: public void push(Object o)
set(String key, Object value): Sets an object on the stack with the specified key, which can be retrieved using findValue(key)
Syntax: public void set(String key, Object value)
size(): It gives the no. of objects in the stack
Syntax: public int size()
What is OGNL?
Object Graph Navigational Language (OGNL) is an open-source framework used to get properties from Java Beans. In Struts 2 –
- It is used to reference and manipulate data on the ValueStack.
- performs two important tasks – data transfer and type conversion.
What are the features of OGNL?
- type conversion
- calling methods
- collection manipulation and generation
- projection across collections
- expression evaluation
- lambda expressions
What is the result?
It acts as a view in the Struts2 MVC framework. It is responsible for redirecting to the destination page which can be specified between the <result> elements together with the name of the result (that is, type of result). The type of result is referred to by the result name.
Predefined result types which are returned by the action class and compared here as the string data type.
- String SUCCESS = “success”
- String NONE = “none”
- String ERROR = “error”
- String INPUT = “input”
- String LOGIN = “login”
User- defined result types
- The dispatcher result – used to include or forward to a target view page (JSP).
- Chain action result – used to achieve action chaining. The multiple actions can be executed in a defined sequence and at the last action, the target view page will be displayed.
- Freemarker result – integrate the Freemarker templates on the view page.
- Redirect result – used to redirect the browser request to the new resource.
- Redirect action – same as redirect result type. But the target result must be an action either in the same application or in the other application.
- Stream result – used to Streaming the InputStream back to the client and the client can download the content in the specified format.
- It is basically a container that stores the objects that are related to the current request-response of a web application.
- It is created during a session, or application or locale, etc. during a complete client-server interaction.
- The objects are stored in a particular manner such as Temporary Objects -> Model Object -> Action Object -> Named Object.
- It consists of all the objects of ValueStack + other objects related to the current interaction of web applications to the client.
What is ActionInvocation?
It represents the execution state of activity. It holds the action and interceptor’s objects.
What are the ActionInvocation methods?
|public ActionContext getInvocationContext()||returns the ActionContext object related with the ActionInvocation.|
|public ActionProxy getProxy()||returns the ActionProxy occasion holding this ActionInvocation.|
|public ValueStack getStack()||returns the occasion of ValueStack.|
|public Action getAction()||returns the occasion of Action related with this ActionInvocation.|
|public void invoke()||invokes the following asset in handling this ActionInvocation.|
|public Result getResult()||returns the occasion of Result.|
In the next article, I am going to discuss Java Struts 2 Architecture and Flow in detail. Here, in this article, I try to explain Java Struts 2 Components and I hope you enjoy this Java Struts 2 Components article.