SpringBoot - 使用Servlet

1、在SpringBoot中使用Servlet

1.1、使用注解注册Servlet:

/**
 * SpringBoot使用Servlet
 */
@WebServlet(name="OneServlet",urlPatterns="/one")
public class OneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("OneServle ...");
        super.doGet(req, resp);
    }
}

 

@SpringBootApplication
//在 springBoot 启动时会扫描@WebServlet并实例化
@ServletComponentScan
public class AppOne {
  public static void main(String[] args) {
      SpringApplication.run(AppOne.class, args);
  }
}

 

访问:http://localhost:8080/one

 

后台打印:

 

 

1.2、另一种初始化Servlet的方法:方法注册

/**
 * SpringBoot使用Servlet
 */
  public class TwoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("TwoServle ...");
        super.doGet(req, resp);
    }
}

 

@SpringBootApplication
public class AppTwo {
    public static void main(String[] args) {
        SpringApplication.run(AppTwo.class, args);
    }
    @Bean
    public ServletRegistrationBean registrationServletBean(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new TwoServlet());
        bean.addUrlMappings("/two");
        return bean;
    }
}

  

访问:http://localhost:8080/two

 

后台打印:

 

 

posted @ 2018-10-06 18:13  Simple°  阅读(757)  评论(0编辑  收藏  举报