简体   繁体   English

如何在签名中没有 RedirectAttributes 的方法中访问 RedirectAttributes?

[英]How can I access RedirectAttributes in a method without RedirectAttributes in its signature?

In a Spring Boot controller, is it possible to access RedirectAttributes in a method without RedirectAttributes in its signature?在 Spring Boot 控制器中,是否可以在签名中没有RedirectAttributes的方法中访问RedirectAttributes In other words, can it be accessed from the framework as a "bean" or context variable?换句话说,它可以作为“bean”或上下文变量从框架中访问吗?

My motivation for doing this is to be able to refactor several request mapping methods (à la Clean Code ) to move exception handling out of those methods.我这样做的动机是能够重构几个请求映射方法(à la Clean Code )以将异常处理移出这些方法。 So, for example, I have several methods with a catch block like this:因此,例如,我有几个带有catch块的方法,如下所示:

    @GetMapping("/security/user/{uid}")
    public String showEditUserForm(@PathVariable("uid") String uid, Model model, RedirectAttributes redirectAttributes) {
        try {
            model.addAttribute("userAccount", userAccountService.findByUsername(uid));
            return "/security/edituser";
        } catch(UserDoesntExistException e) {
            redirectAttributes.addFlashAttribute("flashstatus","danger");
            redirectAttributes.addFlashAttribute("flashmessage","User doesn't exist");
            return "redirect:/security";
        }
    }

Instead, I'd like to do something like this:相反,我想做这样的事情:

    @GetMapping("/security/user/{uid}")
    public String showEditUserForm(@PathVariable("uid") String uid, Model model) {
        try {
            model.addAttribute("userAccount", userAccountService.findByUsername(uid));
            return "/security/edituser";
        } catch(UserDoesntExistException e) {
            return redirectWithMessage("danger","User doesn't exist");
        }
    }

    // and several other mappings that also call redirectWithMessage()

    public String redirectWithMessage(String status, String message) {
        // obtain RedirectAttributes somehow!
        redirectAttributes.addFlashAttribute("flashstatus",status);
        redirectAttributes.addFlashAttribute("flashmessage",message);
        return "redirect:/security";
    }

So the question is, how can the utility method (" redirectWithMessage ") obtain a pointer to RedirectAttributes without every method in the class having to have it in its signature and pass it along via injection?所以问题是,实用程序方法(“ redirectWithMessage ”)如何获得指向RedirectAttributes的指针,而类中的每个方法都必须在其签名中包含它并通过注入传递它?

You have a couple of ways with RequestContextUtils :您有几种使用RequestContextUtils的方法:

  1. Call RequestContextUtils#getOutputFlashMap to get access to the flash map and update them (attributes + target redirect)调用RequestContextUtils#getOutputFlashMap来访问 flash map 并更新它们(属性 + 目标重定向)

  2. Call convenient method RequestContextUtils#saveOutputFlashMap调用方便的方法RequestContextUtils#saveOutputFlashMap

  3. You can get instance of FlashMapManager您可以获得FlashMapManager实例

Invoke this method to write flash attributes:调用此方法写入 flash 属性:

Save the given FlashMap, in some underlying storage and set the start of its expiration period.将给定的 FlashMap 保存在一些底层存储中,并设置其到期时间的开始。 NOTE: Invoke this method prior to a redirect in order to allow saving the FlashMap in the HTTP session or in a response cookie before the response is committed.注意:在重定向之前调用此方法,以允许在提交响应之前将 FlashMap 保存在 HTTP 会话或响应 cookie 中。

void saveOutputFlashMap(FlashMap flashMap, HttpServletRequest request, HttpServletResponse response)

You can gain access to current request/response by @Autowire them into the bean.您可以通过@Autowire将当前请求/响应访问到 bean 中。

For your usecase, stick with #1 is OK (just add the attributes, the redirect location is set on your return string already)对于您的用例,坚持 #1 就可以了(只需添加属性,重定向位置已经在您的返回字符串上设置)

Example:例子:

@Autowired
HttpServletRequest request;

public String redirectWithMessage(String status, String message) {
   FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);

   flashMap.put("flashstatus",status);
   flashMap.put("flashmessage",message);

   return "redirect:/security";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM