Spring MVC 学习笔记 七 controller中其他可用的annotation

本文介绍如何在Spring MVC中使用@InitBinder注解实现自定义的数据绑定,包括日期类型的转换,以及如何通过@ExceptionHandler处理控制器中的异常。

@InitBinder
  在controller中注册一个customer protperty editor以解析request中的参数并通过date bind机制与handler method中的参数做绑定。

 
    @InitBinder
    public void initBinder(WebDataBinder binder) {
       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
       dateFormat.setLenient(false);
       binder.registerCustomEditor(Date.class, new CustomDateEditor(
              dateFormat, false));
    }

 Handler method代码如下

   @RequestMapping("/databind1")
    public ModelAndView databind1(Date date) {
      …   
   }

 访问url http://localhost:8080/springmvc/databind1.action?date=2000-01-02
通过initbinder中注册的customeDateEditor类型,自动将2000-01-02转换为日期类型

@ResponseStatus
返回一个指定的http response状态码。

    @ResponseStatus(reason="no reason",value=HttpStatus.BAD_REQUEST)
    @RequestMapping("/responsestatus")
    public void responseStatusTest(){
      
    }

 

将返回 Http error 400.

@SessionAttributes
  相当于以前的requiresSession属性,当配置此属性时,handler method中对应的参数将从session中获取,如果不存在则抛出SessionRequiredException,与之前提到的SessionStatus. setComplete ()一起使用,可起到避免提及成功后按刷新键重复提交的情况。
@ExceptionHandler

  
   @RequestMapping("/exception")
    public void ExceptionTest() throws Exception{
       throw new Exception("i don't know");
    }  
    @ExceptionHandler
    public String handleException(Exception e,HttpServletRequest request){
       System.out.println(e.getMessage());
       return "helloworld";
    }

 其中/exception抛出一个异常,而handleException则抓到这个异常并进行处理

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值