我有一个Spring MVC Controller,其处理程序如下:
@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到帐户/登录(相同的URL)。我希望在验证后,我将用户重定向到我的应用程序的主页,以便他在地址栏中看到www.mywebappexample.com
而不是www.mywebappexample.com/account/login
。当我从登录方法返回字符串时,它呈现正确的html但我没有我想要显示的URL。我该如何重定向?
编辑:我必须在控制器前面使用redirect:
返回字符串。如果您有一个子类UrlBasedViewResolver UrlBasedViewResolver的视图解析器,则此方法有效。 Thymeleaf的视图解析器不会这样做,但确实有行为 - > ThymeleafViewResolver。这是我的servlet-context.xml(我使用的是thymeleaf):
<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>
答案 0 :(得分:6)
您可以在标签中使用重定向,而不是在浏览器窗口中更新网址:
return "redirect:home";
答案 1 :(得分:0)
检查身份验证是否成功通过,然后使用请求调度程序转发请求
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);