以前编写配置Servlet
<servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>com.neuedu.servlet.FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/first</url-pattern> </servlet-mapping>
SpringBoot 整合Servlet方式一
通过注解扫描完成Servlet组件的注册
- 编写Servlet
package com.neuedu.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * SpringBoot 整合Servlet方式一 * @author 清水三千尺 * */ @WebServlet(name="FristServlet",urlPatterns="/frist") public class FristServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("FristServlet运行了。。。。。。"); } }
- 编写启动类
package com.neuedu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; /** * SpringBoot 启动类 * @author 清水三千尺 * */ @SpringBootApplication @ServletComponentScan //在SpringBoot启动时会扫描>@WebServlet,并将该类实例化 public class App { public static void main(String[] args) throws Exception { SpringApplication.run(App.class, args); } }
- 启动测试
浏览器访问:http://localhost:8080/frist
控制台结果:
SpringBoot 整合Servlet方式二
通过方法完成Servlet组件的注册
- 编写Servlet
package com.neuedu.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * SpringBoot 整合Servlet方式二 * @author 清水三千尺 * */ @WebServlet(name="SecondServlet",urlPatterns="/second") public class SecondServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("SecondServlet运行了。。。。。。"); } }
- 编写启动类
package com.neuedu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import com.neuedu.servlet.SecondServlet; /** * SpringBoot 启动类 * @author 清水三千尺 * */ @SpringBootApplication public class App2 { public static void main(String[] args) throws Exception { SpringApplication.run(App2.class, args); } @Bean public ServletRegistrationBean<SecondServlet> getServletRegistrationBean() { //完成SecondServlet的注册 ServletRegistrationBean<SecondServlet> bean = new ServletRegistrationBean<SecondServlet>(new SecondServlet()); //完成url的指定 bean.addUrlMappings("/second"); return bean; } }
- 启动测试
浏览器访问:http://localhost:8080/second
控制台结果: