我的控制器类中有一些重定向代码,我想重构。这些代码只是检查对象是否为空,如果是...它会将其重定向到特定页面。
以下是代码的一部分:
@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");
}
...
}
我想重构空检查并重定向到一个单独的类,但我不确定如何在控制器中调用它并将重定向到指定页面。
检查控制器中是否存在变量是可以的。您可以使用 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;
}
}