springboot与servlet整合的两种方式,整合步骤如下:
项目结构:
pom.xml:
4.0.0
com.lucifer.springboot
springboot-servlet
0.0.1-SNAPSHOT
jar
springboot-servlet
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.5.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
SpringbootServletApplication:
package com.lucifer.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* @ServletComponentScan
* 在springboot启动时会扫描@WebServlet,并将该类实例化
*/
@SpringBootApplication
@ServletComponentScan
public class SpringbootServletApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootServletApplication.class, args);
}
}
FirstServet:
启动项目,浏览器输入localhost:8080/first,
ps:整合过程中新手很容易遇坑的地方:原本我的项目结构是这样的,如下图:
这时候启动项目,控制台无报错,浏览器输入地址,404,原因就是因为com.lucifer.springboot.servlet这个包没有扫描到。
那百度了,按照百度查到的资料,加了扫描包的注解,没用,效果依然凉凉。
因此这里就把启动类放在com.lucifer.springboot包下,FirstServet就包在子包com.lucifer.springboot.servlet下,启动类的扫描默认是扫描与该启动类同包以及其子包下的类。
项目结构:
SecondServlet:
package com.lucifer.springboot.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author: Lucifer
* @create: 2018-09-19 14:39
* @description:
**/
public class SecondServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().append("springboot整合servlet成功");
}
}
SpringbootServletApplication:
package com.lucifer.springboot;
import com.lucifer.springboot.servlet.SecondServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringbootServletApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootServletApplication.class, args);
}
@Bean
public ServletRegistrationBean getservletRegistrationBean(){
ServletRegistrationBean bean=new ServletRegistrationBean(new SecondServlet());
bean.addUrlMappings("/second");
return bean;
}
}