【问题标题】:How to redirect to a view in Spring MVC如何重定向到 Spring MVC 中的视图
【发布时间】:2018-06-15 12:05:04
【问题描述】:

我试图从 spring 项目的主页重定向到另一个视图,但即使我检查了大多数在线资源并且完全按照我显示的那样做,我还是得到了 404。谁能帮我吗?

代码如下:

控制器:

@RequestMapping(value = "/redirect")
public ModelAndView redirect(){

   return new ModelAndView(new RedirectView("check"));

}

dispathcher-servlet.xml:

<bean class="mine.Controllers.MainController" name="mainController" lazy-init="false" ></bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="resolver">
    <property name="suffix" value=".jsp"></property>
    <property name="prefix" value="/WEB-INF/Views/"></property>
    <property name="order" value="1"></property>
</bean>

index.jsp:

<html>
<head>
   <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Click <a href="/redirect">here</a></p>
</body>
</html>

这是我的项目结构的截图:https://imgur.com/a/RSf6Wsr

【问题讨论】:

    标签: java spring-mvc jsp model-view-controller


    【解决方案1】:

    RedirectView 类构造函数参数是“URL”而不是“视图名称”

    为了让它工作你的例子在你的控制器中添加这个代码

    @RequestMapping(value = "check")
    public ModelAndView check(){
    
    return new ModelAndView("check");
    
    }
    

    并将重定向方法代码更改为此

    @RequestMapping(value = "/redirect")
    public RedirectView redirect(){
    
    return new RedirectView("check");
    
    }
    

    【讨论】:

    • 我让 ,,check" 作为参数,因为那是我最后一次尝试。我试过 check.jsp 、 /check.jsp 、 /check 、 /Views/check.jsp 和 /查看/检查。您能告诉我,根据我的项目结构,正确的 url 是什么,这样我就可以用那个确切的 url 再试一次?
    • 只需添加我发布的代码,尝试让我知道
    • 是的,现在可以了。我的意思是,我收到关于我的 jsp 的错误,但关键是重定向有效。谢谢!
    【解决方案2】:

    您应该使用控制器方法中的"redirect:url" 重定向到另一个url,或者直接返回RedirectView。

    @RequestMapping(value = "/redirect")
    public String redirect(){
        String redirectUrl = "YOUR_URL";
        return "redirect:" + redirectUrl;
    
    }
    

    【讨论】:

    • 我尝试直接返回我用作 ModelAndView 参数的 RedirectView,当我尝试返回带有重定向前缀的字符串时,它刚刚显示在页面上
    猜你喜欢
    • 1970-01-01
    • 2019-04-25
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多