一、@Controller标注的类表示的是一个处理HTTP请求的控制器(即MVC中的C),该类中所有被@RequestMapping标注的方法都会用来处理对应URL的请求。该类也可以被@RequestMapping标注,此时该类中所有方法的url路径都在该目录下。
在SpringMVC框架中,使用@RequsetMapping标注可以将URL与处理方法绑定起来,例如:
@RestController//控制器
@RequestMapping("/index")//绑定接口url:localhost:8080/index
public class HelloController {
private final Logger LOG = LoggerFactory.getLogger(HelloController.class);
@RequestMapping("/")//绑定接口url:localhost:8080/index/
public String HelloWorld(){
return "hello world";
}
@RequestMapping("/test")//绑定接口url:localhost:8080/index/test
public String HelloWorldTwo(){
return "this is a test";
}
}
在浏览器地址里输入:localhost:8080/index/、localhost:8080/index/test,请求会分别交给对应接口绑定的方法Helloworld()和HelloWorldTwo()处理。
结果:
二、@RequestMapping的解释
在web应用中常用的HTTP方法有四种:
- PUT方法用来添加资源
- GET方法用来获取已有的资源
- POST方法用来对资源进行状态转换
- DELETE方法用来删除已有的资源
每一个Web请求都是属于其中一种,在@RequestMapping中如果不指定method值的话,默认是GET请求。
因此@RequestMapping("/")是@RequestMapping("/",method = RequestMethod.GET)的默认,可以通过method属性,设置请求的HTTP方法。
@RequestMapping(value = "/",method = RequestMethod.GET)
//等价于@RequestMapping("/")
@RequestMapping(value = "/",method = RequestMethod.PUT)
@RequestMapping(value = "/",method = RequestMethod.POST)
@RequestMapping(value = "/",method = RequestMethod.DELETE)
比如PUT /hello请求,对应@RequestMapping("/hello",method = RequestMethod.PUT)
Spring MVC最新的版本中提供了一种更加简洁的配置HTTP方式,增加了四个简写注解:
- PutMapping
- GetMapping
- PostMapping
- DeleteMapping
@GetMapping("/")
//等价于@RequestMapping(value = "/",method = RequestMethod.GET)
@PutMapping("/")
//等价于@RequestMapping(value = "/",method = RequestMethod.PUT)
@PostMapping("/")
//等价于@RequestMapping(value = "/",method = RequestMethod.POST)
@DeleteMapping("/")
//等价于@RequestMapping(value = "/",method = RequestMethod.DELETE)