我在我想要重构的Controller类中有一些重定向代码。 这些代码只是检查一个对象是否为空,如果它是......它会将它重定向到一个特定的页面。
以下是代码的一部分:
@RequestMapping(value = "/user-details", method = RequestMethod.GET)
public ModelAndView userDetails(@RequestParam("id") int id) {
...
User user = userService.getUserById(id);
if (matter == null) {
return new ModelAndView("redirect:/users-list.html");
}
...
}
@RequestMapping(value = "/user-application-details", method = RequestMethod.GET)
public ModelAndView userApplicationDetails(@RequestParam("applicationId") int applicationId) {
...
UserApplication application = userApplicationService.getApplicationById(applicationId);
if (application == null) {
return new ModelAndView("redirect:/users-list.html");
}
...
}
@RequestMapping(value = "/user-activity-details", method = RequestMethod.GET)
public ModelAndView userActivityDetails(@RequestParam("activityId") int activityId) {
...
UserActivity activity = userActivityService.getActivityById(activityId);
if (activity == null) {
return new ModelAndView("redirect:/users-list.html");
}
...
}
我想重构null检查和重定向到一个单独的类,但我不知道如何在控制器内调用它并将重定向到指定的页面。
答案 0 :(得分:1)
检查控制器内是否存在变量 是可以的。您可以使用Java 8 Optional
API改进语法。
您可以做的是将异常处理移动到单独的类中。 Spring为此用例提供了一个特殊的组件注释:@ControllerAdvice
伴随着@ExceptionHandler
方法。这确实需要你抛出异常。
有关示例,请参阅:
@Controller
public class SampleController {
@RequestMapping(value = "/user-details", method = RequestMethod.GET)
public ModelAndView userDetails(@RequestParam("id") int id) {
...
Optional<User> userOptional = userService.getUserById(id);
User user = userOptional.orElseThrow(() -> new UserNotFoundException("message here"));
...
}
}
@ControllerAdvice
public class SampleControllerAdvice {
private static final String REDIRECT_USER_LIST = "redirect:/users-list.html";
@ExceptionHandler
public String handleUserNotFound(UserNotFoundException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
return REDIRECT_USER_LIST;
}
@ExceptionHandler
public String handleUserActivityNotFound(UserActivityNotFoundException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
return REDIRECT_USER_LIST;
}
}