一、请求及路径映射部分注解介绍
注解名称 | 描述 |
@Controller | 处理http请求 |
@RestController | Spring4之后新加的注解,原来返回json,需要@ResponseBody配合@Controller |
@RequestMapping | 配置url映射 |
1、@Controller的使用(了解)
相当于serverlet的jsp,前后端不分离的开发,就模板而言很好性能,所以提倡前后端分离式的开发,
2、@RestController的使用
@RestController在实际开发中应用广泛,与@controller相比,不依赖于模板,前后端分离式的开发,开发效率也很高。
3、@RequestMapping的使用
该注解既可以在类上方使用,又可以方法上使用,在类上方使用,如在该处添加,接口访问时采取路径拼接方式访问,如:localhost:8888/spring/hellow
package com.rongrong.springboot.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @author rongrong
* @version 1.0
* @description:
* @date 2019/12/26 20:34
*/
@RestController
/**
* 在类上方使用,如在该处添加,接口访问时采取路径拼接方式访问
* 如:localhost:8888/spring/hellow
*/
@RequestMapping("/spring")
public class HellowController {
@Autowired
Person person;
//在方法 上方使用
@RequestMapping(value = "/hellow",method = RequestMethod.GET)
public String say(){
return person.getGName();
}
}
二、请求参数及组合注解介绍
注解名称 | 描述 |
@PathVariable | 获取url中的数据 |
@RequestParam | 获取请求参数的值 |
@GetMapping | 组合注解 |
1、@PathVariable的使用
一般在restful风格接口使用居多,形式为:/路径/{变量}
//Restful风格接口
@RequestMapping(value = "/getID/{id}", method = RequestMethod.GET)
public String getID(@PathVariable("id") Integer id) {
return "Id:"+id;
}
2、@RequestParam使用
为传统风格形式使用,
3、组合注解及多个路径可以访问同一个接口
@GetMapping可以理解为@RequestMapping
/**
* 组合注解及多个路径可以访问同一个接口
* @param id
* @return
*/
@GetMapping({"/getUserId","/sayhi"})
//@RequestMapping(value = "/getMyId", method = RequestMethod.GET)
public String getUserId(@RequestParam(value = "id",required = false,defaultValue = "0") Integer id) {
return "getMyId: \t"+id;
}