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

@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则抓到这个异常并进行处理

猜你喜欢

转载自starscream.iteye.com/blog/1066712