Spring MVC Basics

Source: Internet
Author: User

Spring MVC Foundation 1. WEB MVC Basics

The essence of MVC is the presentation layer pattern, where we take the view model as the center and separate the view from the controller. Just like in layered mode, we take the business logic as the center, separating the presentation layer from the data Access layer code is the same way. The framework can only help us on a technical level and cannot help us in our thinking and process, and many of us do not like to think and try.

2. The basics of implementing Web MVC

The implementation of the Web MVC Foundation can be summarized as 1 front-segment controllers and 2 mappings.

(1) Front Controller Frontcontroller

Asp. NET and JSP are all in the page path and URL one by one, WEB MVC to map the controller and view through the URL, you need a front-end controller to receive and resolve requests uniformly, and then based on the URL to distribute the request to the controller. Because ASP. NET and Java are at the core of IHttpHandler and servlet respectively, ASP. NET MVC and Spring MVC uses Mvchandler and Dispatcherservlet, respectively, that implement the corresponding interface as the front-section controller.

Asp. NET handles URL mappings through HttpModule's implementation class, urlroutingmodule forwards requests to the front controller mvchandler based on the URL. In Spring MVC, the request is forwarded directly to the front-end controller Dispatcherservlet, based on the configuration of the URL.

(2) Mapping of URLs and Contrller

ASP. NET MVC stores the mapping rules for URLs and controllers in RouteCollection, and the front-end controller Mvchandler to find the controller through the IController interface. Spring MVC uses requestmapping and controller annotations to identify mapping rules without the need to implement control of the I through interface dependencies.

(3) Map of URL and view

ASP. NET MVC defaults through Razorviewengine to find the view based on the URL and view name, and the core interface is iviewengine. Spring MVC uses Internalresourceviewresolver to find views based on URL and view names, and the core interface is viewresolver.

3.Spring MVC get started quickly

(1) Spring MVC initialization

The ASP. NET MVC initialization requires that we register the default URL and controller rules in the Httpapplication.application_start method, because Spring MVC uses the annotation map URL and controller, Therefore, there is no corresponding step. Asp. NET is configured in root Web. config UrlRoutingModule to forward requests to mvchandler,spring MVC we need to configure Dispatcherservlet and their corresponding URLs to achieve the purpose of taking over all requests, Spring has used the servletcontainerinitializer mechanism defined by Servlet3.0 to provide us with the default Abstractannotationconfigdispatcherservletinitializer, just like Inherit HttpApplication's mvcapplication like, write a mywebapplicationinitializer.

(2) Map of URL and view

Asp. NET Razorviewengine has a built-in view of the path and extension. cshtml rules. Spring MVC Internalresourceviewresolver does not provide a default value, so if we do not define path and extension, we only need mywebapplicationinitializer. In general, we will specify that view be placed in a unified view directory with a specific extension. Spring also provides delegatingwebmvcconfiguration, we just have to write one of their own appconfig inherit it, 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<?>[] Getrootconfigcla    SSEs () {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) Mapping of URLs and controllers

As mentioned above, unlike spring MVC and ASP. NET MVC, the controller is not identified through the IController interface, nor is the URL and controller defined by RouteCollection. Instead, there are two annotations: Controller and requestmapping. We simply define a Pojo Mycontroller and its simple home method. and apply the above annotations:

Package S4s;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.RequestMapping, @Controllerpublic class Mycontroller {    @RequestMapping ("/")    Public String Home () {        return "home";    }}

The simplest example is completed by adding the/web-inf/views/home.jsp view file. No configuration of Web. XML is required.

(4) using model

Asp. NET compiles the view to Webviewpage<object>,view and the model is one by one corresponding and the type matches, the model can be arbitrary poco. The view and model in Spring MVC are one-to-many, providing modelmap and its subclasses Modelandview provide functionality similar to Viewresult in ASP. The base class of Modelmap is Linkedhashmap<string, object>.

We modify the code of Mycontroller, using Modelandview to pass a simple Usermodel model, as the Usermodel object of the parameter, as in ASP. NET MVC, the request parameters are automatically mapped to the model's properties. The return value Modelandview is similar to ASP. NET MVC's return View (Viewname,model). Just because the spring MVC model is a list of multiple models, we also need to specify the name of the return 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, add jstl and spring tag support. Because of the difference between view and ASP. NET MVC in spring MVC, there is no way to specify the model type that the view holds without the advantage of smart hints and error detection, and everything goes back to the scripting language era.

<%@ 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>

Attached Pom.xml. Where JUnit is optional, JSTL is required to be introduced with the JSTL syntax in view.

View Code

Spring MVC Basics

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.