Introduction: I see many projects, developers have implemented their own MVC frameworks, not because they want to do different things with Struts, but because they don't realize how to extend Struts. Developing your own MVC framework can get all controls, but this also means that many resources are needed to achieve it (human material), in tense schedule, sometimes it is impossible. Struts is more than just a powerful framework, but it is also scalable. You can extend Struts in three ways. 1, Plugin: If you want to do some business logic during Application Startup or ShutDown, create your own Plugin class. 2, RequestProcessor: If you want to do some business logic in the process of being processed, create your own RequestProcessor class. For example, before each request is executed, you can extend the requestProcessor to check if the user logs in and whether he has permission to perform a particular action. 3, ActionServlet: If you want to do some business logic when you apply when Application Startup and ShutDown, you can also expand an ActionServlet class. However, you should use the ActionServlet when Plugin and RequestProcessor don't solve your needs. In this article, we will use an example of a Struts application to demonstrate how to use these three ways to expand Struts. The code for the sample program can be downloaded from http://www.onjava.com/onjava/2004/11/examples/sample1.zip. Two extensions Struts successful examples are the Validation and Tiles frameworks of Struts themselves. We assume that you are more familiar with the struts framework and know how to use it to create a simple application. If you want to know more about Struts, please refer to the official homepage. Plugin Plugin is an interface that you can create a class that implements the interface, do something when Application Startup or Shutdown is. For example, I created a web application using Hibernate as a persistent layer. I want to initialize Hibernate when I am started. So when I am a first request, Hibernate is already configured and usable. At the same time, we want to close hibernate when Application is closed. We can use a Hibernate Plugin to achieve this demand, through the following two steps: 1. Create a class to implement the Plugin interface:
public class HibernatePlugIn implements PlugIn {private String configFile; // This method will be called at application shutdown time public void destroy () {System.out.println ( "Entering HibernatePlugIn.destroy ()"); // Put hibernate cleanup code here System.out.println ( "Exiting HibernatePlugIn.destroy ()");} // This method will be called at application startup time public void init (ActionServlet actionServlet, ModuleConfig config) throws ServletException {System.out.println ( "Entering HibernatePlugIn .init () "); system.out.println (" Value of Init Parameter " getConfigfile ()); System.out.Println (" EXITING HibernatePlugin.init () ");} public string getconfigfile () {Return Name } Public void setconfigfile (String String) {configfile = string;}} The class that implements the PLUGIN interface must complete two methods: init () and destroy (). When the application startup is called, the destroy () method is called when Shutdown is called. Struts also allows you to transfer initialization parameters to your PLUGIN class. In order to pass parameters, you must create a JavaBean setter method for each parameter in the Plugin class. In our hibernatePlugin class, I will pass the CONFIGFILE's Name as the parameters, not the hardcoded to the program. 2, add the following code to Struts-Config.xml to advertise Struts has new Plugin:
For example, by default Struts calls request.isuserinrole () to check if the user has permission to execute current actionMApping; if you want to implement the database, you have to do it is to rewrite the processroles () method, by querying The user has a must-have necessary permissions to return True or False. First we will see how the process () method is implemented by default, then I will explain every method in the default RequestProcessor class so that you can decide which part is what you want to change.
public void process (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {// Wrap multipart requests with a special wrapper request = processMultipart (request); // Identify the path component we will // use to select a mapping String path = processPath (Request, Response); if (path == null) {return;}}}}}}}}}}}} {log.debug ("Processing A '" Request.getMethod () "' for path '" PATH " '");} // Select a Locale for the current user if requested processLocale (request, response); // Set the content type and no-caching headers // if requested processContent (request, response); processNoCache (request , response); (! processPreprocess (request, response) // General purpose preprocessing hook if) {return;} // Identify the mapping for this request ActionMapping mapping = processMapping (request, response, path); if (mapping == null ) {RETURN;} // check for any role required to perform this action if (! ProcessRoles (Request, Response , Mapping)) {return;} // Process any ActionForm bean related to this request ActionForm form = processActionForm (request, response, mapping); processPopulate (request, response, form, mapping);! If (processValidate (request, response, form, mapping)) {return;}! // Process a forward or include specified by this mappingif (processForward (request, response, mapping)) {return;}! if (processInclude (request, response, mapping)) {return; } // crete or acquire the action instance to // process this requestaction action = processactioncreate (request, response, mapping); if (action == null) {return;
} // Call the Action instance itselfActionForward forward = processActionPerform (request, response, action, form, mapping); // Process the returned ActionForward instanceprocessForwardConfig (request, response, forward);} 1, processMutipart (): In this method, Struts will read the request to check if the recuestTYPE is Multipart / Form-Data. If so, the request will be parsed and packaged into the httpservletRequest. When you create an HTML Form to submit the data, the Request's ContentType default is Application / X-WWW-form-Urlencoded. But if your Form uses the file type INPUT control allows the user to upload files, you must change ContentType to Multipart / Form-Data. If this is the case, you cannot get the data submitted by getParameter (); you must read the request as an InputStream and parsing it to get the parameter value. 2, ProcessPath (): In this method, Struts will read the REQUEST URI to determine the path element, which is used to get the actionMAppint element. 3, ProcessLocale (): In this method, Struts will get Locale for the current REQUEST. If you are configured, you can save this object as the value of the org.apache.struts.Action.Locale property in httpsession. As the side effects of this method, HttpSession will be created. If you don't want to create, you can set the local property to false in ControllerConfig, as follows:
Requested in struts config.xmlresponse.setheader ("Pragma", "No-cache"); Response.setHeader ("cache-control", "no-cache"); response.setdateHeader ("expires", 1); if you Want to set up no-cache header, add the following information in Struts-Config.xml:
public class CustomRequestProcessorextends RequestProcessor {protected boolean processPreprocess (HttpServletRequest request, HttpServletResponse response) {HttpSession session = request.getSession (false); // If user is trying to access login page // then do not check if (request.getServletPath () . Equals ("/ logininput.do") || request.getServletPath (). Equals ("/ login.do")) Return true; // check if username attribute is there is session. // if So, IT means User has allready logged in if (session = null && session.getAttribute ( "userName") = null!!) return true; else {try {// If no redirect user to login Page request.getRequestDispatcher ( "/ Login.jsp") .forward (request, response);} catch (Exception ex) {}} return false;} protected void processContent (HttpServletRequest request, HttpServletResponse response) {// Check if user is requesting ContactImageAction // if yes then set image / gif as Content Type if (Request.getServletPath (). Equals ("/ ContactImage .do ")) {response.setContentType (" image / gif "); return;} super.processContent (Request, Response);}} In the processpreprocess method for the CustomRequestProcessor class, we check the session username properties, if not found, Redirect the user to the landing page. For the demand for generating pictures as output, we must override the ProcessContent method, first check whether the request is / contactimage path. If so, we will set the contentType to Image / GIF; otherwise set to Text / HTML. 2, add the following text after your Struts-Config.xml file, tell the struts CustomRequestProcessor to be used as the RequestProcessor class: