SpringMVC注解使用

本文详细介绍了Spring MVC中如何使用@PathVariable、@RequestParam、@RequestHeader及@CookieValue注解进行参数绑定,并提供了异常处理的方法。

@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 都会 执行此方法 并且将 bigseasea 作为参数 传递到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;
}
}

转载于:https://www.cnblogs.com/websongt/p/7833005.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值