【发布时间】:2019-03-19 19:01:25
【问题描述】:
我的 Spring Boot 应用程序带有映射到 /api 的 REST API。我需要在/ 上定义额外的servlet。我希望与 /api 匹配的所有请求都由 REST API 处理,而所有其他请求都由 servlet 处理。如何做到这一点?
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping
public String get() {
return "api";
}
}
@Bean
public ServletRegistrationBean customServletBean() {
return new ServletRegistrationBean<>(new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().println("custom");
}
}, "/*");
}
}
在上面的代码中,我想要这样的东西:
curl http://localhost:8080/api/
> api⏎
curl http://localhost:8080/custom/
> custom
我尝试使用过滤器重定向请求,但所有请求都转到自定义 servlet:
@Bean
public FilterRegistrationBean apiResolverFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter((req, response, chain) -> {
HttpServletRequest request = (HttpServletRequest) req;
String path = request.getRequestURI().substring(request.getContextPath().length());
if (path.startsWith("/api/")) {
request.getRequestDispatcher(path).forward(request, response);
} else {
chain.doFilter(request, response);
}
});
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
此项目在 github 上可用:https://github.com/mariuszs/nestedweb
【问题讨论】:
-
看看这个帖子 stackoverflow.com/questions/3125296/…>
-
@Gro 我试过了,这不起作用(或者我不知道如何使用它)
-
那行不通。
DispatcherServlet映射到/注册另一个将破坏DispatcherServlet。为什么它需要是一个 servlet,为什么不只是一个普通的控制器?你想达到什么目的? -
@M.Deinum 我需要使用来自外部库 (GitHttpServlet) 的现有 servlet
-
不破坏
DispatcherServlet。您可以尝试使用ServletWrappingController,使其位于DispatcherServlet后面。
标签: java spring spring-boot servlets