Spring MVC - Quick Start

Table of contents

1、SpringMVC

1.1. Review the MVC architecture

1.2. Overview of Spring MVC

1.3. Features of Spring MVC

1.4. The overall architecture of SpringMVC

2. Spring MVC quick start

2.1. Create a web project

2.2. Import dependent coordinates

2.3, tomcat plug-in

2.4, configure the DispatcherServlet front controller

2.5, SpringMVC core configuration file

2.6. Create page

2.7, custom Header (Controller)

3. Annotation development

3.1. Create a Controller class

4. Five mappings

4.1, standard mapping

4.2, Ant style url mapping 

4.3, placeholder mapping

4.4. Limit request method mapping

4.5. Limit request parameters

5. SpringMVC page jump

5.1, return string

5.2. Forwarding (forward keyword)

5.3. Redirection (redirect keyword)

6. Spring MVC stores data

6.1, servlet storage data

6.2. Model stores data


1、SpringMVC

1.1. Review the MVC architecture

MVC is an acronym for Model, View, and Controller, and is a software design specification.

Model: javaBean (1. Process business logic, 2. Encapsulate data)
View: View jsp/html (display data)
controller: Controller (1. Receive request, 2. Call model, 3. Forward view)

MVC organizes code by separating business logic, data, and display. The main function of MVC is to reduce the coupling between view and business logic. MVC is not a design pattern, MVC is an architectural pattern. Of course there are some differences between different MVCs!

1.2. Overview of Spring MVC

Spring MVC is a part of Spring Framework, which is a lightweight web framework based on Java to implement MVC. It can make a simple Java class a controller through a set of annotations without implementing any interface.

A simple sentence: SpringMVC simplifies the development of Servlets! ! , SpringMVC mainly solves the code of the web layer, which is essentially Servlet.

1.3. Features of Spring MVC

1. Lightweight, easy to learn.
2. Efficient, request-response-based MVC framework.
3. Good compatibility with Spring and seamless integration.
4. Convention is better than configuration (SpringBoot).
5. Powerful functions: RESTful, data validation, formatting, localization, themes, etc.
6. Simple and flexible.

1.4. The overall architecture of SpringMVC

There are five main components:

Front controller (DispatcherServlet): only responsible for receiving and responding

Processor mapper (HandlerMapping): Find the corresponding processor according to the requested url

Processor (Handler): the processor defined by the programmer

Processor Adapter (HandlerAdpter): Execute the processor handler

View Resvoler (ViewResvoler): Perform view analysis, process the returned data, and parse it into corresponding page information

1. The user initiates a request to the controller DispatcherServlet (front controller)
2. The front controller goes to the handlerMapper to find the Handler object
3. The HandlerMapper returns the HandlerExecutorChain execution chain (including two parts: Handler, interceptor collection)
4. The front controller, through The HandlerAdapter adapter executes the Handler object
5, the Handler processes the specific business logic
6, after the Handler processes the business logic, returns the ModelAndView where the View is the view name
7, returns the ModelAndView to the front controller
8, the front controller, through the view name in the ModelAndView . Lookup view in view resolver
9, return real View view object
10, render view
11, return user response

2. Spring MVC quick start

2.1. Create a web project

Created maven web project

2.2. Import dependent coordinates

<!--springmvc依赖包,springmvc 只有这一个包-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.9.RELEASE</version>
</dependency>

<!--serlvet-->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>provided</scope>
</dependency>

<!--jsp-->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.0</version>
  <scope>provided</scope>
</dependency>

<!--日志-->
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>1.6.4</version>
</dependency>

<!--测试-->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>

2.3, tomcat plug-in

<build>
  <plugins>
    <!--添加tomcat插件-->
    <plugin>
       <groupId>org.apache.tomcat.maven</groupId>
       <artifactId>tomcat7-maven-plugin</artifactId>
       <version>2.2</version>
       <configuration>
           <port>8080</port>
           <path>/</path>
       </configuration>
    </plugin>
    
  </plugins>
</build>

Click Add Configuration in the upper right corner

 

Click the + sign in the upper left corner, select the Maven add below, fill in tomcat7:run in the configuration bar behind and apply ok

2.4, configure the DispatcherServlet front controller

Configure the DIspatcherServlet front controller in the web.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
           version="3.0">
    <!--前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载指定配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--指定servlet在tomcat启动时创建-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--
            *.do           匹配后缀
            /              请求不了 html,js,css,img
            /*             只能访问controller请求
        -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

2.5, SpringMVC core configuration file

Configure the springmvc-servlet.xml file

<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--HandlerMapping 映射器  springmvc会自己配置无需配置  -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <!--HandlerAdapter 适配器 springmvc会自己配置无需配置-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <!--配置自定义的handler controller-->
    <bean name="handler" class="cn.itssl.controller.Hello"/>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

2.6. Create page

Create a page hello.jsp corresponding to the prefix according to the prefix. Note: the view name here must be consistent with the name written in the setViewName method in the custom Headler, because the front controller will search for the page according to the view name and then echo the data. .

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

2.7, custom Header (Controller)

Create a Hello class to implement the Controller interface, and override the method handleRequest inside.

public class Hello implements Controller {

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","这是第一个springmvc程序!!");

        //设置视图名   hello仅仅是视图的名字
        mv.setViewName("hello");

        return mv;
    }
}

Note: The name filled in setViewName here is the view name, which will automatically splice the prefix and suffix for us, because we have configured it in the configuration file, so the path it finally requests is: localhost:8080/hello.do, The .do here is the matching suffix I configured in the url-pattern in web.xml, and has nothing to do with the splicing suffix .jsp.

3. Annotation development

Thinking in the introductory case:
    1. Each class needs to implement Controller, which is troublesome.
    2. Each class can only handle one business logic, and the controller cannot handle multiple business logics.
    3. Each Controller needs to be configured
    using annotations: to solve the above problems

After learning to use xml configuration files, I always feel that it is too troublesome, so annotation development can be carried out very simply, omitting the cumbersome xml configuration.

3.1. Create a Controller class

@Controller//注解声明这是一个Controller类
@RequestMapping("/hello")
public class Hello2 {
    //标准映射 value可以省略不写,以及/也可省略不写
    @RequestMapping(value = "/show")
    public ModelAndView test1(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","这是第一个springmvc注解!!");
        mv.setViewName("hello");
        return mv;
    }
}

 Configure the core configuration file (enable annotation scanning and enable springMVC annotation driver)

<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--扫描包下的注解-->
    <context:component-scan base-package="cn.itssl.*"/>
    <!--开启注解驱动-->
    <mvc:annotation-driven/>
</beans>

Start the tomcat server test

4. Five mappings

4.1, standard mapping

  //标准映射
    @RequestMapping(value = "/show")
    public ModelAndView test1(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","这是第一个springmvc注解!!");
        mv.setViewName("hello");
        return mv;
    }

4.2, Ant style url mapping 

 //Ant风格url映射
    @RequestMapping("/test/*/show2")
    public ModelAndView test2(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","这是第一个springmvc注解!!2222");
        mv.setViewName("hello");
        return mv;
    }

Multi-level directories can write single-level directories 

//多级目录可以写单级目录
    @RequestMapping("/test/**/show3")
    public ModelAndView test3(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","这是第一个springmvc注解!!2222");
        mv.setViewName("hello");
        return mv;
    }

4.3, placeholder mapping

@RequestMapping(“/user/{userId}/query")

Get the parameter value in the request path through @PathVariable("xxx")

//占位符映射
    @RequestMapping("/show4/{itemId}/{name}")
    public ModelAndView test4(@PathVariable("itemId") String itemId,@PathVariable("name") String name){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","itemId:"+itemId+" name:"+name);
        mv.setViewName("hello");
        return mv;
    }

4.4. Limit request method mapping

RequestMethod.POST @PostMapping("xx")

RequestMethod.GET @GetMapping("xx")

//限制请求方式映射
    //post请求方式
    @RequestMapping(value = "/show5",method = RequestMethod.POST)
    public ModelAndView test5(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","这是指定了post请求方式");
        mv.setViewName("hello");
        return mv;
    }
    //限制请求方式映射
    //get请求方式
    @RequestMapping(value = "/show6",method = RequestMethod.GET)
    public ModelAndView test6(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","这是指定了get请求方式");
        mv.setViewName("hello");
        return mv;
    }
    //限制请求方式映射
    //post/get请求方式  @RequestMapping默认
    @RequestMapping(value = "/show7",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView test7(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","这是指定了get/post请求方式");
        mv.setViewName("hello");
        return mv;
    }

The above method can be replaced by the following 

    @GetMapping("show8")
    public ModelAndView test8(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","这是指定了get请求方式");
        mv.setViewName("hello");
        return mv;
    }
    @PostMapping("show9")
    public ModelAndView test9(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","这是指定了post请求方式");
        mv.setViewName("hello");
        return mv;
    }

4.5. Limit request parameters

Can prevent users from injecting unnecessary information

@GetMapping(value = "show15",params = "id") must contain id
@GetMapping(value = "show15",params = "!id") cannot contain id
@GetMapping(value = "show15",params = "id !=1007") contains id whose value is not 1007

    //请求参数必须包含id  方式一
    @GetMapping(value = "show10",params = "id")
    public ModelAndView test10(@RequestParam("id") int id){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","限定请求参数:"+id);
        mv.setViewName("hello");
        return mv;
    }
    //请求参数必须包含id   方式二
    @GetMapping(value = "show11")
    public ModelAndView test11(@RequestParam("id") int id){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","限定请求参数:"+id);
        mv.setViewName("hello");
        return mv;
    }
    //请求参数不包含id
    @GetMapping(value = "show12",params = "!id")
    public ModelAndView test12(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","非id参数");
        mv.setViewName("hello");
        return mv;
    }
    //请求参数包含id其值不能为1007
    @GetMapping(value ="show13",params = "id!=1007")
    public ModelAndView test13(@RequestParam("id") int id){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","限定请求参数:"+id);
        mv.setViewName("hello");
        return mv;
    }

5. SpringMVC page jump

5.1, return string

@Controller
@RequestMapping("hello3")
public class Hello3 {
    @RequestMapping("show1")
    public ModelAndView show1(){
        //第一种 ModelAndView 转发到视图解析器
        return new ModelAndView("hello");
    }
    //第二种 String 转发到视图解析器
    @RequestMapping("show2")
    public String show2(){
        return "hello";
    }
    //第三种 void 没有返回的视图
    @RequestMapping("show3")
    @ResponseStatus(HttpStatus.OK)
    public void show3(){
        System.out.println("我没有要返回的结果..");
    }

    //第四种 转发--通过servlet内置对象
    @RequestMapping("show4")
    public void show4(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(request,response);
    }
}

5.2. Forwarding (forward keyword)

    //第一种 转发--webapp   页面
    @RequestMapping("show5")
    public String show5(){
        return "forward:/user.html";
    }
    //第二种 转发--webapp   controller类
    @RequestMapping("show6")
    public String show6(){
        return "forward:/hello/show.do";
    }

    //第三种 转发--ModelAndView
    @RequestMapping("show7")
    public ModelAndView show7(ModelAndView mv){
        mv.setViewName("forward:/user.html");//webapp下的页面
        return mv;
    }
    //第三种 转发--ModelAndView
    @RequestMapping("show8")
    public void shiw8(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/user.html").forward(request,response);
    }

5.3. Redirection (redirect keyword)

The bottom layer of this keyword: response.sendRedirect("web project address + redirection address");

@Controller
@RequestMapping("hello4")
public class Hello4 {
    //第一种 重定向 redirect关键字
    @RequestMapping("show1")
    public String show1(){
        return "redirect:/user.html";//重定向webapp下的具体页面
    }
    //第二种 重定向 ModelAndView
    @RequestMapping("show2")
    public ModelAndView show2(ModelAndView mv){
        mv.setViewName("redirect:/user.html");
        return mv;
    }
    //第三种 重定向 绑定servlet内置对象
    @RequestMapping("show3")
    public void show3(HttpServletRequest request, HttpServletResponse response) throws IOException {
       response.sendRedirect(request.getContextPath()+"/user.html");
    }
}

6. Spring MVC stores data

Create a list.jsp page under the webapp package

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
姓名:
${requestScope.name}
城市:
${requestScope.city}
年龄:
${requestScope.age}
</body>
</html>

6.1, servlet storage data

@Controller
@RequestMapping("test")
public class ServletTest {


    @RequestMapping("requestAPI")
    public void requestAPI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("name","itssl");
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }
    
}

6.2. Model stores data

//方式一 ModelAndView存数据
    @RequestMapping("modelAndViewTest")
    public ModelAndView modelAndViewTest(ModelAndView mv){
        mv.addObject("name","jack");
        mv.setViewName("list");
        return mv;
    }
    //方式二 Model
    @RequestMapping("TestModel")
    public String modelAndViewTest2(Model model){
        model.addAttribute("name","rose");
        return "forward:/list.jsp";
    }
    //方式三 ModelMap
    @RequestMapping("TestModelMap")
    public String modelAndViewTest3(ModelMap modelMap){
        modelMap.addAttribute("city","zhengzhou");
        return "forward:/list.jsp";
    }
    //方式四 Map
    @RequestMapping("TestMap")
    public String modelAndViewTest4(Map<Object,Object> map){
          map.put("age",21);
          return "forward:/list.jsp";
    }

Guess you like

Origin blog.csdn.net/select_myname/article/details/127542903