有些老项目还在使用原始的Http Servlet或是struts2, 而新功能都期望使用spring, 而spring已经不使用web.xml配置了. 折中的解决方法:
整合struts2
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public FilterRegistrationBean registration() {
//web.xml中的struts filter移到代码中
StrutsPrepareAndExecuteFilter filter = new StrutsPrepareAndExecuteFilter();
FilterRegistrationBean<StrutsPrepareAndExecuteFilter> registration =
new FilterRegistrationBean<>(filter);
registration.addUrlPatterns("/test/*");
registration.addInitParameter("config", "struts-default.xml,struts2/struts-test.xml");
return registration;
}
}
兼容原始的Servlet
public class MyServlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().write("hello servlet1");
}
}
public class MyServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().write("hello servlet2");
}
}
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public ServletRegistrationBean<HttpServlet> helloServlet1() {
ServletRegistrationBean<HttpServlet> servRegBean = new ServletRegistrationBean<>();
servRegBean.setServlet(new MyServlet1());
servRegBean.addUrlMappings("/servlet1");
return servRegBean;
}
@Bean
public ServletRegistrationBean<HttpServlet> helloServlet2() {
ServletRegistrationBean<HttpServlet> servRegBean = new ServletRegistrationBean<>();
servRegBean.setServlet(new MyServlet2