SPRINGMVC (1)

Source: Internet
Author: User
Tags locale

Simple configuration of the SPRINGMVC

1. First, you need to configure Dispatcherservlet in Web. XML, this class is the core class of SPRINGMVC, so the operation starts here, and most of it is implemented here, such as the parsing of various views, the view's

mappings, and so on. 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 a set of spring, there must be a configuration file, but we do not have the configuration file path, the default path of the file can be modified, if we do not configure the file path, the default path is

/web-inf/springservlet-servlet.xml//  

But we can set the properties of our own, in addition to the file path, you can also set a few properties:

Contextclass: The class that implements the Webapplicationcontext interface, which is used by the current servlet to create the context. If this parameter is not specified, Xmlwebapplicationcontext is used by default. Contextconfiglocation: A string that is passed to the context instance (specified by Contextclass) to specify the location of the context. This string can be broken into multiple strings (using commas as delimiters) to support multiple contexts (in multi-context cases, if the same bean is defined two times, the next one takes precedence).  namespace:webapplicationcontext namespace. The default value is [Server-name]-servlet.

Files can be placed under Web-inf, or under Classpath, such as:

<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 that this classpath refers to the post-compilation location, just beginning to learn the framework, always make such a mistake, can not find the configuration file, is because of the classpath problem.

For Web projects, there is a common notation, which is put under Contextloaderlistener:

RESTful style of

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

Support for multiple files:

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

This way, SPRINGMVC is basically configured, and there is no spring configuration here.

With the simple Web. Xml configured above, let's talk about Dispatcherservlet.

From the above we should understand, in fact, it is a servlet, since it is a servlet, then it is much easier to understand.

Dispathcherservlet The most important is the following several methods, the following hit simple look:

/* *     * Initialize The strategy objects that this servlet uses.     * <p>may is 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 is to initialize a variety of parser, adaptation, and so on, this method is called in the initialization method of its parent class, remember correctly, is actually equivalent to the servlet init method is called when executing. First understand what each of the above methods initializes:

1.MultipartResolver refers to the file upload parsing class, for file upload time, need to use, we look at his method:
Private voidInitmultipartresolver (ApplicationContext context) {Try {
Here to get the BEAN note this constant is defined in the preceding: Multipart_resolver_bean_name = "Multipartresolver";
So when we configure it, the Bean name must be the one above, or it can't be recognized. Oh, look.
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 not configured then the default is no file upload parsing. This time, if the upload, then there will be some problems.

2.LocaleResolver This is localized parsing, that is, to do internationalization, if not set, then the default for us to set a

3.ThemeResolver look at the name also know, is the style and theme resolution class, the default will have for us to set up a

4.HandlerMappings: Request a mapping to the processor if the mapping successfully returns a Handlerexecutionchain object (containing a handler processor (page Controller) object, Multiple Handlerinterceptor interceptors) objects, such as beannameurlhandlermapping the URL and the Bean name Mapping, the map of the successful Bean is the processor here, from the following code can be seen

protectedhandlerexecutionchain gethandler (HttpServletRequest request) throws Exception {
Request a mapping to the processor if the mapping successfully returns a Handlerexecutionchain object (containing a handler processor (page Controller) object, multiple Handlerinterceptor interceptor objects);
If beannameurlhandlermapping the URL with the Bean name Mapping, the map of the successful Bean is the processor here, note that the processor here is worth handler, not handlermapping, the image will
The handlermapping is a template, and the processor handler is the molded product that is carved out of 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) { returnhandler; } } return NULL; }

5.HandlerAdapters: See the adapter, package the various processors into adapters so that you can support multiple types of processors.

Handleradapter ha = Gethandleradapter (Mappedhandler.gethandler ()),//package The processor, and all subsequent operations are done by the adapter

6HandlerExceptionResolvers: A parser, such as when an error occurs, may be unified to a certain page. The default is also implemented, there are too many solutions to the demand, there is nothing to say

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

8ViewResolvers: View parser. A view is typically configured in our configuration, just like this:

        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 is parsing the above. Superclass has only one method

View Resolveviewname (String viewName, locale locale) throws Exception;
9.FlashMapManager Worth is redirect time to save the data of a container equivalent to the map, but the official said in the program is generally not used, such as controller, is often used redirectattributes To transfer data

After finishing several important attributes and then zooming in on the major ones, since it's a servlet, let's take a look at the service method, where the service is:

protected void

There is a code that needs to be paid attention to, and the other code is to configure some attributes or something.

Try {            Dodispatch (request, response);        }

This method is actually the core of Dispatchservlet, and the parser, adapter, and so on we talked about here are all operating here:

protected voidDodispatch (httpservletrequest request, httpservletresponse response) throws Exception {HttpServletRequest Pro Cessedrequest=request;
Handlerexecutionchain Mappedhandler=NULL;//spoken before. Handlermapping mapping succeeds, it will return this thing, including processor and interceptor Boolean multipartrequestparsed=false; Webasyncmanager Asyncmanager=Webasyncutils.getasyncmanager (Request); Try{modelandview mv=NULL; Exception dispatchexception=NULL; Try {
See if the request is multipart (such as file upload) processedrequest=Checkmultipart (Request); Multipartrequestparsed= (Processedrequest! =request); //determine handler for the current request.
        
Map Mappedhandler =gethandler (processedrequest); if(Mappedhandler = =NULL|| Mappedhandler.gethandler () = =NULL) {Nohandlerfound (processedrequest, response); return; }//packaging of 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)) { LongLastModified =ha.getlastmodified (Request, Mappedhandler.gethandler ()); if(logger.isdebugenabled ()) {Logger.debug ("last-modified value for ["+ Getrequesturi (Request) +"] is:"+lastmodified); } if(NewServletwebrequest (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 parse view will eventually call View.render (Mv.getmodelinternal (), request, response) and pass the model in Processdispatchresult (processedreq Uest, Response, Mappedhandler, MV, dispatchexception); }
The following are some of the things that have been compiled later.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 { //used by a multipart request. if(multipartrequestparsed) {Cleanupmultipart (processedrequest); } } } }

The above is also a simple understanding of the SPRINGMVC entrance, the next few days in the study of some SPRINGMVC other functions. A lot of things are self-understanding, do not know right = =.

SPRINGMVC (1)

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.