Learning the open source project jpetstore that comes with springMVC---one spring-mvc.xml configuration file analysis of study notes

Before writing this blog, I will briefly introduce the roles played by the web.xml, spring-mvc.xml, and applicationContext.xml configuration files in the ssm framework. If there is anything wrong, please criticize and correct me.
1. The web.xml configuration file is a configuration file that must exist in each web project. When the server is turned on, the server container will load and parse this configuration file, and convert the configuration information into key-value pairs. The ServletContext object is used by the entire project program. The web.xml configuration file can be said to be the entrance of the entire web project, so in the ssm framework project, it is generally configured in the web.xml file: front-end controller DispatcherServlet, encoding processing CharacterEncodingFilter, context Listeners, jsp file property settings, error handling, spring configuration file loading properties, etc.
2.spring-MVC.xml configuration file: In fact, springMVC is a module of spring. In theory, the configuration information in springMVC can be combined with application.xml. The configuration information is placed in the same configuration file, but in order to reflect the modularity of the program and enhance the maintainability of the project, the configuration information of springMVC and the configuration information of spring are generally placed in two different xml files. In the spring-mvc.xml configuration file, it is more inclined to the request mapping of the foreground, the response jump from the background to the foreground, etc., so the configuration information in the spring-mvc.xml configuration file roughly includes: the front-end controller InternalResourceViewResolver, the controller layer The class is handed over to the spring container for management, front-end request URL and back-end controller mapping configuration, etc.
3. applicationContext.xml configuration file (spring configuration file): The word application means application, we can see from the meaning of the word that the applicationContext.xml configuration file is more inclined to the configuration of program resources and no longer focuses on requests and response. Therefore, the configuration information that generally exists in the applicationContext.xml configuration file includes: the configuration of the data source, all other class resources except the controller layer class, the integration configuration of mybatis, and the configuration of transaction management.
Let's parse the spring-mvc.xml configuration file of the open source project jpetstore: 1.
Configuration and function of InternalResourceViewResolver (view resolver):
the original configuration file:

<bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
        <property name="order" value="2" />
    </bean>

Generally speaking, the view parser accepts the response information from the controller layer to the foreground, parses the information, and finally returns a view to the foreground. InternalResourceViewResolver will parse the returned view names into InternalResourceView objects, InternalResourceView will store all the model properties returned by the Controller handler method in the corresponding request properties, and then redirect the request forword to the target URL on the server side through RequestDispatcher. For example, if prefix=/WEB-INF/views, suffix=.jsp is defined in InternalResourceViewResolver, and the view name returned by the requested Controller handler method is test, then InternalResourceViewResolver will parse test as an InternalResourceView object. The returned model attributes are stored in the corresponding HttpServletRequest attributes, and then the RequestDispatcher is used to forword the request to /WEB-INF/views/test.jsp on the server side. We can look at the source code and find these two methods:

@Override
    protected View createView(String viewName, Locale locale) throws Exception {
        // If this resolver is not supposed to handle the given view,
        // return null to pass on to the next resolver in the chain.
        if (!canHandle(viewName, locale)) {
            return null;
        }
        // Check for special "redirect:" prefix.
        if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
            String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length());
            RedirectView view = new RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible());
            return applyLifecycleMethods(viewName, view);
        }
        // Check for special "forward:" prefix.
        if (viewName.startsWith(FORWARD_URL_PREFIX)) {
            String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length());
            return new InternalResourceView(forwardUrl);
        }
        // Else fall back to superclass implementation: calling loadView.
        return super.createView(viewName, locale);
    }
@Override
    protected void renderMergedOutputModel(
            Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        // Determine which request handle to expose to the RequestDispatcher.
        HttpServletRequest requestToExpose = getRequestToExpose(request);

        // Expose the model object as request attributes.
        exposeModelAsRequestAttributes(model, requestToExpose);

        // Expose helpers as request attributes, if any.
        exposeHelpers(requestToExpose);

        // Determine the path for the request dispatcher.
        String dispatcherPath = prepareForRendering(requestToExpose, response);

        // Obtain a RequestDispatcher for the target resource (typically a JSP).
        RequestDispatcher rd = getRequestDispatcher(requestToExpose, dispatcherPath);
        if (rd == null) {
            throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +
                    "]: Check that the corresponding file exists within your web application archive!");
        }

        // If already included or response already committed, perform include, else forward.
        if (useInclude(requestToExpose, response)) {
            response.setContentType(getContentType());
            if (logger.isDebugEnabled()) {
                logger.debug("Including resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'");
            }
            rd.include(requestToExpose, response);
        }

        else {
            // Note: The forwarded resource is supposed to determine the content type itself.
            exposeForwardRequestAttributes(requestToExpose);
            if (logger.isDebugEnabled()) {
                logger.debug("Forwarding to resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'");
            }
            rd.forward(requestToExpose, response);
        }
    }

From these source codes, we can see that after the InternalResourceViewResolver further parses and encapsulates the response information returned by the controller layer, it will use the server-side jump method to return the view to the foreground.
This is a very important feature of InternalResourceViewResolver. We all know that the content stored under /WEB-INF/ cannot be directly requested by request. For security reasons, we usually put jsp files in WEB-INF directory, and the way InternalResourceView jumps on the server side can solve this problem very well.
2. <context:component-scan base-package="包名" />The configuration and function of the label:
This label is mainly used to automatically scan all the classes registered under the base-package, and hand them over to the spring container for management.
3. <mvc:annotation-driven></mvc:annotation-driven>Configuration and role of tags:
<mvc:annotation-driven></mvc:annotation-driven>Two beans, RequestMappingHandlerMapping and RequestMappingHandlerAdapter, are automatically registered, which are required for Spring MVC to distribute requests for @Controller, and provide data binding support, @NumberFormatannotation support, @DateTimeFormat support, @Valid support Support for reading and writing XML (JAXB) and support for reading and writing JSON (default Jackson). That is to say, after configuring this tag, spring will automatically configure some necessary beans for me. These beans include the necessary beans for mapping with the controller layer using the annotation requestMapping.
4. <mvc:default-servlet-handler />Configuration and role of tags:
Since we configure in the web.xml configuration file to intercept all requests, that is, /*, this will cause static resources to be intercepted, so configure in springMVC.xml<mvc:default-servlet-handler />After that, a org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler will be defined in the Spring MVC context, which will act like an inspector to screen the URL entering the DispatcherServlet. If it is found to be a request for static resources, the request will be It is transferred to the default Servlet of the Web application server for processing. If it is not a request for static resources, the DispatcherServlet will continue to process it.
5. <mvc:resources/>Configuration and use of tags:
This tag is also used to process static resources. Here is a blog that mainly writes about the <mvc:default-servlet-handler />functions and differences between this tag and : https://blog.csdn.net/xiao______xin/article/details/54093355
6. The function analysis of the following original configuration file configuration code slice:

<bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="order" value="1" />
        <property name="exceptionMappings">
            <util:map>
                <entry key="ResourceNotFoundException" value="notFoundError" />
            </util:map>
        </property>
        <property name="statusCodes">
            <util:map>
                <entry key="notFoundError" value="404" />
            </util:map>
        </property>
        <property name="defaultStatusCode" value="500" />
        <property name="defaultErrorView" value="systemError" />
        <property name="warnLogCategory"
            value="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" />
    </bean>

SimpleMappingExceptionResolver can only simply handle exceptions. When an exception occurs, it jumps to the specified page to display the exception information according to the type of exception that occurs. Here we can compare with the <error-page></error-page>tags These two tags are used to handle exceptions, but the <error-page></error-page>tags can only handle errors that occur during the front-end request process, and cannot print error messages. SimpleMappingExceptionResolver can handle the server. The exception occurred in the processing page, and the exception information can be printed on the processing page, which means that SimpleMappingExceptionResolver is actually more focused on exception handling.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324735286&siteId=291194637