spring boot 整合servlet
1.pom文件和其中需要添加的依赖
1.1.maven jar项目指定父类的坐标 jdk版本要指定,因为需要与父类依赖的jdk版本一致
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<!-- jdk1.7 -->
<properties>
<java.version>1.7</java.version>
</properties>
1.2 需要依赖的启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.spring-boot 整合servlet的方式
servlet 原生的方式是配置web.xml文件。现在没有web.xml文件了。可以用两种方式配置servlet
2.1配置的方式配置在spring-boot的启动类中
自定义的FirstServlet类继承Servlet类。实现doGet或者doPost方法
在spring-boot的启动类中除了main方法外还需要一个返回ServletRegistrationBean 的方法,在方法中注册自定义的Servlet类和MappingUrl。
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Bean
public ServletRegistrationBean getFirstServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(
new FirstServlet());
bean.addUrlMappings("/first");
return bean;
}
@Bean
public ServletRegistrationBean getFirst2Servlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(
new First2Servlet());
bean.addUrlMappings("/first2");
return bean;
}
}
2.2基于注解的方式
自定义servlet类中和spring-boot启动类中各添加一条注解即可
@SpringBootApplication
@ServletComponentScan // //在springBoot启动时会扫描@WebServlet,并将该类实例化
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
// 自定义Servlet类中添加的注解
@WebServlet(name="SecondServlet",urlPatterns="/second")
public class SecondServlet extends HttpServlet {
以上是spring-boot集成servlet的方式。
可以同时使用两种方式。
总结:方式一对每个servlet在spring-boot中添加一个方法,该方法返回SrvletRegistrationBean的方法,该方法被@bean注解。
方式二更为简单,对Servlet和Spring-boot的启动类各添加条注解即可。