spring mvc如何处理responsebody和view Exception?

spring mvc如何处理responsebody和view Exception?,spring,spring-mvc,controller,exceptionhandler,Spring,Spring Mvc,Controller,Exceptionhandler,我有一个控制器 @Controller @RequestMapping("/test") public class TestController { @RequestMapping("/1") @ResponseBody public String test1(){ Object o = null; o.toString(); return "I ma test one!"; } @RequestMapping("/2") public String test2

我有一个控制器

@Controller
@RequestMapping("/test")
public class TestController {


@RequestMapping("/1")
@ResponseBody
public String test1(){
    Object o = null;
    o.toString();

    return "I ma test one!";
}


@RequestMapping("/2")
public String test2(){
    Object o = null;
    o.toString();               
    return "test";

 }
}
是否可以创建ControllerAdvice以将控制器方法作为不同的结果处理,而无需将它们移动到消息中的不同类。 我的意思是: 1.test1返回一条字符串消息:如果存在异常,则使用handleError1处理它并返回一条消息。 2.test1返回一个视图:如果有异常,用handleError2处理它,并返回/重定向到一个视图

@ControllerAdvice
public class AdviceController {

@ExceptionHandler({ NullPointerException.class })
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Map handleError1(IllegalStateException ex, HttpServletRequest request) {
    Map map = new HashMap();
    map.put("code","1000");
    map.put("message","NullPointerException of Object");
    return map;
}


@ExceptionHandler(NullPointerException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public String handleError2(MultipartException e, RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
      redirectAttributes.addFlashAttribute("code", "1000");
    return "redirect:/error";

}

}
如果使用 @ControllerAdvice(annotations=RestController.class) @ControllerAdvice(注释=Controller.class)

我们需要创建更多控制器