4

我有一个带有如下处理程序的 Spring MVC 控制器:

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


@RequestMapping(value = "/account/login", method = RequestMethod.POST, params = "login")
public String login(@RequestParam(value = "username") String username, 
        @RequestParam(value = "password") String password) {

    // do authentication
    return "home";
}

login.html 页面中的表单 POST 到 account/login(相同的 url)。我希望在身份验证之后,我将用户重定向到我的应用程序的主页,以便他www.mywebappexample.com在地址栏中看到而不是www.mywebappexample.com/account/login. 当我从登录方法返回字符串时,它会呈现正确的 html,但我没有要显示的 URL。我该如何重定向?

编辑:我必须在我的控制器返回字符串前加上redirect:. 如果您有一个子类 UrlBasedViewResolver UrlBasedViewResolver的视图解析器,则此方法有效。Thymeleaf 的视图解析器没有这样做,但它确实具有行为 -> ThymeleafViewResolver。这是我的 servlet-context.xml(我使用的是百里香):

<bean id="templateResolver"
      class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
    <property name="prefix" value="/WEB-INF/"/>
    <property name="suffix" value=".html"/>
    <property name="templateMode" value="HTML5"/>
</bean>

<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver"/>
</bean>

<bean id="viewResolver" class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine"/>
    <property name="order" value="1"/>
</bean>
4

2 回答 2

7

您可以在标签中使用重定向,而不是在浏览器窗口中更新 URL:

return "redirect:home";
于 2012-12-28T23:50:32.263 回答
0

检查身份验证是否成功,然后使用请求调度程序转发请求

RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
 rd.forward(request, response);
于 2012-12-28T23:52:35.343 回答