Spring Boot中用Controller替代index.jsp端点的实现问题
如何用Spring Boot Controller替换被外部调用的index.jsp端点
问题背景
现有Spring Boot应用,APP/index.jsp端点被外部应用调用,无法修改该URL。计划用Controller替换原JSP文件,通过Thymeleaf返回相同数据,但@RequestMapping("index.jsp")无法触发控制器,其他后缀的请求可正常响应。
已尝试的无效操作:
- 调整JspServlet自动配置相关参数,但添加后无端点响应
- 调试验证发现
AbstractServletWebServerFactory的shouldRegisterJspServlet方法返回false,但无法在启动时设置JSP对象,也无法移除包含JspServlet的Jar包
解决方案
方案1:禁用JspServlet,让DispatcherServlet接管所有请求
Spring Boot默认会让JspServlet拦截.jsp后缀请求,导致DispatcherServlet无法处理这类请求。可以通过配置禁用JspServlet,让DispatcherServlet优先处理所有路径:
- 在
application.properties中添加配置:
# 禁用自动注册的JspServlet,避免拦截.jsp请求 server.servlet.jsp.enabled=false # 让DispatcherServlet处理所有路径的请求 spring.mvc.servlet.path=/
- 编写对应Controller:
@Controller public class IndexController { @RequestMapping("/index.jsp") public String index(Model model) { // 复制原JSP中的数据填充逻辑,比如model.addAttribute("key", "value") return "index"; // 对应Thymeleaf的index.html模板文件 } }
方案2:修改JspServlet的映射范围
如果无法完全禁用JspServlet,可以通过自定义ServletRegistrationBean缩小其拦截范围,让它不处理/index.jsp:
@Configuration public class ServletConfig { @Bean public ServletRegistrationBean<JspServlet> jspServletRegistrationBean() { ServletRegistrationBean<JspServlet> registration = new ServletRegistrationBean<>(new JspServlet()); // 仅让JspServlet处理指定路径的.jsp请求,排除/index.jsp registration.addUrlMappings("/internal/*.jsp"); registration.setLoadOnStartup(3); return registration; } }
配置完成后,/index.jsp请求会自动被DispatcherServlet转发到对应的Controller处理。
方案3:用Filter转发请求到Controller
如果以上方案都不适用,可编写Filter将/index.jsp请求转发到Controller的映射路径:
- 实现Filter:
@Component public class JspForwardFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if ("/index.jsp".equals(req.getRequestURI())) { // 转发到Controller的处理路径 req.getRequestDispatcher("/index").forward(request, response); return; } chain.doFilter(request, response); } }
- 编写对应Controller:
@Controller public class IndexController { @RequestMapping("/index") public String index(Model model) { // 数据填充逻辑 return "index"; } }
内容的提问来源于stack exchange,提问作者Felipe Issa
相关产品推荐
相关产品推荐

