1. 整合 Servlet

2022-06-28 19:27:01 浏览数 (1)

本文最后更新于 915 天前,其中的信息可能已经有所发展或是发生改变。

通过注解扫描完成 Servlet 组件的注册

1.1 编写 servlet

代码语言:javascript复制
//SpringBoot 整合 Servlet 方式一 
<servlet> 
    <servlet-name>FirstServlet</servlet-name> 
    <servlet-class>com.bjsxt.servlet.FirstServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>FirstServlet</servlet-name> 
    <url-pattern>/first</url-pattern> 
</servlet-mapping>
  • 1.2 编写 controller
代码语言:javascript复制
@WebServlet(name="FirstServlet",urlPatterns="/first") 
public class FirstServlet extends HttpServlet { 
    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
        // TODO Auto-generated method stub 
        super.doGet(req, resp); 
    } 
}
  • 1.3 编写启动类
代码语言:javascript复制
@SpringBootApplication 
@ServletComponentScan //在 springBoot 启动时会扫描@WebServlet,并将该类实例 化
public class App { 
    public static void main(String[] args) { 
        SpringApplication.run(App.class, args); 
    } 
}

通过方法完成 Servlet 组件的注册

  • 2.1 编写 servlet
代码语言:javascript复制
/***SpringBoot 整合 Servlet 方式二 **/
public class SecondServlet extends HttpServlet { 
    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
        System.out.println("SecondServlet.........."); 
    } 
}
  • 2.2 编写启动类
代码语言:javascript复制
/*** SpringBoot 整合 Servlet 方式二 **/ 
@SpringBootApplication 
public class App2 { 
    public static void main(String[] args) { 
        SpringApplication.run(App2.class, args); 
    }
    @Bean 
    public ServletRegistrationBean getServletRegistrationBean(){ 
        ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet()); 
        bean.addUrlMappings("/second"); 
        return bean; 
    } 
}

0 人点赞