1

I have a controller as

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

 }
}

Is it possible to create ControllerAdvice(s) to handle the controller method as different result without moving these to message to different classes. I mean: 1. test1 returns a String message: if there is exception, handle it with handleError1 and return a message. 2. test1 returns a view : if there is exception, handle it with handleError2 and return/redirect to a view.

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

}

}

if use @ControllerAdvice(annotations=RestController.class) @ControllerAdvice(annotations=Controller.class)

We need to create more controllers.

4

0 回答 0