如何在Struts1和Spring中实现旧站到新站的URL重定向?
用Struts或Spring实现旧站URL到新站的重定向
基于Struts 2的实现方式
全局路径重定向(适配所有旧路径)
在struts.xml里定义全局重定向结果,搭配通配符action匹配所有请求:
<struts> <package name="old-site-redirect" namespace="/" extends="struts-default"> <global-results> <result name="redirect-new" type="redirect"> <param name="location">https://my_new_site${requestURI}</param> <param name="parse">true</param> </result> </global-results> <action name="*"> <result name="success" type="redirect-new"> <param name="requestURI">/${1}</param> </result> </action> </package> </struts>
这个配置会把旧站的任意路径https://my_old_site/xxx直接重定向到https://my_new_site/xxx,${requestURI}会自动捕获请求的路径部分。
特定路径精确重定向
如果只需要重定向个别路径,单独配置对应action即可:
<struts> <package name="specific-redirect" namespace="/" extends="struts-default"> <action name="a_section_of_the_website"> <result type="redirect">https://my_new_site/a_section_of_the_website</result> </action> </package> </struts>
基于Spring MVC的实现方式
配置类方式(推荐)
创建配置类实现WebMvcConfigurer,通过addViewControllers批量设置重定向规则:
@Configuration public class RedirectConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { // **匹配任意子路径,$0代表完整匹配路径,保留原查询参数 registry.addRedirectViewController("/**", "https://my_new_site$0") .setKeepQueryParams(true); } }
控制器动态处理
如果需要加额外逻辑(比如过滤特定路径),可以写一个通用控制器:
@Controller public class OldSiteRedirectController { @RequestMapping("/**") public String redirect(HttpServletRequest request) { String path = request.getRequestURI(); return "redirect:https://my_new_site" + path; } }
XML配置方式(传统项目)
在spring-servlet.xml里添加视图控制器配置:
<mvc:view-controller path="/**" view-name="redirect:https://my_new_site$0"/>
内容的提问来源于stack exchange,提问作者MinionAttack
相关产品推荐
相关产品推荐

