一、Springboot整合Servlet
第一种方案:
-
1、创建一个自定义的servlet,继承HttpServlet添加@WebServlet注解
-
以前ssm中的web.xml配置文件中的servlet>
<servlet><servlet-name>FirstServlet</servlet-name><servlet-class>com.gblfy.servlet.FirstServlet</servlet-class>
</servlet><servlet-mapping><servlet-name>FirstServlet</servlet-name><url-patten>/first</url-patten>
</servlet-mapping>
- Spring Boot 实现方式
/*** @author gblfy* @ClassNme FirstServlet* @Description SpringBoot整合Servlet 方式1* @Date 2019/2/19 14:49* @version1.0*/
@WebServlet(name = "FirstServlet",urlPatterns = "/first")
public class FirstServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
}
- 2、在启动类中添加注解
/**- SpringBoot整合Servlet 方式1*/
@SpringBootApplication
@ServletComponentScan//在springboot启动时会扫描@WebServlet注解,并将该类实例化
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
- 3、为了便于显示,在servlet中添加输出语句
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("FirstServlet启动........");}
- 4、浏览器访问:http://localhost:8080/first
- 5、查看控制台
第二种方案:
-
通过方法完成servlet组建的注册
-
1、编写一个自定义servlet
- 以前ssm中的web.xml配置文件中的servlet
<servlet><servlet-name>FirstServlet</servlet-name><servlet-class>com.gblfy.servlet.FirstServlet</servlet-class>
</servlet><servlet-mapping><servlet-name>FirstServlet</servlet-name><url-patten>/first</url-patten>
</servlet-mapping>
- Spring Boot 实现方式
/*** @author gblfy* @ClassNme FirstServlet* @Description SpringBoot整合Servlet 方式2* @Date 2019/2/19 14:49* @version1.0*/
public class SecondServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("SecondServlet启动........");}
}
- 2、编写启动类,添加一个方法,通过@Bean注解注入bean
/*** SpringBoot整合Servlet 方式2*/
@SpringBootApplication
@ServletComponentScan
public class SpringBootChapter3Application2 {public static void main(String[] args) {SpringApplication.run(SpringBootChapter3Application2.class, args);}@Beanpublic ServletRegistrationBean getServletRegistrationBean(){ServletRegistrationBean bean =new ServletRegistrationBean(new SecondServlet());bean.addUrlMappings("/second");return bean;}
}
- 3、浏览器访问验证:http://localhost:8080/second
- 4、查看控制台输出
本文源码下载:
github地址:
https://github.com/gb-heima/Spring-Boot-Actual-Combat/tree/master/parent/spring-boot-chapter-3