来自拦截器的Spring MVC简单访问控制:如何显示错误

时间:2015-08-24 07:34:07

标签: spring spring-mvc

在Spring 4.2 webapp中,我在会话中有一个rights对象,我可以从中查询登录用户是否可以访问特定页面。我可以检查控制器的访问权限,并重定向到带有消息的另一个页面。问题是我必须为每个控制器中的每个请求方法重复此操作。

我几乎可以将所有代码移动到拦截器,但是我无法从那里访问RedirectAttributes,所以我不知道如何添加错误消息。有办法吗?

@Controller
@SessionAttributes("rights")
@RequestMapping("/f")
public class FController {
   ...
    @RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
    public String edit(@PathVariable("id") int id,
        @ModelAttribute("rights") UserRights rights,
        RedirectAttributes redA, ModelMap model) throws SQLException {
        if (!rights.canAccess("/f/edit")) {
            redA.addFlashAttribute("errormessage", messages.getMessage("error.noright", null, Locale.getDefault()));
            return "redirect:/f/list";
        }
        ... // set up model
        return "fEdit";
    }
 ...
 }

1 个答案:

答案 0 :(得分:1)

是的,你可以!它不像控制器方法那样集成,但您可以在拦截器中访问输出flash映射。您可以在Spring Framework ReferenceManual的Using flash attributes一章中找到相关参考。感谢ModelAndViewDefiningException,您仍然可以让Spring进行重定向并处理输出flash地图

你可以在拦截器中放置这样的东西:

    if (!rights.canAccess("/f/edit")) {
        // get access to the output flash map
        FlashMap redA = RequestContextUtils.getOutputFlashMap(HttpServletRequest request);
        // add the redirect attributes
        redA.put("errormessage", messages.getMessage("error.noright", null, Locale.getDefault()));
        // prepare the redirection
        ModelAndView redirMav = new ModelAndView("redirect:/f/list");
        // ask the spring machinery to process the redirection
        throw new ModelAndViewDefiningException(redirMav);
    }
相关问题