Spring MVC3 Principle Tutorial and its framework construction example

Source: Internet
Author: User

Original:Spring MVC3 Principle Tutorial and its frame construction example

Http://www.zuidaima.com/share/1816340522191872.htm

First, preface:

Hello everyone, Spring3 mvc is a very good MVC framework, since it was released in the 3.0 release, now there are more and more teams choosing SPRING3 MVC. SPRING3 MVC structure is simple, should that sentence simple is beautiful, and he is strong and flexible, performance is also excellent.

The official download URL is: http://www.springsource.org/download (this article uses the Spring 3.0.5 version)

Struts2 is also an excellent MVC architecture, with many advantages such as good structure. But here is the disadvantage, Struts2 because the use of value stack, OGNL expression, struts2 tag library, etc., will lead to the performance of the application degradation. STRUTS2 multi-layer interceptors, multi-instance action performance are very good.

Advantages of SPRING3 MVC:

1, Spring3 MVC Learning difficulty is less than the struts2,struts2 of unnecessary functions too much. Oh, of course this is not the deciding factor.

2, Spring3 MVC is easy to write a good performance program, Struts2 to be careful to write good performance program (refers to the MVC part)

3, Spring3 MVC flexibility is you can not imagine, Spring's extensibility is legendary, Spring3 MVC certainly will not lag behind, not because of the use of the MVC framework and feel any restrictions.

Second, the core class and interface:

Dispatcherservlet--Front Controller

Handlermapping interface--mapping of processing requests

Implementation classes for the Handlermapping interface:

simpleurlhandlermapping mapping a URL to a controller through a configuration file

defaultannotationhandlermapping maps a URL to a controller class via annotations

Handleradapter interface--mapping of processing requests

The Annotationmethodhandleradapter class, through annotations, maps a URL to the method of the Controller class

Controller interface--controllers

Since we have used the @controller annotation, the class that added the @controller annotation annotation can assume the responsibility of the Controller (Action),

So we don't have to use this interface.

Handlerinterceptor interface--Interceptor

Without graphs, we implement this interface ourselves to complete the work of the Interceptor.

Implementation class for the Viewresolver interface

The Urlbasedviewresolver class passes a configuration file and gives a view name to the

Internalresourceviewresolver class, than the above class, joined the JSTL support

View interface

Jstlview class

Localresolver interface

Handlerexceptionresolver interface--Exception handling

Simplemappingexceptionresolver Implementation Class

Modelandview class

No diagram.

Third, core flowchart

Iv. Description of Dispatcherservlet

With spring MVC, configuring Dispatcherservlet is the first step.

Dispatcherservlet is a servlet, so you can configure multiple dispatcherservlet.

The Dispatcherservlet is the predecessor controller, which is configured in the Web. xml file. Interception of matching requests, servlet intercept matching rules to be self-defined, the interception of requests, according to certain rules distributed to the target controller (we write action) to deal with.

The "so-and-so rule": is different from the implementation class of which handlermapping interface you are using.

Let's take a look at the first example:

<web-app>       <servlet>           <servlet-name>example</servlet-name>           <servlet-class >org.springframework.web.servlet.DispatcherServlet</servlet-class>           <load-on-startup>1</ load-on-startup>       </servlet>      <servlet-mapping>           <servlet-name>example</ servlet-name>          <url-pattern>*.form</url-pattern>       </servlet-mapping>   

<load-on-startup>1</load-on-startup> is the boot sequence that enables the servlet to start with the SERVLETP container.

<url-pattern>*.form</url-pattern> will intercept the *.form end of the request.

<servlet-name>example</servlet-name> This servlet's name is example, and can have multiple dispatcherservlet, which are distinguished by their name. Each dispatcherservlet has its own Webapplicationcontext context object. At the same time save the ServletContext and request object, about key, explained later.

During the initialization of Dispatcherservlet, the framework looks for a configuration file named [Servlet-name]-servlet.xml in the WEB app's Web-inf folder, generating the bean defined in the file.

A second example:

<servlet>  2.     <servlet-name>springMVC</servlet-name>  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  4.     <init-param>  5.         <param-name>contextConfigLocation</param-name>  6.         <param-value>classpath*:/springMVC.xml</param-value>  7.     </init-param>  8.     <load-on-startup>1</load-on-startup>  9. </servlet>  <servlet-mapping>     <servlet-name>springMVC</servlet-name>  .     <url-pattern>/</url-pattern>  

Indicates the file name of the profile, does not use the default profile name, and uses the Springmvc.xml configuration file.

Where <param-value>**.xml</param-value> can use a variety of writing
1, do not write, use the default value:/web-inf/<servlet-name>-servlet.xml
2. <param-value>/WEB-INF/classes/springMVC.xml</param-value>
3. <param-value>classpath*:springMVC-mvc.xml</param-value>
4. Multiple values are separated by commas

servlet intercept matching rules can be self-defined, which URL is appropriate for servlets to intercept?

When mapping to @requestmapping ("/user/add"):
1, interception *.do, such as:/user/add.do, the disadvantage: all the URLs to. Do end. Does not affect access to static files.
2, interception/app/*, such as:/app/user/add, the disadvantage: the URL of the request must contain/app, @RequestMapping ("/user/add") do not need to include/app.
3, interception/, for example:/user/add, disadvantage: The jpg,js,css static file access is also blocked not normal display. There is a solution behind it.
4, intercept/*, you can go to the action, but forwarded to the JSP is intercepted again, can not access to the JSP.

V. Description of the parent context

If you use the listener listener to load the configuration, the listener listener is typically used in struts+spring+hibernate projects. As follows

<listener>       <listener-class>org.springframework.web.context.contextloaderlistener</ Listener-class>    </listener>

Spring creates a global webapplicationcontext context, called the root context , saved in ServletContext, and key is Webapplicationcontext.root_web_ The value of the Application_context_attribute property. You can use the tool class to remove the context: Webapplicationcontextutils.getwebapplicationcontext (ServletContext);

Dispatcherservlet is a servlet that can be configured multiple at the same time, each dispatcherservlet has its own webapplicationcontext context, which inherits the root context All the things in it. Saved in ServletContext, key is the "Org.springframework.web.servlet.FrameworkServlet.CONTEXT" +servlet name. When a request object is generated, the Webapplicationcontext context is saved in the Request object, and key is DispatcherServlet.class.getName () + ". CONTEXT ". You can use the tool class to remove the context: Requestcontextutils.getwebapplicationcontext (Request);

ApplicationContext instances in spring can be limited to different scopes (scopes).
In the Web MVC framework, each dispatcherservlet has its own webapplicationcontext, which inherits all the bean definitions of the root webapplicationcontext.
These inherited beans can also be overridden in each Serlvet's own domain (override), and the overwritten bean can be set on only the properties that are used by the servlet instance itself.

Summary: Instead of using the listener listener to load the spring configuration, use Dispatcherservlet to load the spring configuration, not the parent context, just a dispatcherservlet, it's simple, and nothing's bothering you.

vi. springmvc-mvc.xml configuration file Snippet (not using default profile name)

<!--automatically scanned package name--<context:component-scan base-package= "COM.APP,COM.CORE,JUNIT4" ></context: component-scan> <!--default annotation mappings Support--<mvc:annotation-driven/> <!--view Interpreting classes--&G     T <bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name= "prefix"      Value= "/web-inf/jsp/"/> <property name= "suffix" value= ". JSP"/><!--can be empty, easy to implement their own based on the extension to select the View Interpretation class logic-- <property name= "Viewclass" value= "Org.springframework.web.servlet.view.JstlView"/> </bean> &l t;! --Interceptors-<mvc:interceptors> <bean class= "Com.core.mvc.MyInteceptor"/> &LT;/MVC:INTERCEPTORS&G              T <!--access to a static resource file (optional)--<mvc:default-servlet-handler/> <!--access to a static resource file two (two)-- > <mvc:resources mapping= "/images/**" location= "/images/" cache-period= "31556926"/> <mvc:resources mapping= "/js/**" location= "/js/" cache-period= "31556926"/> <mvc:resources mapping= "/css/**" location= "/css/" cache-period= "   31556926 "/>

<context:component-scan/> scans the annotations on the classes in the specified package, and the commonly used annotations are:

@Controller declaring the Action component
@Service declaring the Service component @Service ("Mymovielister")
@Repository declaring DAO Components
@Component refer to components when they are not well categorized.
@RequestMapping ("/menu") Request mapping
@Resource for injection, (provided by the Java EE) by default assembly by name, @Resource (name= "Beanname")
@Autowired for Injection, (Srping provided) by default assembly by type
@Transactional (Rollbackfor={exception.class}) transaction Management
@ResponseBody
@Scope ("prototype") to set the scope of the bean

<mvc:annotation-driven/> is a shorthand form that can be manually configured instead of this shorthand form, which allows beginners to quickly apply the default configuration scheme. <mvc:annotation-driven/> will automatically register defaultannotationhandlermapping and annotationmethodhandleradapter two beans, is required by spring MVC to distribute the request to @controllers.
and provides: Data binding support, @NumberFormatannotation support, @DateTimeFormat support, @Valid support, read/write XML support (JAXB), read/write JSON support (Jackson).
Later, we used the JSON support when we processed the response to the AJAX request.
Later, when you write JUnit unit tests on an action, you take defaultannotationhandlermapping and annotationmethodhandleradapter two beans from the spring IOC container, To complete the test, take the time to know is <mvc:annotation-driven/> This sentence registered in these two beans.

<mvc:interceptors/> is a shorthand form. By looking at the big picture above, we know that we can configure multiple handlermapping. <mvc:interceptors/> will inject an interceptor for every handlermapping. In fact, we can also manually configure each handlermapping to inject an interceptor.

<mvc:default-servlet-handler/> uses the default servlet to respond to static files.

<mvc:resources mapping= "/images/**" location= "/images/" cache-period= "31556926"/> match url/images/** URLs as static resources , which is read out in memory by spring and then in response to HTTP.

Vii. How to access static files, such as Jpg,js,css?

How your dispatcherservlet intercepts URLs such as *.do, there is no problem accessing static resources. If your dispatcherservlet intercepts "/", all requests are intercepted, and access to *.js,*.jpg is intercepted.

Purpose: Normal access to static files, do not find static file 404.

Scenario One: Activate Tomcat's defaultservlet to handle static files

<servlet-mapping>        <servlet-name>default</servlet-name>       <url-pattern>*.jpg</ url-pattern>      </servlet-mapping>     <servlet-mapping>            <servlet-name>default</ servlet-name>        <url-pattern>*.js</url-pattern>     </servlet-mapping>     < servlet-mapping>             <servlet-name>default</servlet-name>           <url-pattern>*.css</ Url-pattern>       </servlet-mapping>     To configure multiple, each file is configured with a    

To write in front of the Dispatcherservlet, let Defaultservlet first intercept, this will not enter spring, I think the performance is the best bar.

Tomcat, Jetty, JBoss, and GlassFish the default servlet name-"Default"
Google App Engine Default servlet name-"_ah_default"
Resin default servlet name-"Resin-file"
WebLogic default servlet name-"Fileservlet"
The name of the WebSphere default servlet-"Simplefileservlet"
Scenario two: After the spring3.0.4 version provided the Mvc:resources
How to use Mvc:resources:

<!--access to static resource files--    

The/images/** maps to Resourcehttprequesthandler for processing, and location specifies the position of the static resource. Can be a Web application root directory, inside the jar package, so that the static resources can be compressed into the jar package. Cache-period allows static resources to be Web cache

If the following error occurs, there may be a reason for not configuring <mvc:annotation-driven/>.
Error warning:no mapping found for HTTP request with URI [/mvc/user/finduser/lisi/770] in Dispatcherservlet with Name ' Spring MVC '

Using the <mvc:resources/> element, register the URI of the mapping in the UrlMap of Simpleurlhandlermapping,
Key is the URI pattern value of mapping, and value is Resourcehttprequesthandler,
In this way, the access to static resources is cleverly transferred from handlermapping to Resourcehttprequesthandler processing and returned, so it supports the Classpath directory and the access of static resources within the JAR package.
It is also important to note that you should not set DefaultHandler for simpleurlhandlermapping. Because the DefaultHandler to the static URI is Resourcehttprequesthandler,
Otherwise, the static resources request cannot be processed.

Scenario three, using <mvc:default-servlet-handler/>

<mvc:default-servlet-handler/>

The "/**" URL will be registered to the Simpleurlhandlermapping UrlMap, and the access to the static resource is transferred from handlermapping to Org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler processed and returned.
Defaultservlethttprequesthandler use is the default servlet for each servlet container.

Additional note: The order of execution of multiple handlermapping issues:

The Defaultannotationhandlermapping Order property value is: 0

<mvc:resources/> Auto-registered Simpleurlhandlermapping's Order property value is: 2147483646

The value of the Order property for the <mvc:default-servlet-handler/> autoenrollment simpleurlhandlermapping is: 2147483647

Spring executes a smaller order value first. When access to a a.jpg picture file, first through the defaultannotationhandlermapping to find the processor, must not be found, we do not call a.jpg action. And then the order value in ascending, because the last simpleurlhandlermapping is a match "/**", so will definitely match, and then respond to the picture.

Access to a picture, but also to go layer-by-layer matching. I don't know how it's performing. Another day to do a stress test, compared to Apache.

Finally, how do you dispatcherservlet intercept *.do such a URL, do not save the above problem.

How do I request a method that maps to a specific action?
Scenario One: Based on XML configuration mappings, you can use simpleurlhandlermapping, beannameurlhandlermapping for URL mapping and interception requests.
Configure the method slightly.
Scenario two: Based on annotation mappings, you can use defaultannotationhandlermapping.

<bean class= "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" >  </ Bean>  

But before we configured the <mvc:annotation-driven/>, he would automatically register the bean, and it would not be necessary for us to display the registered bean.
The above can be injected into the interceptors, to achieve the rights control and other pre-work.
We use the 2nd type, based on annotations, to use spring MVC

and use it on the action class:
@Controller
@RequestMapping ("/user")

Ix. Interceptors in spring:
Spring provides us with:
Org.springframework.web.servlet.HandlerInterceptor interface,

Org.springframework.web.servlet.handler.HandlerInterceptorAdapter Adapter,
Implement this interface or inherit this class, it is very convenient to implement their own interceptors.

There are three ways to do this:

Action before executing:
public boolean prehandle (HttpServletRequest request,
HttpServletResponse response, Object handler);

Execute before generating view
public void Posthandle (HttpServletRequest request,
HttpServletResponse response, Object handler,
Modelandview Modelandview);

Last execution, can be used to release resources
public void Aftercompletion (HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)


preprocessing, post processing (call service and return Modelandview, but no page rendering), return processing (page already rendered)
In the Prehandle, the coding, security control and so on can be processed;
In Posthandle, there is an opportunity to modify the Modelandview;
In aftercompletion, logging is possible based on whether an ex is null to determine if an exception has occurred.
The object handler in the parameter is the next interceptor.

X. How to use interceptors?
To customize an interceptor to implement the Handlerinterceptor interface:

public class Myinteceptor implements Handlerinterceptor {          slightly ...    }

Spring MVC does not have a total interceptor and cannot intercept all requests.
Spring MVC interceptors, which belong to the handlermapping level, can have multiple handlermapping, each handlermapping can have its own interceptor.
When a request by the order value from small to large, sequential execution of the implementation of the Handlermapping interface class, which first has returned, then it can be finished, the back of the handlermapping will not go, the process is completed. It goes to the next operation.
When will the interceptor be executed? When a request is given to a handlermapping, the handlermapping first finds the processor to handle the request, how to find it, executes the interceptor, and after the interception is done, it is handed to the target processor.
If the processor is not found, then the interceptor will not be executed.


There are three ways to configure the spring MVC configuration file:
Scenario one, (approximate) total Interceptor, block all URLs

<mvc:interceptors>       <bean class= "Com.app.mvc.MyInteceptor"/>   

Why is it called "approximate" and the front says that spring does not have a total interceptor.

<mvc:interceptors/> will inject an interceptor for every handlermapping. There is always a handlermapping that can find the processor, and only a single processor is found, so this interceptor will always be executed. Play the role of the total interceptor.

Scenario two, (approximate) The total interceptor, intercepts the matching URL.

<mvc:interceptors >       <mvc:interceptor>             <mvc:mapping path= "/user/*"/> <!--/user/*  --             <bean class= "Com.mvc.MyInteceptor" ></bean>         </mvc:interceptor>     </MVC: Interceptors>  

is one more URL match than the scheme.

Scenario three, interceptors on the Handlermappint

<bean class= "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" >         < Property name= "Interceptors" >             <list>                <bean class= "Com.mvc.MyInteceptor" ></bean>            </list>         </property>        

If <mvc:annotation-driven/> is used, it automatically registers defaultannotationhandlermapping with Annotationmethodhandleradapter These two beans, so there is no chance to inject it with the interceptors attribute, you cannot specify an interceptor.

Of course we can manually configure the above two beans, do not use <mvc:annotation-driven/>, you can inject the interceptors attribute interceptor.

In fact, I also do not recommend the use of <mvc:annotation-driven/>, while it is recommended to manually write the configuration file to replace the <mvc:annotation-driven/>, which is strong control.

Xi. How to implement the global exception handling?

In the spring MVC configuration file:

<!--total error handling-   <bean id= "Exceptionresolver" class= " Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver ">       <property name=" Defaulterrorview ">             <value>/error/error</value>       </property>       <property name=" Defaultstatuscode ">             <value>500</value>       </property>      <property name=" Warnlogcategory ">             <value>org.springframework.web.servlet.handler.simplemappingexceptionresolver </value>       </property>      </bean>

The main class here is the Simplemappingexceptionresolver class, and his parent class Abstracthandlerexceptionresolver class.

What properties can be configured, I know by looking at the source code.

You can also implement the Handlerexceptionresolver interface and write an exception handler of your own. The extensibility of spring is very good.

With Simplemappingexceptionresolver we can map different exceptions to different JSP pages (through the configuration of the Exceptionmappings property).

We can also specify a default exception prompt page for all exceptions (through the configuration of the Defaulterrorview property), and spring will display exception information with this default configuration if the thrown exception does not have a corresponding mapping in exceptionmappings.

Note that the exception display interface that is configured here includes only the main file name, and the file path and suffix are already specified in Viewresolver. As/error/error represents/error/error.jsp

Display the wrong JSP page:

<%@ page language= "java" contenttype= "text/html; CHARSET=GBK "      pageencoding=" GBK "%>   <%@ page import=" java.lang.Exception "%>   <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >   

One sentence: Request.getattribute ("Exception"), key is exception, is also specified by default in the Simplemappingexceptionresolver class, it is possible to modify this value through the configuration file, We can go to see the source code.

Original address: http://www.blogjava.net/wangxinsh55/archive/2012/11/22/391728.html

Welcome to the reading of Ah!

Spring MVC3 Principle Tutorial and its framework construction example

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.