SpringMvc (1), springmvc

Source: Internet
Author: User

SpringMvc (1), springmvc

Simple spring MVC Configuration

1. first, you need. configure DispatcherServlet in xml. This class is the core class of springmvc. Therefore, operations are started from here and most of them are implemented here, such as analysis of various views and view

Ing. Configuration file:

    <servlet>        <servlet-name>springServlet</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>springServlet</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>

Since it is consistent with spring, there must be a configuration file, but we do not have a configuration file path, and the default path of the file can be modified, if no path is configured for this file, the default path is

/WEB-INF/springServlet-servlet.xml // The default path is:/WEB-INF/[servlet name]-servlet. xml

However, you can set attributes by yourself. In addition to the file path, you can also set the following attributes:

ContextClass: class that implements the WebApplicationContext interface. The current servlet uses it to create the context. If this parameter is not specified, XmlWebApplicationContext is used by default. ContextConfigLocation: A string sent to the context instance (specified by contextClass) to specify the location of the context. This string can be divided into multiple strings (using commas as the separator) to support multiple contexts (in the case of multiple contexts, if the same bean is defined twice, followed by a priority ). Namespace: The namespace of WebApplicationContext. The default value is [server-name]-servlet.

Files can be placed either under the WEB-INF or under the classpath, for example:

<servlet>     <servlet-name>springServlet</servlet-name>     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>     <init-param>         <param-name>contextConfigLocation</param-name>         <param-value>classpath:springmvc.xml</param-value>     </init-param>     <load-on-startup>1</load-on-startup> </servlet>  <servlet-mapping>     <servlet-name>springServlet</servlet-name>     <url-pattern>/</url-pattern> </servlet-mapping>

Note thatThis classpath refers to the location after compilation. When you first start learning the framework, you will always make such an error. The configuration file cannot be found because of the classpath problem.

For web projects, there is also a general syntax, which is placed under the ContextLoaderListener:

Restful

  <context-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath*:/spring-context*.xml</param-value>  </context-param>

Multi-file:

<context-param>      <param-name>contextConfigLocation</param-name>      <param-value>          classpath:spring-common-config.xml,          classpath:spring-budget-config.xml      </param-value></context-param>

In this way, springmvc is basically configured. spring configuration is not mentioned here.

After configuring simple web. xml, let's talk about DispatcherServlet.

From the above we should understand that it is actually a servlet. Since it is a servlet, it is much easier to understand.

The main method of DispathcherServlet is the following:

/**     * Initialize the strategy objects that this servlet uses.     * <p>May be overridden in subclasses in order to initialize further strategy objects.     */    protected void initStrategies(ApplicationContext context) {        initMultipartResolver(context);        initLocaleResolver(context);        initThemeResolver(context);        initHandlerMappings(context);        initHandlerAdapters(context);        initHandlerExceptionResolvers(context);        initRequestToViewNameTranslator(context);        initViewResolvers(context);        initFlashMapManager(context);    }

This method initializes various parser, adaptation, and so on. This method is called in the initialization method of its parent class. If you remember correctly, it is actually called when the Servlet init method is executed. First, let's take a look at the initialization of each of the above methods:

1. MultipartResolver refers to the file upload parsing class, which needs to be used during file upload. Let's look at this method:
Private void initMultipartResolver (ApplicationContext context) {try {
// Obtain the bean here. Note that this constant is defined in the front: MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver ";
// The bean name must be the one above when we configure it. Otherwise, it cannot be identified.
This. multipartResolver = context. getBean (MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver. class); if (logger. isDebugEnabled () {logger. debug ("Using MultipartResolver [" + this. multipartResolver + "]") ;}} catch (NoSuchBeanDefinitionException ex) {// Default is no multipart resolver. this. multipartResolver = null; if (logger. isDebugEnabled () {logger. debug ("Unable to locate MultipartResolver with name'" + MULTIPART_RESOLVER_BEAN_NAME + "': no multipart request handling provided ");}}}

If this parameter is not configured, no file upload is parsed by default. In this case, some problems may occur when uploading files.

2. LocaleResolver: Local resolution, that is, international resolution. If it is not set,

3. ThemeResolver also knows the name, that is, the style and theme parsing class. By default,

4. handlerMappings: request-to-processor ing. If the ing is successful, a HandlerExecutionChain object (including one Handler processor (page Controller) object and multiple HandlerInterceptor interceptors) object is returned; for example, BeanNameUrlHandlerMapping maps the URL to the Bean name. The Bean mapped to success is the processor here. It can be seen from the following code:

Protected HandlerExecutionChain getHandler (HttpServletRequest request) throws Exception {
// Request the ing to the processor. If the ing is successful, a HandlerExecutionChain object (including one Handler processor (page Controller) object and multiple HandlerInterceptor interceptor objects) will be returned );
// For example, BeanNameUrlHandlerMapping maps the URL and Bean name. The Bean mapped to success is the processor. Note that the processor here is worth handler, not handlerMapping.
// HandlerMapping is a template, and the processor handler is a Molding Product carved based on your bean.
For (HandlerMapping hm: this. handlerMappings) {if (logger. isTraceEnabled () {logger. trace ("Testing handler map [" + hm + "] in DispatcherServlet with name'" + getServletName () + "'");} HandlerExecutionChain handler = hm. getHandler (request); if (handler! = Null) {return handler;} return null ;}

5. HandlerAdapters: You can see the adapter and pack it into an adapter for various processors to support multiple types of processors.

HandlerAdapter ha = getHandlerAdapter (mappedHandler. getHandler (); // package the processor. All subsequent operations are performed by the adapter.

6 HandlerExceptionResolvers: a parser. For example, if an error occurs, it may be uniformly transferred to a page. There are also implementations by default. There are too many solutions to this requirement. There is nothing to talk about.

7. RequestToViewNameTranslator: When the processor does not return information such as the logical view name, the request URL is automatically mapped to the logical view name;

8 ViewResolvers: View parser. In our configuration, a view is usually configured as follows:

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

The view parser parses the above. The superclass only have one method.

View resolveViewName(String viewName, Locale locale) throws Exception;
9. flashMapManager is a container that stores data in redirect mode, which is equivalent to map sub-assembly. However, it is officially said that it is not used in programs, such as in controller, redirectAttributes is often used for data transmission.

After talking about several important attributes, we can enlarge the main attributes. Since servlet is used, let's take a look at the service method. The service here is like this:

protected void doService(HttpServletRequest request, HttpServletResponse response) 

There is such a code that requires attention, and other code is to configure some attributes or something.

try {            doDispatch(request, response);        }

This method is actually the core of DispatchServlet. The Parser and adapter we mentioned earlier are all operated here:

Protected void doDispatch (HttpServletRequest request, HttpServletResponse response) throws Exception {HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null; // as mentioned earlier. If handlerMapping is successful, this will be returned, including the processor and interceptor boolean multipartRequestParsed = false; WebAsyncManager asyncManager = WebAsyncUtils. getAsyncManager (request); try {ModelAndView mv = null; Exception dispatchException = null; try {
// Check whether the request is Multipart (such as file upload) processedRequest = checkMultipart (request); multipartRequestParsed = (processedRequest! = Request); // Determine handler for the current request.
        
// Ing mappedHandler = getHandler (processedRequest); if (mappedHandler = null | mappedHandler. getHandler () = null) {noHandlerFound (processedRequest, response); return;} // wrap the adapter // Determine handler adapter for the current request. handlerAdapter ha = getHandlerAdapter (mappedHandler. getHandler (); // Process last-modified header, if supported by the handler. string method = request. getMethod (); Boolean isGet = "GET ". equals (method); if (isGet | "HEAD ". equals (method) {long lastModified = ha. getLastModified (request, mappedHandler. getHandler (); if (logger. isDebugEnabled () {logger. debug ("Last-Modified value for [" + getRequestUri (request) + "] is:" + lastModified);} if (new ServletWebRequest (request, response ). checkNotModified (lastModified) & isGet) {return ;}} if (! MappedHandler. applyPreHandle (processedRequest, response) {return;} // Actually invoke the handler. mv = ha. handle (processedRequest, response, mappedHandler. getHandler (); if (asyncManager. isConcurrentHandlingStarted () {return;} // applyDefaultViewName (request, mv); mappedHandler. applyPostHandle (processedRequest, response, mv);} catch (Exception ex) {dispatchException = ex ;}
      
// The resolution view will eventually call view. render (mv. getModelInternal (), request, response); pass the model into processDispatchResult (processedRequest, response, mappedHandler, mv, dispatchException );}
// Some operations after compilation are followed by catch (Exception ex) {triggerAfterCompletion (processedRequest, response, mappedHandler, ex);} catch (Error err) {triggerAfterCompletionWithError (processedRequest, response, mappedHandler, err);} finally {if (asyncManager. isConcurrentHandlingStarted () {// Instead of postHandle and afterCompletion if (mappedHandler! = Null) {mappedHandler. applyAfterConcurrentHandlingStarted (processedRequest, response) ;}} else {// Clean up any resources used by a multipart request. if (multipartRequestParsed) {cleanupMultipart (processedRequest );}}}}

The above gives a brief introduction to springmvc's portal. In the next few days, I will study other functions of springmvc. I understand a lot of things by myself. I don't know, right? =.

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.