SpringBoot整合Web开发:整合Servlet
SpringBoot学习目录
通过注解扫描完成Servlet组件的注册
Servlet类:
/**
*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>
*
*/
@WebServlet(name="FirstServlet",urlPatterns="/first")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
Application.java:
/**
* SpringBoot 整合 Servlet 方式一
*
*/
@SpringBootApplication
@ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
通过方法完成Servlet组件的注册
Servlet类:
/**
*SpringBoot 整合 Servlet 方式二
*
*/
public class SecondServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("SecondServlet..........");
}
}
Application.java:
/**
* SpringBoot 整合 Servlet 方式二
*
*/
@SpringBootApplication
public class Application2 {
public static void main(String[] args) {
SpringApplication.run(Application2.class, args);
}
@Bean
public ServletRegistrationBean getServletRegistrationBean(){
ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
bean.addUrlMappings("/second");
return bean;
}
}
总结
1.方式一在Servlet类上添加注释@WebServlet(name=“FirstServlet”,urlPatterns="/first")
等同于在web.xml中配置:
<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>
然后在启动类Application.java上添加@ServletComponentScan,让springBoot启动时扫描@WebServlet,并将该类实例化
2.方式二只在Application.java中添加了一个返回类型为ServletRegistrationBean的方法,方法名自定义,添加注释@Bean