spring 学习(二)什么是spring mvc

637 阅读3分钟

什么是spring mvc

Spring的web MVC框架与许多其他web MVC框架一样,是请求驱动的,Spring Web模型-视图-控制器(MVC)框架是围绕DispatcherServlet设计的,DispatcherServlet将请求分派给处理程序,具有可配置的处理程序映射、视图解析、区域设置和主题解析,以及对上传文件的支持。默认处理程序基于@Controller和@RequestMapping注释,提供了多种灵活的处理方法。

spring mvc 请求处理机制

chapter_6_DispatcherServlet.png

这个图描述了spring mvc处理web请求的基本逻辑

  1. 请求首先会进入front controller(DipatcherServlet),由前端控制器把请求分配到对应的controller,
  2. 由特定的controller中的逻辑去handle request,处理完返回一个模型给Front Controller
  3. front controller 把模型交给视图模板去呈现视图,把结果给front controller

声明controller

spring mvc 提供基于注解的编程模式,其中@Controller,@RestController元素处理请求映射,请求输入,异常handle。

  • @Controller
  • @RestController 相当于@Controller + @ResponseBody

映射请求处理方法

@RequestMapping 用于将web请求映射到请求处理类的方法。提供一些参数,用于限制映射的请求:

  • path,value 映射请求URI,String数组,可以映射多个URI,可以忽略参数名,如:@RequestMapping("/foo")。
  • method 被允许的http请求方法,可以是:GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE,如:method = RequestMethod.GET,没有默认值,如果不配置method参数,使用GET, POST, PUT, PATCH, DELETE方法的请求都可以映射到这个方法上。
  • params 映射请求的参数,1. 请求参数必须包含这个设定的值才会映射到这个方法(eg. params = "myParam=myValue",),2. 请求参数必须没有这个参数才能映射到该方法(eg. params = "!name"), 3. 请求参数必须包含指定的参数才会映射到该方法(eg. params = "name")
  • headers 限制映射请求的header内容,(eg. headers = "content-type=text/*",请求的content-type 的值为text/html或text/plain可以映射到该方法)
  • consumes 限制请求的Content-Type(使用Content-Type来表示具体请求中的媒体类型信息),可以使用 “!”运算符 (eg. consumes = {"text/plain", "application/*"})
  • produces 限制请求的Accept(请求中的Accept 字段是让服务器知道什么media type是client端可以接受的。),可以使用 “!”运算符(eg. produces = {"text/plain", "application/*"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

其他注解

  • @GetMapping 相当于@RequestMapping + (method = RequestMethod.GET)
  • @PostMapping
  • @PutMapping

URL patterns

  • "/resources/ima?e.png" - match one character in a path segment
  • "/resources/*.png" - match zero or more characters in a path segment
  • "/resources/**" - match multiple path segments
  • "/projects/{project}/versions" - match a path segment and capture it as a variable
  • "/projects/{project:[a-z]+}/versions" - match and capture a variable with a regex

捕捉的URI变量可以用@PathVariable访问 For example:

@GetMapping("/owners/{ownerId}/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
    // ...
}

可以在类或方法级别声明URL变量,

@Controller
@RequestMapping("/owners/{ownerId}")
public class OwnerController {

    @GetMapping("/pets/{petId}")
    public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
        // ...
    }
}

handle method

方法参数

下面表格描述了支持controller 的方法参数,任何参数都不支持响应类型。

Controller method argumentDescription
WebRequest访问请求参数和session属性.
@PathVariable访问URI模板变量
@MatrixVariable用来访问URI path 片段中的name-value pairs
@RequestParam用来访问servlet请求参数,
@RequestHeader用来访问servlet请求header
@CookieValue用来访问cookies
@RequestBody访问http request body,把body 转换成这个方法的参数对象

Map 及 Model 概述 Spring MVC 在内部使用了一个org.springframework.ui.Model 接口存储模型数据。

Spring MVC 在调用方法前会创建一个–隐含的模型对象作为模型数据的存储容器。如果方法的入参为 Map 或 Model 类型,Spring MVC 会隐含模型的引用传递给这些入参。在方法体内,开发者可以通过这个入参对象访问到模型中的所有数据,也可以向模型中添加新的属性数据。

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ricky.codelab.webapp.ch2.model.User;

@Controller
@RequestMapping("model")
public class ModelController {

    @RequestMapping("register")
    public String register(User user, Model model){

        model.addAttribute("user", user);

        return "home";
    }

    @RequestMapping("register2")
    public String register(User user, Map<String, Object> map){

        map.put("user", user);

        return "home";
    }
}


Return Value

被@ResponseBody注释的方法返回数据绑定到响应body,返回值可以是String或对象

@GetMapping("/accounts/{id}")
@ResponseBody
public Account handle() {
    // ...
}

参考

docs.spring.io/spring-fram…