【问题标题】:Spring redirect on POSTPOST 上的 Spring 重定向
【发布时间】:2017-03-30 14:14:33
【问题描述】:

这是我的更新用户方法:

@ResponseBody
@Transactional
@RequestMapping(value = "/profile/edit/{id}", method = RequestMethod.POST)
public String updateUser(@PathVariable("id") final Integer id, String firstname, String lastname, final RedirectAttributes redirectAttributes) {

    respository.updateFirstname(id,firstname);
    respository.updateLastname(id, lastname);

    redirectAttributes.addFlashAttribute("message", "Successfully changed..");
    return "redirect:/profile";
}

一切正常。还有数据库中的更新。但重定向只是一个字符串,不要更改路径。谁能告诉我为什么?

【问题讨论】:

  • 删除@ResponseBody。让你的控制器事务性也是一个糟糕的主意......你应该有一个事务性边界的服务(这样你就可以重用这些东西)。

标签: spring spring-mvc spring-security spring-boot thymeleaf


【解决方案1】:

@ResponseBody 仍然可以进行重定向。

您可以通过以下方式执行此操作,这样您仍然可以在 @ResponseBody(例如 json)中传递预期数据,并且如果某些“用例”迫使您进行重定向。同样按照建议,不要在控制器级别使用事务范围,而是在服务层上使用

@ResponseBody
@RequestMapping(value = "/profile/edit/{id}", method = RequestMethod.POST)
public String updateUser(@PathVariable("id") final Integer id, String firstname, String lastname, final RedirectAttributes redirectAttributes, HttpServletResponse response) {

    respository.updateFirstname(id,firstname);
    respository.updateLastname(id, lastname);

    if(someCondition == "redirectMe"){
       redirectAttributes.addFlashAttribute("message", "Successfully changed..");
       response.sendRedirect("/profile");
    }

 return "some_data_for_view";
}

【讨论】:

    【解决方案2】:
    @GetMapping("/abc/def")
    public void some_method(HttpServletResponse response){
    //to do
    response.sendRedirect("url");
    }
    

    【讨论】:

      【解决方案3】:

      问题出在@ResponseBody 注释中。删除后,重定向应按预期工作。通过使用它,您可以覆盖 Spring MVC 的默认行为,并将返回值视为原始响应。

      【讨论】:

        猜你喜欢
        • 2019-02-02
        • 2020-02-17
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        • 2011-06-06
        • 1970-01-01
        • 2017-09-07
        • 2013-06-22
        相关资源
        最近更新 更多