Java Web series: Spring MVC basics,

Source: Internet
Author: User

Java Web series: Spring MVC basics,
1. Web MVC Basics

The essence of MVC is the presentation layer model. We take the view model as the center and separate the view and controller. Just like the layered mode, we take the business logic as the center and separate the presentation layer and data access layer code. The framework can only help us at the technical level and cannot help us in thinking and process. Many of us do not like to think and try.

2. Basic Web MVC implementation

The implementation of Web MVC can be summarized as one front-end controller and two mappings.

(1) Front-end controller FrontController

ASP. both NET and JSP correspond one-to-one with the Page path and URL. to map the Controller and View through URL, a front-end Controller must receive and parse requests in a unified manner, then, the request is distributed to the Controller Based on the URL. Because ASP. NET and Java use IHttpHandler and Servlet as the core, ASP. net mvc and Spring MVC use MvcHandler and DispatcherServlet that implement the corresponding interfaces as the front-end controllers respectively.

In ASP. NET, the implementation class of HttpModule processes URL ing. The UrlRoutingModule forwards the request to the front-end controller MvcHandler Based on the URL. In Spring MVC, the request is directly forwarded to the front-end controller DispatcherServlet Based on the URL configuration.

(2) ing between URL and Contrller

ASP. net mvc stores URL and Controller ing rules in RouteCollection. The front-end Controller MvcHandler searches for controllers through the IController interface. Spring MVC uses the RequestMapping and Controller annotation to identify the ing rules, and does not need to use interface dependencies to control the I server.

(3) URL ing between URL and View

ASP. net mvc searches for a view based on the URL and view name through RazorViewEngine by default. The core interface is IViewEngine. Spring MVC uses internalResourceViewResolver to search for a view based on the URL and view name. The core interface is ViewResolver.

3. Spring MVC Quick Start

(1) Spring MVC Initialization

For ASP. net mvc initialization, We need to register the default URL and Controller Rules in the HttpApplication. Application_Start method. Spring MVC does not follow the corresponding steps because it uses annotation ing URL and Controller. ASP. NET in the root web. the UrlRoutingModule configured in config can forward requests to MvcHandler. In Spring MVC, We need to configure DispatcherServlet and its corresponding URL to take over all requests, spring has used the Servlet3.0 inerinitializer mechanism defined by Servlet3.0 to provide us with the default AbstractAnnotationConfigDispatcherServletInitializer. Just write a MyWebApplicationInitializer Like inheriting the MvcApplication of HttpApplication.

(2) URL ing between URL and View

The RazorViewEngine of ASP. NET has built-in View Path and. cshtml extension rules. The internalResourceViewResolver of Spring MVC does not provide the default value. Therefore, if we do not define the Path and extension, we only need MyWebApplicationInitializer. Generally, we place the View in a unified View directory with a specific extension. Spring also provides DelegatingWebMvcConfiguration. We only need to write an AppConfig to inherit it and rewrite the configureViewResolvers method. The complete code is as follows:

package s4s;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration;import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;import org.springframework.web.servlet.view.InternalResourceViewResolver;public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {    @Override    protected Class<?>[] getRootConfigClasses() {        return new Class[] { AppConfig.class };    }    @Override    protected Class<?>[] getServletConfigClasses() {        return new Class[] { AppConfig.class };    }    @Override    protected String[] getServletMappings() {        return new String[] { "/" };    }}@Configuration@ComponentScanclass AppConfig extends DelegatingWebMvcConfiguration {    @Override    protected void configureViewResolvers(ViewResolverRegistry registry) {        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();        viewResolver.setPrefix("/WEB-INF/views/");        viewResolver.setSuffix(".jsp");        registry.viewResolver(viewResolver);    }}

(3) ing between URL and Controller

As mentioned above, Spring MVC and ASP. net mvc are different. They do not use the IController interface to identify the Controller, nor use RouteCollection to define the URL and Controller. Instead, they use two Annotations: Controller and RequestMapping. We simply define a POJO MyController and its simple Home method. And the above annotation is applied:

package s4s;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class MyController {    @RequestMapping("/")    public String Home() {        return "home";    }}

Add the/WEB-INF/views/home. jsp View File to complete the simplest example. No web. xml configuration is required.

(4) use Model

ASP. NET finally compiles the View into WebViewPage <object>. The View and Model correspond one to one and match the type. The Model can be any POCO. In Spring MVC, View and Model are one-to-many. ModelMap and its subclass ModelAndView provide functions similar to ViewResult in ASP. net mvc. The base class of ModelMap is LinkedHashMap <String, Object>.

We modify the code of MyController and use ModelAndView to pass a simple UserModel model. The UserModel object model as the parameter is the same as that in ASP. net mvc, the request parameters are automatically mapped to the attributes of the model. The returned value ModelAndView is similar to the return View (viewName, model) of ASP. net mvc. However, because the Spring MVC model is a list of multiple models, we also need to specify the Name of the returned model.

package s4s;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class MyController {    @RequestMapping("/")    public ModelAndView Home(@ModelAttribute UserModel model) {        model.setUserName(model.getUserName() + "~");        return new ModelAndView("home", "model", model);    }}class UserModel {    String userName = "";    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }}

(5) use View

Modify home. jsp and Add tag support for jstl and spring. The View and ASP. net mvc has a big difference. There is no way to specify the Model type held by the View, so there is no advantage of smart prompts and error detection. Everything has returned to the era of scripting.

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE HTML>

Attach pom. xml. Junit is optional, and jstl needs to be introduced in View using jstl syntax.

<Project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion> 4.0.0 </modelVersion> <groupId> me. test </groupId> <artifactId> s4s </artifactId> <packaging> war </packaging> <version> 0.0.1-SNAPSHOT </version> <name> s4s Maven Webapp </name> <url> http://maven.apache.org </url> <dependencies> <dependency> <groupId> junit </groupId> <artifactId> junit </artifactId> <version> 3.8.1 </version> <scope> test </scope> </dependency> <groupId> javax. servlet </groupId> <artifactId> javax. servlet-api </artifactId> <version> 3.1.0 </version> </dependency> <groupId> org. springframework </groupId> <artifactId> spring-webmvc </artifactId> <version> 4.2.4.RELEASE </version> </dependency> <groupId> javax. servlet </groupId> <artifactId> jstl </artifactId> <version> 1.2 </version> </dependency> </dependencies> <build> <finalName> s4s </finalName> <plugins> <plugin> <groupId> org. apache. maven. plugins </groupId> <artifactId> maven-compiler-plugin </artifactId> <version> 3.3 </version> <configuration> <source> 1.8 </source> <target> 1.8 </target> </configuration> </plugin> </plugins> </build> </project>View Code4.Spring MVC initialization Mechanism

(1) Application initialization:

Spring implements the javax. Servlet. ServletContainerInitializer interface defined in servlet 3.0 and uses the javax. servlet. annotation. HandlesTypes annotation to reference the WebApplicationInitializer interface. Therefore, when the Servlet container is initialized, The onStartup method of the WebApplicationInitializer implementation class under the current class path is automatically executed (this is similar to ASP. NET Application_Start works similarly, as mentioned in the Java Web Basics of the series ).

(2) Dependency injection initialization:

In ASP. NET, We initialize the dependency injection container in Application_Start. In Spring MVC, we can implement the WebApplicationInitializer interface to execute dependency injection initialization. In the Web environment, the implementation class of the ApplicationContext interface we use is the annotation-based AnnotationConfigWebApplicationContext (mentioned in the Spring dependency injection basics in the series ), however, we do not need to directly implement WebApplicationInitializer and manually initialize the AnnotationConfigWebApplicationContext object, because Spring has defined AbstractAnnotationConfigDispatcherServletInitializer as the implementation class of the WebApplicationInitializer interface and has included annotationconfigwebappl.

(3) Dependency injection Configuration:

When Annotation-based annotations are used, you can use @ Configurateion to specify POJO to replace web. xml to configure dependency injection. Similarly, @ ComponentScan can replace the scan configuration function in web. xml. With ComponentScan and Configurateion, you can configure 0xml. The Contrller-related annotations mentioned above are all scanning takes effect only after ComponentScan is enabled.

(4) DispatcherServlet initialization:

The AbstractAnnotationConfigDispatcherServletInitializer class's parent class AbstractDispatcherServletInitializer already contains DispatcherServlet initialization. The related class diagram is as follows:

5. Action Filter of Spring MVC

. Net mvc provides many Filter interfaces and an ActionFilterAttribute abstract class as the basis for Filter. The AuthorizeAttribute interceptor that implements the IAuthorizationFilter interface is most well known. Spring MVC provides many interfaces, abstract classes, and implementation classes based on the HandlerInterceptor interface. It also has the permission verification UserRoleAuthorizationInterceptor interceptor similar to. net mvc. The built-in interceptor can meet most of the requirements. It is painted on the image for convenience. The above is Spring MVC, and the following is. net mvc.

The model verification and permission verification sections will be continued later.

Summary

(1) The main points of MVC implementation are frontend Controller, URL and Controller ing, URL and View ing.

(2) MvcHandler and DispatcherServlet

(3) ServletContainerInitializer and HttpApplication. Application_Start

(4) RazorViewEngine and internalResourceViewResolver

(5) IMvcFilter and HandlerInterceptor

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.