今天就跟大家聊聊有關SpringBoot如何整合Servlet,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
使用Spring Initializr創建項目,選擇Web組件
需要在Servlet類上增加@WebServlet 注解 ,urlPatterns指定匹配Url
//com.zhl.springbootweb.servlet.FirstServlet
package com.zhl.springbootweb.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;
/*
* 整合Servlet方式一
* */
@WebServlet(name = "FirstServlet",urlPatterns = "/first")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("First Servlet");
}
}在啟動類上增加@ServletComponentScan注解
package com.zhl.springbootweb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
/*在SpringBoot啟動時會掃描@WebServlet注解,并將該類實例化*/
@ServletComponentScan
public class SpringbootWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootWebApplication.class, args);
}
}不需要增加@WebServlet注解
//com.zhl.springbootweb.servlet.SecondServlet
package com.zhl.springbootweb.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/*整合Servlet 方式二*/public class SecondServlet extends HttpServlet {@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Second Servlet");
}
}使用@Configuration標識為配置類
使用@Bean 標識為組件
addUrlMappings 方法添加URL匹配
//com.zhl.springbootweb.config.ServletConfig
package com.zhl.springbootweb.config;
import com.zhl.springbootweb.servlet.SecondServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServletConfig {
/*完成Servlet組件注冊*/
@Bean
public ServletRegistrationBean getServletRegistrationBean(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new SecondServlet());
servletRegistrationBean.addUrlMappings("/second");
return servletRegistrationBean;
}
}看完上述內容,你們對SpringBoot如何整合Servlet有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。