控制器建言可以设置控制器的全局配置,即用@ControllerAdvice注解的类中的方法,可为Controller的建言。可以通过设置@ControllerAdvice的属性选择对全部或部分Controller进行设置。@ControllerAdvice和@ExceptionHandler、@InitBinder、@ModelAttribute配合使用。
@ExceptionHandler:用于处理Controller出现的错误,其注解的Method的MethodSignature是flexible的。
@InitBinder:用于设置WebDataBinder,后者用于将请求参数绑定到Model中,可对请求参数在Model中使用进行设置。
@ModelAttribute:用于为Model添加属性,在Controller中的@RequestMapping注解的方法中,可以通过在方法参数前使用@ModelAttribute获取相应属性。
示例:
1. @ControllerAdvice
package com.controllerAdvice;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice // 为Controller添加建言,可配置Controller selectors
public class DemoControllerAdvice {
/**异常处理,该注解下的MethodSignature can be flexible
* @param exception
* @param request
* @return
*/
@ExceptionHandler(value = Exception.class)
public ModelAndView exception(Exception exception, WebRequest request) {
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("errorMessage", exception.getMessage());
return modelAndView;
}
/** 设置请求数据绑定WebDataBinder
* @param dataBinder
*/
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id"); // 设置不能将id请求参数绑定到Model中
}
/** 为Model添加键值对
* @param model
*/
@ModelAttribute
public void modelAttribute(Model model) {
model.addAttribute("msg", "额外信息");
}
}
2. Controller
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.object.DemoObj;
@Controller
public class AdviceController {
@RequestMapping("/advice")
public String getAdviceJsp(DemoObj obj, @ModelAttribute("msg") String msg) {
throw new IllegalArgumentException(
"Sorry, some argument is wrong, which comes from @ModelAttribute: " + msg);
}
}
3. Result
explore地址栏:http://localhost:8080/com-springmvc/advice?id=1&name=xx
1、通过调试,可看到
DemoObj的id = null,name=xx,成功过滤了id参数
2、最后显示页面为:
error.jsp
Sorry, some argument is wrong, which comes from @ModelAttribute: 额外信息