Spring 4.3 中引进了下面的注解 @RequestMapping 在方法层级的变种,来帮助简化常用 HTTP 方法的映射,并更好地表达被注解的方法的语义。比如,@GetMapping可以读作 GET @RequestMapping。
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
下面是一个示例:
1)编写 JSP 页面
首先在上一篇中的项目中的 helloWorld.jsp 中追加下面的代码
Composed RequestMapping
Test1 Test2
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: inspectorDEBUG 2016-09-07 ......