• spring 官方文档-片段学习——webflux-ann-controller


    spring 官方文档-片段学习总结

    片段所在连接:https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web-reactive.html#webflux-ann-controller

    片段目录:

         

    1.4章节简述

      SpringWebFlux提供了一个基于注释的编程模型,其中@Controller和@RestController组件使用注释来表示请求映射、请求输入、异常处理等等。带注释的控制器具有灵活的方法签名,不需要扩展基类或实现特定的接口。

    1.4.1 @Controller ,表示一个类是控制器并自动被容器侦测。

    @Target({ElementType.TYPE})        #注解的作用目标——接口、类、枚举、注解
    @Retention(RetentionPolicy.RUNTIME)#保留至运行时
    @Documented                        #被javadoc工具记录
    @Component                         #视为组件,被容器自动侦测
    public @interface Controller {
    	String value() default "";
    }
    

          @RestController ,表示一个类是控制器并自动被容器侦测;将控制器返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区。

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Controller
    @ResponseBody                     #将控制器返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区
    public @interface RestController {
    	String value() default "";
    }

    1.4.2 Request Mapping

      @RequestMap注释用于将请求映射到控制器方法。它具有按URL、HTTP方法、请求参数、标头和媒体类型匹配的各种属性。

           它可以在类级别用于表示共享映射,也可以在方法级别用于缩小到特定的端点映射。

    @Target({ElementType.METHOD, ElementType.TYPE}) #注解的作用目标——方法;接口、类、枚举、注解。
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Mapping
    public @interface RequestMapping {
    
    	String name() default "";#为当前映射指定一个名称,不常用,一般不会指定
    
    	@AliasFor("path")#属性的别名
    	String[] value() default {};#value path 等价
    
    	@AliasFor("value")#属性的别名
    	String[] path() default {};#value path 等价
    
    	RequestMethod[] method() default {};#约束映射到的HTTP请求方法;GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
    #根据这些特定方法,分别有RequestMapping的相应变体。
    	String[] params() default {};#约束请求参数,例如:params = "myParam=myValue"  ;处理请求中包含了名为“myParam”,值为“myValue”的请求
    
    	String[] headers() default {};#约束请求头,例如:headers = "content-type=text/*"
    
    	String[] consumes() default {};#约束请求可消费的媒体类型,例如:consumes = {"text/plain", "application/*"}
         
    	String[] produces() default {};#约束请求可生成的媒体类型,例如:produces = {"text/plain", "application/*"}
    }

    它还有几个HTTP方法的快捷变体(可类比对数据库的操作理解):

    • @GetMapping         查

    • @PostMapping        改增

    • @PutMapping         增

    • @DeleteMapping      删

    • @PatchMapping       用于将HTTP{@code Patch}请求映射到特定处理程序方法的注释【还不理解】

    1.4.3 Handler methods

      常见的控制器方法参数注解:@PathVariable、@RequestParam、@RequestHeader、@ModelAttribute、@SessionAttributes@SessionAttribute

    、@CookieValue、@RequestBody、@RequestPart。分别举例演示:

    @PathVariable
    // GET /pets/42
    @GetMapping("/pets/{petId}")
    public void findPet(@PathVariable String petId) {
    
        // petId == 42
    }
    

    @RequestParam

    @GetMapping
        public String setupForm(@RequestParam("petId") int petId, Model model) {
            Pet pet = this.clinic.loadPet(petId);
            model.addAttribute("pet", pet);
            return "petForm";
        }

    @RequestHeader

    /**
    模拟请求头
    Host                    localhost:8080
    Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
    Accept-Language         fr,en-gb;q=0.7,en;q=0.3
    Accept-Encoding         gzip,deflate
    Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
    Keep-Alive              300

    */
    @GetMapping("/demo")
    public void handle(
            @RequestHeader("Accept-Encoding") String encoding,
            @RequestHeader("Keep-Alive") long keepAlive) {
        //...
    }

    @ModelAttribute

    @PostMapping("/owners/{ownerId}/pets/{petId}/edit")
    public String processSubmit(@ModelAttribute Pet pet) { }  # ownerId petId 需要和对象Pet的参数key匹配。

    @SessionAttributes ,用于类级注解,用来存储请求间的模型数据,同级别的子节点共享数据。

    @Controller
    @SessionAttributes("pet")
    public class EditPetForm {
    
        // ...
    
        @PostMapping("/pets/{id}")
        public String handle(Pet pet, BindingResult errors, SessionStatus status) {
            if (errors.hasErrors) {
                // ...
            }
                status.setComplete();
                // ...
            }
        }
    }

    @SessionAttribute,根属性数据,全部节点共享数据。

    如果您需要访问全局管理的预先存在的会话属性,即控制器外部(例如,通过过滤器),并且可能存在或不存在,则可以使用方法参数上的@SessionAttribute注释。

    @GetMapping("/")
    public String handle(@SessionAttribute User user) {
        // ...
    }

    @CookieValue

    //模拟cookie   JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
    
    @GetMapping("/demo")
    public void handle(@CookieValue("JSESSIONID") String cookie) {
        //...
    }

    @RequestBody,使用@RequestBody注释通过HttpMessageReader读取请求体并将其反序列化为对象

    //@Valid 序列化后对象必须匹配,否则报 WebExchangeBindException,响应BAD_CODE为:400
    @PostMapping("/accounts")
    public void handle(@Valid @RequestBody Account account, BindingResult result) {
        // ...
    }

    @RequestPart

    /**
    Multipart requests can also be submitted from non-browser clients in a RESTful service scenario. For example a file along with JSON:
    
    POST /someUrl
    Content-Type: multipart/mixed
    
    --edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
    Content-Disposition: form-data; name="meta-data"
    Content-Type: application/json; charset=UTF-8
    Content-Transfer-Encoding: 8bit
    
    {
        "name": "value"
    }
    --edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
    Content-Disposition: form-data; name="file-data"; filename="file.properties"
    Content-Type: text/xml
    Content-Transfer-Encoding: 8bit
    ... File Data ...
    */
    @PostMapping("/")
    public String handle(@RequestPart("meta-data") MetaData metadata,
            @RequestPart("file-data") FilePart file) {
        // ...
    }

    1.4.4. Model Methods

    @ModelAttribute注释可以在@RequestMapping方法参数上使用,以从模型创建或访问对象并将其绑定到请求。@ModelAttribute还可以用作控制器方法的方法级注释,其目的不是处理请求,而是在请求处理之前添加常用的模型属性。

    控制器可以有任意数量的@ModelAttribute方法。所有这些方法都在同一个控制器中的@RequestMapping方法之前调用。还可以通过@ControllerAdview在控制器之间共享@ModelAttribute方法。有关详细信息,请参阅关于Controller通知的部分。

    @ModelAttribute方法具有灵活的方法签名。除了@ModelAttribute本身或与请求主体相关的任何内容之外,它们支持与@RequestMapping方法相同的许多参数。

    1.4.5、1.4.6 略

  • 相关阅读:
    动软代码生成器 修改配置
    显示转换explicit和隐式转换implicit
    Memcache学习整理
    SQL2008-分页显示3种方法
    SQL2008-表对表直接复制数据
    SQL2008-删除时间字段重复的方法
    SQL2008-中不想插入从复记录
    SQL2008-c:PROGRA~1COMMON~1SystemOLEDB~1oledb32.dll出错找不到指定的模块
    ACCESS-如何多数据库查询(跨库查询)
    ACCESS-字符函数
  • 原文地址:https://www.cnblogs.com/wzk1992/p/8591010.html
Copyright © 2020-2023  润新知