1.创建servlet
在src对应的目录下创建一个servlet,添加相关的get方法,设置@WebServlet注解,如下:
/**
-
@program: springboot-01-servlet
-
@description: SpringBoot整合servlet的第一种方式
-
@author: 波波烤鸭
-
@create: 2019-05-11 14:53
*/
@WebServlet(name = “FirstServlet”,urlPatterns = “/first”)
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("–doGet方法执行了----");
PrintWriter out = resp.getWriter();
out.write(“success”);
out.flush();
out.close();
}
}
2.启动类中配置
在启动类的头部我们通过@ServletComponentScan注解来加载自定义的Servlet
@SpringBootApplication
//在 springBoot 启动时会扫描@WebServlet,并将该类实例化
@ServletComponentScan()
public class Springboot01ServletApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot01ServletApplication.class, args);
}
}
[
【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
]( )3.启动测试
通过启动类启动程序访问:http://localhost:8080/first 如下
整合成功~
1.创建servlet
第二种整合servlet的方式不需要在servlet的头部添加@WebServlet注解。
/**
-
@program: springboot-01-servlet
-
@description: SpringBoot整合servlet的第二种方式
-
不用在Servlet中添加@WebServlet注解
-
@author: 波波烤鸭
-
@create: 2019-05-11 15:00
*/
public class SecondServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("–doGet方法执行了----");
PrintWriter out = resp.getWriter();
out.write(“success second”);
out.flush();
out.close();
}
}
2.修改启动类
我们需要在启动类中单独注册servlet,创建一个新的启动类,具体如下:
/**
-
@program: springboot-01-servlet
-
@description: SpringBoot整个Servlet的第二种方式的启动类
-
@author: 波波烤鸭
-
@create: 2019-05-11 15:04
*/
@SpringBootApplication
public class App {