• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
飝飝JAVA
博客园    首页    新随笔    联系   管理    订阅  订阅

SpringMVC注解使用

@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;
}
}

posted @ 2017-11-14 15:59  飝飝JAVA  阅读(124)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3