Spring MVC is new – starting from scratch

Source: Internet
Author: User

Introduction to Spring MVC

Spring MVC is a lightweight web framework based on the MVC architecture pattern that is designed to modularize web development and decouple the overall architecture.

Spring MVC has some advantages:

As part of the spring framework, it has the advantages of spring (IOC,AOP, etc.)

Supports flexible URL-to-page-controller mapping

Provides flexible data validation, formatting, and data-binding mechanisms

Support RESTful style

Spring MVC Request Process

The overall request flow for the Spring MVC framework is as follows:

Several functional components of spring MVC are involved:

Front-end controller (dispatcherservlet): Receives a user request and returns the result of the request. It acts as a transponder or central processing unit, controls the entire execution process, and reduces the coupling between components that are progressively scheduled.

Processor Mapper (handlermapping): Based on the URL requested by the user, through annotations or XML configuration, to find the appropriate processor handler

processor Adaptation (Handleradapter): Complete the method in the calling processor based on the handler found by the Mapper

Processor (Handler): Request processing of specific logic, return data and view information

view Resolver: Resolves a specific view that resolves a logical view name into a real view by Modelandview The view information in the object

Detailed steps in the request process:

1: The user initiates the request and the request is intercepted by the front-end controller (dispatcherservlet)

2: Front Controller (dispatcherservlet) Request Processor Mapper (handlermapping) lookup Handler

3: Processor Mapper (handlermapping) finds corresponding handler (can be more annotated or XML configuration) based on configuration, may contain multiple interceptor interceptors, return to front Controller

4: Front Controller (dispatcherservlet) Request processor Adapter (Handleradapter) to perform the corresponding handler

5: Adapter is assigned to the corresponding handler processor

Return Modelandview object to processor adapter after 6:handler processor finishes executing

7: The processor adapter accepts the return result of the handler processor and returns the result to the front-end controller (dispatcherservlet)

8: Front Controller (Dispatcherservlet) receives the data and view information returned by the processor adapter, requests the View resolver, resolves the corresponding view

9: The view resolver returns to the front-end controller based on the corresponding view results matching the View information

10: Front controller receives a specific view, renders the view, fills the model data into the view view, and produces the final view

11: Front Controller returns results to user

Build your demo project from scratch:

Create a new Dynamic Web project under Eclipse

Project default directory structure:

Add a Jar package dependency

WebContent > Web-inf > lib folder to import the corresponding jar package, The core of the jar package is Spring-webmvc-5.0.0.release.jar, and the others are mostly spring for managing contexts and Beande packages, jstl tag libraries, and a log package for printing logs:

Configuring the front-end controller in Web. xml

The front-end controller is the equivalent of Spring MVC's proprietary servlet for intercepting all eligible requests and handing them over to the framework

<?XML version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://xmlns.jcp.org/xml/ns/javaee"xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"ID= "webapp_id"version= "3.1">          <!--Configuring the front-end controller-dispatchservlet -  <servlet>  <Servlet-name>Springmvcnext</Servlet-name>  <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>  <!--Contextconfiglocation is not required, if Contextconfiglocation is not configured, the SPRINGMVC configuration file defaults to: Web-inf/servlet name+ "-servlet.xml "  -  <Init-param>          <Param-name>Contextconfiglocation</Param-name>        <Param-value>Classpath:applicationContext.xml</Param-value>  </Init-param>  </servlet>    <servlet-mapping>  <Servlet-name>Springmvcnext</Servlet-name>  <Url-pattern>/</Url-pattern> <!--block requests from users based on rules set by Url-pattern block all requests here, including static resources, </servlet-mapping> </  web-app> 

Where the URL matching rules defined in the <servlet-mapping> tag are in the form of *.action, the corresponding servlet is named Springmvcnext, and the <servlet> The controller configured is Org.springframework.web.servlet.DispatchServlet, which is the front-end controller for the current SPRINGMVC project,<init-param> The tag is the parameter that the current controller depends on, and two parameters represent the context parameter and the parameter loading path.

About Classpath: Represents the compiled output path for a Web project after compilation

Configure the Spring MVC configuration

Add the Applicationcontext.xml file in the Java source code directory

Specific content:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:p= "http://www.springframework.org/schema/p"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:mvc= "Http://www.springframework.org/schema/mvc"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/security http://www.springframework.org/schema/security/ Spring-security.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/ Spring-mvc-4.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd ">    <!--the package scanner label will be used to activate the spring MVC Comment scanning feature, allowing annotations such as @controller and @requestmapping to be used.  -    <Context:component-scanBase-package= "Com.sl.controller" />        <!--Note Driver -    <Mvc:annotation-driven/>        <!--Configuring the View resolver -    <Beanclass= "Org.springframework.web.servlet.view.InternalResourceViewResolver"ID= "Internalresourceviewresolver">        < Propertyname= "prefix"value= "/web-inf/view/" />        < Propertyname= "suffix"value= ". jsp" />    </Bean></Beans>
Adding controller controllers and Views view

Add the package Com.sl.controller under the SRC directory and add the controller code as follows:

 PackageCom.sl.controller;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.servlet.ModelAndView; @Controller Public classHelloworldcontroller {@RequestMapping ("/index")//handles all requests beginning with/index in the URL path: including/index/* and/index.html     PublicModelandview HelloWorld () {String message= "Hello Spring MVC"; return NewModelandview ("index", "message", message); }}

Add a view file in Web-inf/view index.jsp

<HTML><Head>    <title>Spring MVC</title></Head><Body>${message}</Body></HTML>

Operation Result:

Spring MVC is new – starting from scratch

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.