SpringBoot学习2:springboot整合servlet
整合方式1:通过注解扫描完成 Servlet 组件的注册
1、编写servlet
package com.bjsxt.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by Administrator on 2019/2/4. */ @WebServlet(name = "FirstServlet",urlPatterns = "/first") //该servlet的名字,访问路径 public class FirstServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("firstServlet............."); } }
2、编写启动类
package com.bjsxt; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; /** * Created by Administrator on 2019/2/4. */ @SpringBootApplication @ServletComponentScan //在springboot启动时,会扫描@WebServlet,并将该类实例化 public class App { public static void main(String[] args){ SpringApplication.run(App.class,args); } }
整合方式二:通过方法完成 Servlet 组件的注册
1、编写servlet
package com.bjsxt.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by Administrator on 2019/2/4. */ public class SecondServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("secondServlet............."); } }
2、编写启动类
package com.bjsxt; import com.bjsxt.servlet.SecondServlet; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; /** * Created by Administrator on 2019/2/4. */ @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; } }