java 登录后Spring MVC控制器重定向到某个URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14077190/
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
Spring MVC controller redirect to some URL after login
提问by Sotirios Delimanolis
I have a Spring MVC Controller with handlers like so:
我有一个带有如下处理程序的 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";
}
The form in the login.html page POSTs to account/login (the same url). I'd like that after the authentication, I redirect the user to the home page of my application, so that he sees www.mywebappexample.com
in address bar instead of www.mywebappexample.com/account/login
. When I return the string from the login method, it renders the proper html but I don't have the URL I want to show. How can I redirect?
login.html 页面中的表单发布到 account/login(相同的 url)。我希望在身份验证后,我将用户重定向到我的应用程序的主页,以便他www.mywebappexample.com
在地址栏中看到而不是www.mywebappexample.com/account/login
. 当我从登录方法返回字符串时,它会呈现正确的 html,但我没有想要显示的 URL。如何重定向?
Edit:I had to prefix my controller return String with redirect:
. This works if you have a view resolver that subclasses UrlBasedViewResolver UrlBasedViewResolver. Thymeleaf's view resolver doesn't do that but it does have the behavior -> ThymeleafViewResolver. Here's my servlet-context.xml (I'm using thymeleaf):
编辑:我必须在我的控制器返回字符串前加上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>
回答by Reimeus
You can use a redirect in the tag instead which should update the URL in the browser window:
您可以在标签中使用重定向来代替它应该更新浏览器窗口中的 URL:
return "redirect:home";
回答by Scoota P
Check if the authentication passed successfully and then forward the request with the request dispatcher
检查身份验证是否成功,然后将请求转发给请求调度器
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);