Java 如何在spring-mvc中传递参数以重定向页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19249049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:27:30  来源:igfitidea点击:

How to pass parameters to redirect page in spring-mvc

javaspringspring-mvc

提问by gstackoverflow

I have wrote following controller:

我写了以下控制器:

@RequestMapping(value="/logOut", method = RequestMethod.GET )
    public String logOut(Model model, RedirectAttributes redirectAttributes)  {
        redirectAttributes.addFlashAttribute("message", "success logout");
        System.out.println("/logOut");
        return "redirect:home.jsp";
    }

How to change this code that on page home.jspI can to write ${message}and to see "success logout"

如何更改页面上home.jsp我可以编写${message}和查看的代码"success logout"

采纳答案by Debojit Saikia

When the return value contains redirect:prefix, the viewResolverrecognizes this as a special indication that a redirect is needed. The rest of the view name will be treated as the redirect URL. And the client will send a new request to this redirect URL. So you need to have a handler method mapped to this URL to process the redirect request.

当返回值包含redirect:前缀时,它viewResolver会将其识别为需要重定向的特殊指示。视图名称的其余部分将被视为重定向 URL。客户端将向 this 发送一个新请求redirect URL。所以你需要有一个处理程序方法映射到这个 URL 来处理重定向请求。

You can write a handler method like this to handle the redirect request:

您可以编写这样的处理程序方法来处理重定向请求:

@RequestMapping(value="/home", method = RequestMethod.GET )
public String showHomePage()  {
    return "home";
}

And you can re-write the logOuthandler method as this:

您可以将logOut处理程序方法重写为:

@RequestMapping(value="/logOut", method = RequestMethod.POST )
public String logOut(Model model, RedirectAttributes redirectAttributes)  {
    redirectAttributes.addFlashAttribute("message", "success logout");
    System.out.println("/logOut");
    return "redirect:/home";
}

EDIT:

编辑:

You can avoid showHomePagemethod with this entry in your application config file:

您可以showHomePage在应用程序配置文件中避免使用此条目的方法:

<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
 .....
 xsi:schemaLocation="...
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 ....>

<mvc:view-controller path="/home" view-name="home" />
 ....
</beans>

This will forward a request for /hometo a view called home. This approach is suitable if there is no Java controller logic to execute before the view generates the response.

这会将请求转发/home到名为 的视图home。如果在视图生成响应之前没有要执行的 Java 控制器逻辑,则此方法适用。