Spring 4.3 中引進了下面的注解 @RequestMapping 在方法層級的變種,來幫助簡化常用 HTTP 方法的映射,並更好地表達被注解的方法的語義。比如,@GetMapping可以讀作 GET @RequestMapping。
-
@GetMapping
-
@PostMapping
-
@PutMapping
-
@DeleteMapping
-
@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 ......
