spring4.3新注解之:@RequestMapping变种(@GetMapping,@PostMapping,@PutMapping,@DeleteMapping,@PatchMapping)

Spring 4.3 中引进了下面的注解 @RequestMapping 在方法层级的变种,来帮助简化常用 HTTP 方法的映射,并更好地表达被注解的方法的语义。比如,@GetMapping可以读作 GET @RequestMapping。

  1. @GetMapping

  2. @PostMapping

  3. @PutMapping

  4. @DeleteMapping

  5. @PatchMapping

下面是一个示例:

1)编写 JSP 页面

    首先在上一篇中的项目中的 helloWorld.jsp 中追加下面的代码

<hr>
    <h2>Composed RequestMapping</h2>
    <a href="composed/get">Test1</a>
    <br>
    <a href="composed/2016-09-05">Test2</a>
    <br>
    <!-- 一个以 POST 方式提交的表单 -->
    <form action="composed/post" method="post">
        Username:<input type="text" name="username" placeholder="用户名..."><br>
        Password:<input type="password" name="password" placeholder="用户名..."><br>
        <button type="submit">登录</button>
    </form>

2)定义一个控制器

    在代码中,添加下面的控制器:

package com.techmap.examples.controllers;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 组合的 @RequestMapping。
 */
@Controller
@RequestMapping("/composed")
public class ComposedController
{
    
    @GetMapping("/get")
    public String get()
    {
        return "/examples/targets/test1";
    }
    
    /**
     * 带有 URI 模板
     */
    @GetMapping(path = "/{day}")
    public String getForDay(@PathVariable @DateTimeFormat(iso = ISO.DATE) Date day, Model model)
    {
        System.out.println("--> " + new SimpleDateFormat("yyyy-MM-dd").format(day));
        
        return "/examples/targets/test2";
    }
    
    @PostMapping("/post")
    public String post(
            @RequestParam(value="username") String user, 
            @RequestParam(value="password") String pass
            )
    {
        System.out.println("--> Username: " + user);
        System.out.println("--> Password: " + pass);
        
        return "/examples/targets/test3";
    }
}

3)测试

    点击 Composed RequestMapping 下面的 test1 和 test2 超链接,会正常进行页面跳转。输入用户名和密码,并点击“登录”按钮后,也会进行跳转,但是控制台会像下面那样打印出输入的用户名密码(我输入的用户名和密码都是inspector):

......
DEBUG 2016-09-07 08:31:24,923 Returning cached instance of singleton bean 'composedController'  (AbstractBeanFactory.java:249) 
--> Username: inspector
--> Password: inspector
DEBUG 2016-09-07 ......
原文地址:https://www.cnblogs.com/duanxz/p/7489033.html