覆盖SpringMVC应用程序中的默认重定向URL [英] Override the default redirect URL in a SpringMVC application
问题描述
我有一个简单的Spring MVC应用程序,它将在某些控制器操作后将用户重定向到新页面.例如:
I have a simple Spring MVC application that will redirect the user to a new page after certain controller actions. For example:
@Controller
public class ResponseController {
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveObj(HttpServletRequest request, @ModelAttribute("someObject") Object obj) {
// logic to validate and save object
return "redirect:/obj/" + id;
}
}
这个Spring MVC应用程序在其他几个实例的负载均衡器后面运行.每个都有自己的主机名.负载平衡器配置了SSL,而实例未配置.
This Spring MVC application is running behind a loadbalancer with several other instances. Each have their own hostname. The loadbalancer is configured with SSL and the instances are not.
我想知道的是重写默认重定向行为的最佳实践.当前,该应用程序以 https://mysite.com 开头,但是在用户执行需要重定向的操作后,应用程序会将用户重定向到 http://some.hostnameX.com .
What I would like to know is the best practice to override the default redirect behavior. Currently, the application starts with https://mysite.com, but after a user performs an action that requires a redirect, the application redirects the user to http://some.hostnameX.com.
当前,我有一个用于帮助将用户重定向到mysite.com的属性.
Currently, I have a property that is used to help redirect the user to mysite.com.
loadbalancer.url=https://mysite.com
然后,在控制器中,我有以下内容:
Then, in the controller, I have the following:
@Value("loadbalancer.url")
String loadbalanerUrl;
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveObj(HttpServletRequest request, @ModelAttribute("someObject") Object obj){
// logic to validate and save object
return "redirect:" + loadbalancerUrl + "/obj/" + id;
}
是否有更好的方法来替代此行为?
Is there a better way to override this behavior?
推荐答案
可以在org.springframework.web.servlet.view.UrlBasedViewResolver
中找到重定向行为.您可以通过扩展任何子类或类本身并将其添加到应用程序上下文中来轻松更改此行为.
The redirect behavior can be found in org.springframework.web.servlet.view.UrlBasedViewResolver
. You can easily alter this behavior by extending any subclass or the class itself and add it to the application context.
例如,您可以编写一个特殊条件,该条件将在重定向视图名称中添加url.它将无需手动进行操作.
You could for example write a special condition that will prepend the url in a redirect view name. It will eliminate the need to do it manually.
public class CustomUrlBasedViewResolver extends UrlBasedViewResolver {
@Value("${loadbalancer.url}")
private String loadBalancerUrl;
@Override
protected View createView(String viewName, Locale locale) throws Exception {
if (viewName.startsWith(super.REDIRECT_URL_PREFIX)) {
String url = viewName.substring(REDIRECT_URL_PREFIX.length());
String loadBalancedViewName = super.REDIRECT_URL_PREFIX + loadBalancerUrl + url;
return super.createView(loadBalancedViewName, locale);
}
return super.createView(viewName, locale);
}
}
这篇关于覆盖SpringMVC应用程序中的默认重定向URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!