content

1. Introduction of SpringMVC 2. Workflow of SpringMVC 3. Construction and configuration file description of SpringMVC 4

For SpringMVC introduction

SpringMVC is a successor to the Spring Framework and has been integrated into Spring Web Flow. The Spring framework provides a full-featured MVC module for building Web applications. Use Spring pluggable MVC architecture, so that when using Spring for WEB development, you can choose to use Spring’s SpringMVC framework or integrate other MVC development frameworks, such as Struts1(not used now), Structs2(generally used in old projects), etc.

Features:

1.SpringMVC is a successor to Spring. 3. MVC based design pattern M: Entity, DAO, Service V:HTML,Jsp, Velocity C: Control layer,SpringMVC,Struts2

SpringMVC workflow

Working principle diagram:

Working principle Text description:

1. The user sends the request to the DispatcherServlet of the front-end controller. 2. The DispatcherServlet invokes the HandlerMapping processor mapper upon receiving the request. 3. The processor mapper finds the specific processor and generates a processor object and a processor interceptor (if any) back to the DispatcherServlet. 4. DispatcherServlet calls the HandlerAdapter processor adapter. 5. The HandlerAdapter ADAPTS to invoke specific handler (Controller, also known as back-end Controller) methods. 6. The handler returns the ModelAndView to the HandlerAdapter after execution. 7. The HandlerAdapter returns the processor execution result ModelAndView to the DispatcherServlet. 8. The DispatcherServlet passes the ModelAndView to the ViewReslover view parser. 9. ViewReslover returns specific View to DispatcherServlet after parsing. 10. The DispatcherServlet calls the View parser to render the View from the View (that is, populate the View with model data). 11. Return the rendered page to the front-end controller DispatcherServlet. 12. DispatcherServlet responds to the rendered page to the client.

Noun explanation:

1.DispatcherServlet(front-end controller) : core component, coordinating calls to other components. HandlerMapping: Find the Handler that handles the request based on the request. 3.Handler: A method used to process requests. 4.HandlerAdapter: ADAPTS parameters and calls to execute handler methods. 5.ModelAndView: Encapsulates the jump page and the parameters passed to the page. 6.ViewResolver: Finds the page to jump to and parses data to that page.

For SpringMVC construction

1. Create a Web project dependency package:

2. Configure the front-end controller in web. XML.

<! -- Front-end controller -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
<! -- Front-end control class -->
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<! Web-inf /servlet-name+"-"servlet.xml(springmVC-servlet.xml)-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
<! -- "/" represents all forms of request, or *. Do, not *.*-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
Copy the code

3. Write the SpringMVC configuration file:

(Other non-default mapping handlers and processor adapters, as well as custom view parsers, and bean nodes to map requests to handlers)

<?xml version="1.0" encoding="UTF-8"? >
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <! -- Request "/login", LoginController handles request -->
    <bean id="/login" class="com.springmvc.controller.LoginController"/>
</beans>
Copy the code

4. Custom processor class (implementation interface) :

The LoginController class implements the Controller interface:

public class LoginController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        mv.addObject("msg"."Successful landing.");
        System.out.println(1111111);
        returnmv; }}Copy the code

5. Test:

Directly enter project url /login in the browser address bar

Additional notes to the SpringMVC configuration file:

<! Instantiate a non-default mapping handler --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/ > <! Instantiate the non-default adapter handler --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/ > <! Define the prefix and suffix of the view parserreturn "Write the page name directly"No longer suffix. JSP --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
Copy the code

Custom processor class (annotated) :

1. Enable annotation scanning and MVC annotation driver in Spring configuration files:

<! --> <context:component-scan base-package="com.springmvc.controller"/ > <! < MVC :annotation-driven Conversion -service="myConverter"/>
Copy the code

2. Define processor classes through annotations

Here I’ll create a new regController.java file:

@Controller// Instantiate the subcontroller class
public class RegController {

    @RequestMapping("reg")// This annotation is for example mapping the matching request "reg"
    public ModelAndView reg(a){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        mv.addObject("msg".Registered "1");
        returnmv; }}Copy the code

@requestMapping (” requestname “) : matches requests that can be added to classes or methods. Request names in annotations can be omitted.

Note: 1. The @requestMapping annotation is not allowed on a class, but it is required for a method in a class to be a processor method. 2. If the annotation exists on both classes and methods, and the request name in the annotation is omitted, this method is the default requested method. At http://locathost:8080/springmvc01/, the default priority access static front page, if there is no static front page is the default request access to the background.

SpringMVC value passing

Back end to front end

(1) through (Model, ModelAndView, Map, ModelMap), request the request:

Case description:

The return type is String, which is used as the view name by default. Class type parameters in processor methods are automatically instantiated.

@Controller
public class RegController {

    @RequestMapping("reg")
    public ModelAndView reg(a){/ / ModelAndView spread value
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        mv.addObject("msg".Registered "1");
        return mv;
    }

    @RequestMapping("reg1")// The return type is String as the view name; Class type parameters in the processor are automatically instantiated
    public String reg1(Model m){/ / the Model values
        m.addAttribute("msg"."Pass the data to the front page through the model");
        return "index";
    }

    @RequestMapping("reg2")
    public String reg2(Map m){/ / the Map values
        m.put("msg"."Send data to front page via map");
        return "index";
    }

    @RequestMapping("reg3")
    public String reg3(ModelMap m){/ / ModelMap spread value
        m.put("msg"."Upload data to front page via ModelMap");
        return "index";
    }

    @RequestMapping("reg4")
    public String reg4(a){// The return type is String as the view name; Class type parameters in the processor are automatically instantiated
        return "index"; }}Copy the code

2. Pass values through Session:

    @RequestMapping("reg5")
    public String reg5(HttpSession session){
        session.setAttribute("msg"."Sending data to the front-end page via session");
        return "index";
    }
Copy the code

Front-end JSP page:

<%@ page contentType="text/html; charset=UTF-8" language="java"%> < HTML > <head> <title> title </title> </head> <body>${msg}

${uid}
</body>
</html>

Copy the code

The front-end data is transferred to the background

1. The background receives data transmitted by the page through int,String and other types:

Front-end JSP page:

 <a href="user/getUById? uid=1&uname=lkk"> Edit </a> <%-- @requestMapping (RequestMapping) {"user"), and then access the processor method"getUById"In this case, I chose the first level request: direct access to the processor method. --%> <a href="getUById? uid=1&uname=lkk"> edit < / a >Copy the code

Background receives page data via int,String:

@RequestMapping("getUById")
	public String getUById(Model m,int uid,String uname) {
		m.addAttribute("msg", u);
		return "main";
	}

Copy the code

2. The background receives the data transmitted by the page through the custom class:

Background User entity class:

public Class User{
    private int uid;
    private String uname;
}
Copy the code

Receive page submitted data with custom type User:

@RequestMapping("getUById")
	public String getUById(Model m,User u) {
		m.addAttribute("msg", u);
		return "index";
	}
Copy the code

If you’re just getting started, take a look at this tutorial and hope it helps!