• 14_Spring Boot 使用Servlet(了解)


    一、通过注解扫描方式实现

    1. 通过注解方式创建一个Servlet

    在com.suke.springboot.servlet包下创建MyServlet

    1. /*
    2. * http://localhost:9014/014-springboot-filter/MyServlet
    3. * */
    4. @WebServlet(value = "/MyServlet")
    5. public class MyServlet extends HttpServlet {
    6. @Override
    7. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    8. System.out.println("-------doGet------");
    9. resp.getWriter().write("you had me at hello");
    10. }
    11. @Override
    12. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    13. System.out.println("-------doPost------");
    14. }
    15. }

    2. ​​​​​​​在主应用程序Application类上添加注解

    注解:@ServletComponentScan("com.suke.springboot.servlet")

    1. @SpringBootApplication
    2. @ServletComponentScan("com.suke.springboot.web")
    3. public class Application {
    4. public static void main(String[] args) {
    5. SpringApplication.run(Application.class, args);
    6. }
    7. }

    3. ​​​​​​​​​​​​​​启动应用SpringBoot,浏览器访问测试

    二、通过Spring Boot的配置类实现(组件注册)

    1. ​​​​​​​创建一个普通的Servlet

    1. ublic class HeServlet extends HttpServlet {
    2. @Override
    3. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    4. response.getWriter().print("He SpringBoot Servlet");
    5. response.getWriter().flush();
    6. response.getWriter().close();
    7. }
    8. @Override
    9. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    10. doGet(request,response);
    11. }
    12. }

    2.​​​​​​​ 编写一个Spring Boot的配置类,在该类中注册Servlet

    1. @Configuration //添加@Configuration 将此类变为配置变
    2. public class ServletConfig {
    3. /**
    4. * @Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名
    5. * 如下代码相当于
    6. * <beans>
    7. * <bean id="transferService" class="com.acme.TransferServiceImpl"/>
    8. * </beans>
    9. * @return
    10. */
    11. @Bean
    12. public ServletRegistrationBean heServletRegistrationBean() {
    13. ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new HeServlet(),"/servlet/heServlet");
    14. return servletRegistrationBean;
    15. }
    16. }

    3. ​​​​​​​启动应用SpringBoot,浏览器访问测试

  • 相关阅读:
    使用spring cloud config来统一管理配置文件
    力扣(LeetCode)315. 计算右侧小于当前元素的个数(2022.11.12)
    obs推流核心流程分析
    Express.js实现注册和登录
    Flink 开发环境搭建
    Oracle中的循环
    线段与线段的关系
    分库分表(3)——ShardingJDBC实践
    ChatGPT4.0怎么收费
    ssm基于微信小程序的新生自助报到系统+ssm+uinapp+Mysql+计算机毕业设计
  • 原文地址:https://blog.csdn.net/qq_45037155/article/details/125636797