SSH framework-Struts (3)-core methods for running Struts

Source: Internet
Author: User

SSH framework-Struts (3)-core methods for running Struts

In the previous article, we talked about how to instantiate an ActionServlet for a single instance in Tomcat and perform initialization according to the web. xml configuration file. At this time, the client generates a request at the End of. do. After the request is submitted in get/post mode, no matter which method the request is submitted, it will enter the process core method.


ActionServelt doGet () and doPost () Methods


      public void doGet(HttpServletRequest request,HttpServletResponse response)        throws IOException, ServletException {        process(request, response);    }    public void doPost(HttpServletRequest request,      HttpServletResponse response)        throws IOException, ServletException {        process(request, response);    }


Process Method


    protected void process(HttpServletRequest request, HttpServletResponse response)        throws IOException, ServletException {        ModuleUtils.getInstance().selectModule(request, getServletContext());        ModuleConfig config = getModuleConfig(request);        RequestProcessor processor = getProcessorForModule(config);        if (processor == null) {           processor = getRequestProcessor(config);        }        processor.process(request, response);    }

This method has two main functions:

First, call org. apache. struts. util. the selectModule () method of the ModuleUtils class. This method selects the module responsible for processing the current request based on the request object and servletContext, the ModuleConfig and MessageResources objects related to this module are stored in the reverse request range, which allows other components of the framework to conveniently read these objects from the request range, to obtain application configuration information and Message Resources.
Second, instantiate the RequestProcessor class, and then call the process () method of the RequestProcessor class to complete more than a dozen pre-processing request operations.


RequestProcessor process () method


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;        }                if (log.isDebugEnabled()) {            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);        // General purpose preprocessing hook        if (!processPreprocess(request, response)) {            return;        }                this.processCachedMessages(request, response);        // 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);                // Validate any fields of the ActionForm bean, if applicable        try {            if (!processValidate(request, response, form, mapping)) {                return;            }        } catch (InvalidCancelException e) {            ActionForward forward = processException(request, response, e, form, mapping);            processForwardConfig(request, response, forward);            return;        } catch (IOException e) {            throw e;        } catch (ServletException e) {            throw e;        }                    // Process a forward or include specified by this mapping        if (!processForward(request, response, mapping)) {            return;        }                if (!processInclude(request, response, mapping)) {            return;        }        // Create or acquire the Action instance to process this request        Action action = processActionCreate(request, response, mapping);        if (action == null) {            return;        }        // Call the Action instance itself        ActionForward forward =            processActionPerform(request, response,                                 action, form, mapping);        // Process the returned ActionForward instance        processForwardConfig(request, response, forward);    }




According to the process () method,

1. processMultipart (); 1. First, determine whether it is post. If it is not post, it is definitely not an upload request. Then the request object is directly returned.

if (!"POST".equalsIgnoreCase(request.getMethod())) {return (request);        }

2. Obtain the ContentType of the request object. If ContentType is multipart/form-datade, a new MultipartRequestWrapper object is returned. Otherwise, the request is directly returned.

 String contentType = request.getContentType();        if ((contentType != null)            && contentType.startsWith("multipart/form-data")) {            return (new MultipartRequestWrapper(request));        } else {            return (request);        }

In short, it is used to determine whether the upload function is required. If the upload function is required, you must change the form contentType to multipart/form-data, this method is used to parse and package it into a package that implements HttpServletRequest to serve the upload of files.

Ii. processPath ()

        String path = processPath(request, response);        if (path == null) {            return;        }                if (log.isDebugEnabled()) {            log.debug("Processing a '" + request.getMethod() +                      "' for path '" + path + "'");        }


Call the processPath method to obtain the name of the specific action to be accessed.




Iii. processLocale ()

protected void processLocale(HttpServletRequest request,HttpServletResponse response) {        // Are we configured to select the Locale automatically?        if (!moduleConfig.getControllerConfig().getLocale()) {            return;        }        // Has a Locale already been selected?        HttpSession session = request.getSession();        if (session.getAttribute(Globals.LOCALE_KEY) != null) {            return;        }        // Use the Locale returned by the servlet container (if any)        Locale locale = request.getLocale();        if (locale != null) {            if (log.isDebugEnabled()) {                log.debug(" Setting user locale '" + locale + "'");            }            session.setAttribute(Globals.LOCALE_KEY, locale);        }    }
   

Whether it is a local service or an international service, which is based on the browser settings (specifically, based on the operating system settings)

4. processContent (); processNoCache ();

ProcessContent is used to determine the content type and encoding type.
ProcessNoCache determines whether certain content is cached Based on the configuration attributes in the configuration file.

5. processMapping ()

Obtain the corresponding actionmapping from Struts. config. xml according to the request, response, and action names, that is, put the action to be requested in the configured request into the ActionMapping object.


1. First, find the corresponding configuration information in the configuration file.


// Is there a mapping for this path?  ActionMapping mapping = (ActionMapping) moduleConfig.findActionConfig(path);


2. Put the configuration in the request and return it.

        // If a mapping is found, put it in the request and return it        if (mapping != null) {            request.setAttribute(Globals.MAPPING_KEY, mapping);            return (mapping);        }


3. Find "unknown ing path (if any )". If it is found, put it in the request and return it.

        // Locate the mapping for unknown paths (if any)        ActionConfig[] configs = moduleConfig.findActionConfigs();        for (int i = 0; i < configs.length; i++) {            if (configs[i].getUnknown()) {                mapping = (ActionMapping) configs[i];                request.setAttribute(Globals.MAPPING_KEY, mapping);                return (mapping);            }        }


4. If the mapping information is still not found, an error message is sent and null is returned.

        // No mapping can be found to process this request        String msg = getInternal().getMessage("processInvalid");        log.error(msg + " " + path);        response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);        return null;

In this case, the ActionMapping element contains the name of the Action class and the information of the ActionForm used in the request, and the ActionForwards information configured in the current ActionMapping.

6. processActionForm ()

 protected ActionForm processActionForm(HttpServletRequest request,                                           HttpServletResponse response,                                           ActionMapping mapping) {        // Create (if necessary) a form bean to use        ActionForm instance = RequestUtils.createActionForm            (request, mapping, moduleConfig, servlet);        if (instance == null) {            return (null);        }        // Store the new instance in the appropriate scope        if (log.isDebugEnabled()) {            log.debug(" Storing ActionForm bean instance in scope '" +                mapping.getScope() + "' under attribute key '" +                mapping.getAttribute() + "'");        }        if ("request".equals(mapping.getScope())) {            request.setAttribute(mapping.getAttribute(), instance);        } else {            HttpSession session = request.getSession();            session.setAttribute(mapping.getAttribute(), instance);        }        return (instance);    }

Check whether the name attribute or attribute is configured in mapping to specify the ActionForm. If ActionForm is configured, search for it in the session or Request and return it. If no value is found, create Based on the ActionForm path and put it into the scope domain. VII. processPopulate ()


 protected void processPopulate(HttpServletRequest request,                                   HttpServletResponse response,                                   ActionForm form,                                   ActionMapping mapping)        throws ServletException {        if (form == null) {            return;        }        // Populate the bean properties of this ActionForm instance        if (log.isDebugEnabled()) {            log.debug(" Populating bean properties from this request");        }                form.setServlet(this.servlet);        form.reset(mapping, request);                if (mapping.getMultipartClass() != null) {            request.setAttribute(Globals.MULTIPART_KEY,                                 mapping.getMultipartClass());        }                RequestUtils.populate(form, mapping.getPrefix(), mapping.getSuffix(),                              request);        // Set the cancellation request attribute if appropriate        if ((request.getParameter(Constants.CANCEL_PROPERTY) != null) ||            (request.getParameter(Constants.CANCEL_PROPERTY_X) != null)) {                            request.setAttribute(Globals.CANCEL_KEY, Boolean.TRUE);        }    }

This method is mainly used to fill in data for ActionForm, execute the reset method of ActionForm, and then obtain the names of all input fields in the form, according to the request. getParameter obtains the value corresponding to the input domain name, and then puts the input domain name and value in the form of a key-value pair into the map, call BeanUtils, an important third-party component, to convert attributes and copy them to a specific ActionForm.


8. processValidate ()

Verify the validity of the form data. This method is optional. If Struts verification is used, this method is automatically executed for verification.

9. processForward ()

Handle the forward and include specified by mapping. Struts checks the values of the forward and include attributes of elements. If there is a configuration, the forward and include requests are placed on the configuration page, then, it is forwarded to the specific ActionServlet for processing specific business logic.

Summary


So far, the core method process OF RequestProcessor has been executed. And then perform business-related operations in the specific Action.

Throughout the execution process, there are two main methods: one is the process method in AcionServlet, and the other is the process () method of RequestProcessor. For other methods to intercept the Request Path and fill the actionForm, methods such as internationalization are also used to encapsulate the appearance mode in the process method.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.