整合方式1:經過註解掃描完成 Servlet 組件的註冊
一、編寫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............."); } }
二、編寫啓動類
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 組件的註冊
一、編寫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............."); } }
二、編寫啓動類
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; } }