下文筆者將講述兩種SpringBoot集成Servlet的方法,如下所示:
實作思路:
方式1:
使用全注解的方式開發
1.1 在啟動類上面加上注解 @ServletComponentScan
1.2 撰寫Servlet程式,并在Servlet程式上加上注解 @WebServlet(name="testServlet1",urlPatterns = "/test")
方式2:
直接撰寫一個@Configuration類
將Servlet程式使用ServletRegistrationBean注冊到Springboot中
例1:
//啟動類上加入Servlet掃描注解
@SpringBootApplication
@ServletComponentScan
public class SpringbootservletApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootservletApplication.class, args);
}
}
//撰寫Servlet類
@WebServlet(name="testServlet1",urlPatterns = "/test")
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("java265.com 提醒你 -servlet已經開始運行");
}
}
-----采用以上方式撰寫代碼后,我們可以使用
http://localhost:8080/test訪問servlet了
例2:
@SpringBootApplication
public class SpringbootservletApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootservletApplication.class, args);
}
}
//撰寫servlet
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("java265.com 提醒你 -servlet已經開始運行");
}
}
//撰寫configuration類
package com.java265;
import com.adeal.servlet.TestServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServletConfig {
/*
* 多個Servlet 需實體化多個ServletRegistrationBean實體
* */
@Bean
public ServletRegistrationBean getServletRegistrationBean() {
ServletRegistrationBean bean = new ServletRegistrationBean(new TestServlet());
//Servlet既可以使用 test01也可以使用test02訪問
bean.addUrlMappings("/test02");
bean.addUrlMappings("/test01");
return bean;
}
}
-------撰寫以上代碼后,我們可以使用----
http://localhost:8080/test01 訪問servlet了
http://localhost:8080/test02 訪問servlet了
來源于:http://www.java265.com/JavaFramework/SpringBoot/202201/2221.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/518919.html
標籤:Java
上一篇:Logstash 入門實戰(3)--input plugin 介紹
下一篇:SpringMVC(六):攔截器
