MindRivet

Rivetting your Day!

Struts

April 12th, 2008 by admin

Struts is a framework that implements a Model-View- Controller (MVC) framework. The main purpose of an MVC framework is to separate presentation code and business logic code.

It is also very important to recognize what Struts is not -



Security
Access control
Individual tailored customized views / portal framework
Data Access
Multi channel distribution


What kind of benefits Struts will bring?

Enforces Modularity and Application Partitioning
Increases Role Separation
Increases code manageability
Increase code extensibility (Ability to adapt change)

Struts Overview

Features

Web Application Framework based on MVC framework
Struts is an Controller Centric Framework
Multiple sub-applications support
Common Utilities like File uploading and handling multipart requests
Custom Tag Libraries
Capturing Form Data
Once Only Submission
Declarative Exception Handling
Internationalization and Localization Support
Validator Framework
Includes Tiles Framework


Struts is Based on MVC Architecture

Client browser: An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response.
Controller: The Controller receives the request from the browser, and decides where to send the request. The Controller is a command design pattern implemented as a servlet. The struts-config.xml file configures the Controller.
Business logic: The business logic updates the state of the model and helps control the flow of the application. With Struts this is done with an Action class as a thin wrapper to the actual business logic.
Model state: The model represents the state of the application. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. The JSP file reads information from the ActionForm bean using JSP tags.
View: The view is simply a JSP file. There is no flow logic, no business logic, and no model information — just tags.


Struts Controller Components

ActionServlet
RequestProcessor
Action classes

ActionServlet

It implements both the Front Controller and Singleton pattern.
Centralized access to the presentation tier request handling.
Best Practice – Never access any JSP directly use forward instead
The process() method is called to handle the request either through a doGet() or doPost() method passing the request and response for request processing.
Delegates the request processing to RequestProcessor class.

Responsibilities:
Intercept client requests.
Map each request to a specific business operation.
Collect results from the business operation and make available to the client.
Determine the view to display to the client based on the current state and and result of the business operation.

Configuring web.xml for Struts:
<servlet>
 <servlet-name>action</servlet-name>
 <servlet-class>
 org.apache.struts.action.ActionServlet
 </servlet-class>
<!– Default Application Module –>
<init-param>
   <param-name>config</param-name>
   <param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<!– Sub Application Module –>
<init-param>
   <param-name>config/sub</param-name>
   <param-value>/WEB-INF/struts-sub-config.xml</param-value>
</init-param>
</servlet>
<!– Action Servlet Mapping –>
<servlet-mapping>
 <servlet-name>action</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

Initialization:
The servlet container loads ActionServlet when it is started or when the first request is fired by calling its init() method.
It first loads the framework’s internal message bundle.
Then, the default application as well as its Application Message Resources and plug-ins are loaded.
The above step is followed for the each application module configured.

RequestProcessor
 With Struts 1.1, the RequestProcessor was introduced to allow the developers to customize request-handling rather that sub-classing the ActionServlet.The ActionServlet delegates the request by calling the process() method to it passing the request and response. This method is similar to that of the ActionServlet.
 This process() method in turn passes the request through the set of process methods before the request is fulfilled passing the request and response objects.
 Some of the methods include
processMultipart():  If the request is of type multipart/form-data, it wraps as a MultipartRequestWrapper instance which  will wrap the request.
processLocale(): Used to locate the locale of the user and store it in the HttpSession.
processNoCache(): Used to set the proper header parameter in the response object.
processPreProcess(): This is an empty hook you can override as needed. It returns a Boolean. Return true to continue processing as normal or false if the response has now been completed.
processContent(): Sets the default content type in the response based on config.
processMapping(): Returns the appropriate ActionMapping from the config for this request
processActionForm(): Returns the Action Form instance associated with this mapping. If one doesn’t exist in session or request (as defined in struts-config) will create one as appropriate
processValidate(): Calls validate() in the action Form. If there were any errors it returns false (and the request will be forwarded back to the input), or true if validation succeeded.
 processActionCreate(): Returns the instance of Action that will perform the request.
 processActionForward(): Forwards or redirects based on the Action Forward returned by the action > when its execute method was called. (If that forward was null, this method > does nothing.)
 This class could be extended to provide a custom behavior of request handling like overriding the processPreProcess() method to perform the preprocessing of the request before it is delegated the request handler i.e. Action class.
Configuration
 The RequestProcessor is configured in the struts-config.xml.
 <controller contentType=”text/html;charset=UTF-8″
 locale=”true“ nocache=”true“ processorClass=”com.dev.struts.CustomRequestProcessor”/>

Using RequestProcessor for session / login checking
public class SessionRequestProcessor extends
 RequestProcessor{ protected String processPath(HttpServletRequest
 request,  HttpServletResponse response)  throws IOException
 {           
       String origPath = request.getRequestURI();
  if(!origPath.endsWith( “/Login.do “)){
     HttpSession session =
 request.getSession(false); // get session only if
 it exists
  if (session != null ) { // session
 available,
  return super.processPath(request,
 response);
  }
 else // redirect to login page
     return “/Login “;    // returns without .do
       }
 else {
 HttpSession session =
 request.getSession(false); // get session only if
 it exists
  if (session != null)
 session.invalidate();
 return super.processPath(request, response);
 // process login page request
   }
      }

Action
An Action is an Adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed.
Each Action class is designed to perform a single business operation on behalf of the client.
Usually thin classes with most business logic being performed in JavaBean or EJB.
The execute() method of the Action class is called by the RequestProcessor depending upon the request.
Action classes are expected to be thread-safe as only a single instance of each Action class is created for an application.
It is a best practice to create an Application-specific Action base class which provides you with added flexibility and extensibility by allowing common Action behavior in the parent class.
ActionForward class
The ActionForward class represents a logical abstraction of a web resource. This may be an JSP/Servlet.
This reduces the coupling between the application and the physical resource.
The physical resource is specified in the configuration file.

Each action element in the configuration file is represented in memory by an instance of ActionMapping class.

Configuration
<action
   input=”/security/signin.jsp”
   name=”loginForm”
   path=”/signin”
   scope=”request” type=”com.dev.storefront.LoginAction”
   validate=”true”>
   <forward name=”Success” path=”/index.jsp” redirect=”true”/>
   <forward name=”Failure” path=”/security/signin.jsp” redirect=”true”/>
 </action>

Implementation:
public class LoginAction extends AppBaseAction {
 public ActionForward execute( ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request, HttpServletResponse response )
  throws Exception{
   LoginForm loginform = (LoginForm) form;
 UserDTO user = new UserDTO();
     BeanUtils.copyProperties( user, loginform); 
 return mapping.findForward( “Success” );
 }
}
References
[
struts.apache.org
www.onjava.com/pub/a/onjava/2002/12/11/jakartastruts.html
[

This entry was posted on Saturday, April 12th, 2008 at 11:01 am and is filed under Java. You can follow any responses to this entry through the RSS 2.0 feed. Responses are currently closed, but you can trackback from your own site.

Bookmark and Share

Comments are closed.