Spring MVC控制器重定向外部URL失败:解决路径错误引发的500异常
解决短链接重定向到本地域名的问题
这个问题我之前也碰到过,核心原因是RedirectView默认会把不带协议的链接当成相对路径,所以你返回的www.google.com会被Spring自动拼上当前应用的域名localhost:8080,变成localhost:8080/www.google.com,自然会出现500错误。
问题分析
当你返回的目标URL没有包含http://或https://协议前缀时,Spring会认为这是一个应用内的相对路径,会自动拼接当前请求的域名和上下文路径,最终生成错误的重定向地址。
解决方案
你只需要确保重定向的目标是完整的绝对URL(带协议前缀),有两种可靠的实现方式:
1. 代码中补全协议前缀
如果数据库中存储的原始长链接没有协议(比如只有www.google.com),可以在代码里判断并补全:
@RequestMapping(value="/{url}", method = RequestMethod.GET) public RedirectView getLongURl(@PathVariable("url") String url) { String original = database.getLongUrl(UrlShortener.decode(url)); // 检查链接是否包含协议前缀,没有则添加https(或根据需求用http) if (!original.startsWith("http://") && !original.startsWith("https://")) { original = "https://" + original; } RedirectView redirectView = new RedirectView(); redirectView.setUrl(original); return redirectView; }
2. 数据库存储完整绝对URL
更推荐的方式是在数据库中直接存储带协议的完整URL(比如https://www.google.com),这样代码不需要额外处理,直接返回即可:
@RequestMapping(value="/{url}", method = RequestMethod.GET) public RedirectView getLongURl(@PathVariable("url") String url) { // 数据库直接返回带协议的完整链接 String original = database.getLongUrl(UrlShortener.decode(url)); return new RedirectView(original); }
额外小技巧
如果你习惯用"redirect:"前缀的字符串返回方式,同样要保证目标是完整绝对URL:
@RequestMapping(value="/{url}", method = RequestMethod.GET) public String getLongURl(@PathVariable("url") String url) { String original = database.getLongUrl(UrlShortener.decode(url)); if (!original.startsWith("http://") && !original.startsWith("https://")) { original = "https://" + original; } return "redirect:" + original; }
这样修改后,重定向就会直接跳转到目标网站,不会再拼接本地域名啦~
内容的提问来源于stack exchange,提问作者skmangalam
相关产品推荐
相关产品推荐

