@PathVariable 注解
带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义
通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable("xxx") 绑定到操作方法的入参中。
代码示例:
/**
* localhost:8080/springmvc/hello/pathVariable/bigsea
* localhost:8080/springmvc/hello/pathVariable/sea
* 这些URL 都会 执行此方法 并且将 bigsea、sea 作为参数 传递到name字段
* @param name
* @return
*/
@RequestMapping("/pathVariable/{name}")
public String pathVariable(@PathVariable("name")String name){
System.out.println("hello "+name);
return "helloworld";
}
@RequestParam 绑定请求参数
在处理方法入参处使用 @RequestParam 可以把请求参数传递给请求方法
– value:参数名
– required:是否必须。默认为 true, 表示请求参数中必须包含对应的参数,若不存在,将抛出异常
代码示例:
@RequestMapping("/requestParam")
public String requestParam(@RequestParam(value="firstName",required=false)String firstName,
@RequestParam( value="lastName" ,required = true) String lastName,
@RequestParam(value="age",required = false ,defaultValue="0")int age) {
System.out.println("hello my name is " + (firstName == null ? "" : firstName)
+ lastName + "," + age +" years old this year");
return "helloworld";
}
@RequestHeader 获取请求头
请求头包含了若干个属性,服务器可据此获知客户端的信息,通过 @RequestHeader 即可将求头中的属性值绑定到处理方法的入参中
@RequestMapping("/requestHeader")
public String requestHeader(@RequestHeader("User-Agent")String userAgent,@RequestHeader("Cookie")String cookie){
System.out.println("userAgent:["+userAgent+"]");
System.out.println("cookie:["+cookie+"]");
return "helloworld";
}
@CookieValue 获取 cookie值
/**
* 使用@CookieValue 绑定cookie值
* 注解@CookieValue 也有 value ,required ,defaultValue 三个参数
* @param session
* @return
*/
public String cookieValue(@CookieValue(value = "JSESSIONID", required= false)String session){
System.out.println("JESSIONID:["+session+"]");
return "helloworld";
}
异常处理类
局部
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
System.out.println("in testExceptionHandler");
return mv;
}
@RequestMapping("/error")
public String error(){
int i = 5/0;
return "hello";
}
全局
@ControllerAdvice
public class testControllerAdvice {
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
System.out.println("in testControllerAdvice");
return mv;
}
}