SpringBoot整合Servelt

1.1通过注解扫描完成servlet组件的注册

编写servlet

1
2
3
4
5
6
7
@WebServlet(name="FirstServlet",urlPatterns="/first")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("FirstServlet............");
}
}

编写启动类

1
2
3
4
5
6
7
@SpringBootApplication
@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

1.2 通过方法完成Servlet组件的注册

编写servlet

1
2
3
4
5
6
7
public class SecondServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("SecondServlet..........");
}
}

编写启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Bean
public ServletRegistrationBean<?> getServletRegistrationBean(){
ServletRegistrationBean<?> bean = new ServletRegistrationBean<SecondServlet>(new SecondServlet());
bean.addUrlMappings("/second");
return bean;
}
}