目录:
- @EnableWebMvc
- @Controller
- @RequestMapping
- @ResponseBody
- @RequestBody
- @PathVariable
- @RestController
- @ControllerAdvice
- @ExceptionHandler
- @InitBinder
- @ModelAttribute
- @RequestMapping
- @ExceptionHandler
- @InitBinder
- @ModelAttribute
相关注解:
(1)@EnableWebMvc 在配置类中开启Web MVC的配置支持,如一些ViewResolver或者MessageConverter等,若无此句,重写WebMvcConfigurerAdapter方法(用于对SpringMVC的配置)。
@Configuration
@ComponentScan("com.my")
@EnableWebMvc
public class MyWebConfig extends WebMvcConfigurerAdapter {
/**
* 配置JSP视图解析器
* 如果没有配置视图解析器。Spring会使用BeanNameViewResolver,通过查找ID与逻辑视图名称匹配且实现了View接口的beans
* @return
*/
@Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver ();
/**设置视图路径的前缀*/
resolver.setPrefix("/WEB-INF/");
/**设置视图路径的后缀*/
resolver.setSuffix(".jsp");
return resolver;
}
}
(2)@Controller 声明该类为SpringMVC中的Controller
@RequestMapping("/v1")
@Controller
@Slf4j
public class OcppController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private DeviceService deviceService;
.......
}
(3)@RequestMapping 用于映射Web请求,包括访问路径和参数(类或方法上)
(4)@ResponseBody 支持将返回值放在response内,而不是一个页面,通常用户返回json数据(返回值旁或方法上)
@RequestMapping("/v1")
@ResponseBody
public String userProfile(@PathVariable String username){
return "user" + username;
}
(5)@RequestBody 允许request的参数在request体中,而不是在直接连接在地址后面。(放在参数前)
@HystrixCommand(fallbackMethod = "defaultRemoteStartTransaction")
@RequestMapping(value = "/remoteStartTransaction", method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<ResponseVo> remoteStartTransaction(
@RequestBody
com.chargedot.ocppservice.controller.request.RemoteStartTransactionRequest paramVo) {
log.info("[remoteStartTransaction][param]{}", paramVo);
RemoteStartTransactionRspVo response = new RemoteStartTransactionRspVo();
......
}
(6)@PathVariable 用于接收路径参数,比如@RequestMapping(“/hello/{name}”)申明的路径,将注解放在参数中前,即可获取该值,通常作为Restful的接口实现方法。
@RequestMapping("/hello/{name}")
@ResponseBody
public String userProfile(@PathVariable String username){
return "user" + username;
}
(7)@RestController 该注解为一个组合注解,相当于@Controller和@ResponseBody的组合,注解在类上,意味着,该Controller的所有方法都默认加上了@ResponseBody。
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
类似:
@Controller
@ResponseBody
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
(8)@ControllerAdvice 通过该注解,我们可以将对于控制器的全局配置放置在同一个位置,注解了@Controller的类的方法可使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上,对所有注解了 @RequestMapping的控制器内的方法有效。
(9)@ExceptionHandler 用于全局处理控制器里的异常
(10)@InitBinder 用来设置WebDataBinder,WebDataBinder用来自动绑定前台请求参数到Model中。
(11)@ModelAttribute 本来的作用是绑定键值对到Model里,在@ControllerAdvice中是让全局的@RequestMapping都能获得在此处设置的键值对。