Spring Mvc execution principle and xml annotation configuration (6)

Source: Internet
Author: User

Spring Mvc execution principle and xml annotation configuration (6)
Spring MVC execution principle in Spring Mvc access process, each request first goes through many filters and is processed by DispatcherServlet; in a Spring MVC project, multiple dispatcherservlets can be configured, each DispatcherServlet can correspond to multiple HandlerMapping, and each HandlerMapping can have its own Interceptor (Interceptor ). 1. the request is first captured by the front-end DispatcherServlet; 2. after HandlerMapping, DispatcherServlet obtains the appropriate Hanlder, that is, Controller, and returns it to DispatcherServlet; 3. if an interceptor is set, the preHandler method of the interceptor is preferred, and the execution result is returned to DispatcherServlet; 4. based on the captured request and Handler (Controller), DispatcherServlet obtains the appropriate HandlerAdapter for processing and returns the result to DispatcherServlet. The result is (View and Model. if an interceptor is set, it is to execute the postHandler method of the interceptor and return DispatcherServlet; 6. dispatcherServlet The obtained view and model are combined with ViewResolver to return the specified view template and return it to DispatcherServlet; 7. dispatcherServlet, in combination with the view model and model, executes the render () Rendering interface and returns it to the client. A DispatcherServlet has its own context configuration file, which inherits from the root context configuration file; each DispatcherServlet can be configured with multiple different HandlerMapping ing methods. Each HandlerMapping implements the Ordered interface. You can set the preferred HandlerMapping in the context file configuration. After your request is captured by DispatcherServlet, dispatcherServlet uses HandlerMapping with a higher priority to find available Handler. If no suitable Handl is found Er, so that the HandlerMapping with the second priority continues to be searched until it is found. For example, Spring MVC provides the main HanderMapping including DefaultAnnotationHandlerMapping, SimpleUrlHandlerMapping, beanNameUrlHandlerMapping copy Code <bean id = "defaultAnnoHandlerMapping" class = "org. springframework. web. servlet. mvc. annotation. defaultAnnotationHandlerMapping "> <property name =" order "value =" 1 "/> </bean> <bean id =" simpleUrlMapping "class =" org. springframework. web. servlet. ha Ndler. SimpleUrlHandlerMapping "> <property name =" order "value =" 2 "/> <! --... --> </Bean> <bean id = "beanNameUrlMapping" class = "org. springframework. Web. servlet. handler. BeanNameUrlHandlerMapping"> <! --... --> </Bean> if order is not explicitly specified for HandlerMapping, the default value is Integer. MAX_VALUE, which corresponds to the lowest priority. If DefaultAnnotationHandlerMapping finds the corresponding Handler, it will pass the data to the corresponding HandlerAdapter (method) under the corresponding Controller class for processing; if not, it will be processed by SimpleUrlHandlerMapping; spring MVC xml configuration description 1. web. xml configuration 1>. first, the Spring listener: <! -- Creates the Spring Container shared by all Servlets and Filters --> <listener-class> org. springframework. web. context. contextLoaderListener </listener-class> </listener> is the portal of the entire spring framework. The configuration file of the root Context of the application is automatically loaded because it implements the interface ServletContextListener, when the project is started, the implementation method is executed. 2>. Root application context configuration: <! -- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name> contextConfigLocation </param-name> <param-value>/WEB-INF /spring/root-context.xml </param-value> </context-param> can also be called spring global configuration, here, you can configure the data source and other basic global spring configurations. dispatcherServlet can inherit the configurations from here. 3>. diapatcherServlet configuration: copy the Code <! -- Processes application requests --> <servlet-name> appServlet </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </servlet-class> <init-param> <param-name> contextConfigLocation </param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml </param -value> </init-param> <load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-name> appS Ervlet </servlet-name> <url-pattern> *. do </url-pattern> </servlet-mapping> the copy code load-on-startup value is "1", indicating that the servlet (dispatcherServlet is also a servlet) is started with the servlet container at the same time. The init-param node of dispatcherservlet is not required. If no configuration is available, the context configuration file corresponding to the dispatcherServlet goes to the/WEB-INF/[servlet-name]-servlet. xml loading; servlet-mapping url-pattern value "*. do "indicates that servlet will only intercept. do suffix requests. This configuration does not affect access to static resources. 4>. configure project code: copy the Code <filter> <filter-name> CharacterEncodingFilter </filter-name> <filter-class> org. springframework. web. filter. characterEncodingFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init- param> <init-param> <param-name> forceEncoding </param-name> <param-value> true </param-value> </init-param> </filter> <filter-mapping> <filter-name> Charac TerEncodingFilter </filter-name> <url-pattern>/* </url-pattern> </filter-mapping> copy the Code. If the filter is not configured, request access may encounter garbled; ------------------------------------------------------------- now configure diapatcherServlet corresponding context configuration file:/WEB-INF/spring/appServlet/servlet-context.xml (configured above) 1>. start scanning all Controller <context: component-scan base-package = "com. study. web "/> mainly acts on @ Controller. If its package structure is like this: com. study. web | --- controller | --- -- | ----- AbcController. java | ----- cdeController. java writes the base-package above to com. study. web. the controller is also correct; 2>. <mvc: annotation-driven/> Note: it is a short form that allows beginners to quickly apply the default configuration scheme. The Bean ultannotationhandlemapping and AnnotionMethodHandleAdapter beans are registered by default, the two beans correspond to the class level and the latter to the method level. The above DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter are necessary for Spring to distribute requests to @ Controller. Annotation-driven scans the annotation on the class in the specified package. Common annotations include: copy the code @ Controller to declare the Action component @ Service to declare the Service component @ Service ("myMovieLister ") @ Repository declare Dao Component @ Component refers to a Component. @ RequestMapping ("/menu") Request ing @ Resource is used for injection, (which is provided by j2ee) is assembled by name by default, and @ Resource (name = "beanName") @ Autowired is used for injection, by default, @ Transactional (rollbackFor = {Exception. class}) Transaction Management @ ResponseBody @ Scope ("prototype") sets bean Scope to copy code 3>. view resolution class, which parses the Model View name. Add the prefix suffix <beans: bean class = "org. springframework. web. servlet. view. internalResourceViewResolver "> <beans: property name =" prefix "value ="/WEB-INF/views/"/> <beans: property name =" suffix "value = ". jsp "/> </beans: bean> InternalResourceViewResolver provides support for JstlView: <property name =" viewClass "value =" org. springframework. web. servlet. view. jstlView "/> in versions earlier than Spring Mvc 2.5, the annotation function is provided to fully support REST. REST Access system resources through URLs without extensions; REST treats each requested resource as static, and each URL resource is a static resource; it provides access ing through the @ RequestMapping main @ PathVariable annotation. The value and method in @ RequestMapping can support restful access. Through the policy interface, the Spring framework is highly configurable and contains multiple view technologies, such as assumerver Pages (JSP), Velocity, Tiles, iText, and POI. The Spring MVC Framework does not know the view used, so it does not force you to only use JSP technology. Spring MVC separates the roles of controllers, model objects, schedulers, and processing program objects, making them easier to customize. For example, if Velocity technology is used, you only need to change the value of suffix ". vm "; 4>. spring Interceptor: global configuration: <mvc: interceptors> <bean class = "com. study. web. interceptor. myInterceptor "> </bean> </mvc: interceptors> path-Based interceptor: copy the Code <mvc: interceptors> <mvc: interceptor> <mvc: mapping path = "/**/*. do "/> <beans: bean class =" com. study. interceptor. utils. stuInterceptor "> <beans: property name =" startWrk "> <beans: value> 1 </beans: value> </beans: propert Y> <beans: property name = "endWrk"> <beans: value> 24 </beans: value> </beans: property> <beans: property name = "redirectUrl"> <beans: value> http: // 127.0.0.1: 8080/interceptor/static/timeout.htm </beans: value> </beans: property> </beans: bean> </mvc: interceptor> </mvc: interceptors> copy code-related Java classes: stuInterceptor (this class is used to intercept outside the specified time range, then the page request is forwarded to/interceptor/static/timeout.htm) to copy the code package com. study. interceptor. utils; Import java. util. calendar; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springframework. web. servlet. handlerInterceptor; import org. springframework. web. servlet. modelAndView; // import org. springframework. web. servlet. handler. handlerInterceptorAdapter; import com. study. interceptor. controlle R. homeController; public class StuInterceptor implements HandlerInterceptor/* extends HandlerInterceptorAdapter */{private static final Logger logger = LoggerFactory. getLogger (HomeController. class); private int startWrk; private int endWrk; private String redirectUrl; @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {lo Gger.info ("Interceptor", "I am in Custom Interceptor! "); Calendar cal = Calendar. getInstance (); int hour = cal. get (Calendar. HOUR_OF_DAY); if (hour> startWrk & hour <endWrk) {return true;} else {response. sendRedirect (redirectUrl); return false ;}} public int getStartWrk () {return this. startWrk;} public void setStartWrk (int startWrk) {this. startWrk = startWrk;} public int getEndWrk () {return this. endWrk;} public void setEndWrk (int endWrk) {This. endWrk = endWrk;} public String getRedirectUrl () {return this. redirectUrl;} public void setRedirectUrl (String redirectUrl) {this. redirectUrl = redirectUrl;} @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {// TODO Auto-generated method stub System. out. println ("after posthandler ");} @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// TODO Auto-generated method stub System. out. println ("after completion") ;}} copy Code 5>. configure the interceptor in HandlerMapping: copy the Code <! -- Mapping --> <bean id = "urlMapping" class = "org. springframework. web. servlet. handler. simpleUrlHandlerMapping "> <property name =" mappings "> <props> <prop key ="/abc. do "> abcController </prop> <prop key =" def. kara "> defController </prop> </props> </property> <! -- Register interceptor --> <property name = "interceptors"> <list> <ref bean = "myInterceptor"> </ref> </list> </property> </bean> copy the code and copy the Code <bean class = "org. springframework. web. servlet. mvc. annotation. defaultAnnotationHandlerMapping "> <property name =" interceptors "> <list> <bean class =" com. study. web. myInteceptor "> </bean> </list> </property> </bean> copy Code 6>. use placeHolder to load the application property profile <context: property-placeholder location = "/WEB-INF/config. properties "/> for example, loading mysql jdbc configuration information: driver = com. mysql. jdbc. driverurl = jdbc: mysql: // localhost: 3306/springdbusername = rootpassword = 123 then the driver information configured for the mysql data source can be configured as follows: copy the Code <context: property-placeholder location = "classpath: META-INF/mybatis/mysql. properties "/> <bean id =" dataSource "class =" org. springframework. jdbc. datasource. driverManagerDataSource "> <property name =" driverClassName "value =" $ {driver} "> </property> <property name =" url "value =" $ {url} "> </property> <property name = "username" value = "$ {username}"> </property> <property name = "password" value = "$ {password}"> </property> </bean>

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.