2、SpringBoot整合之SpringBoot整合Servlet


SpringBoot整合servlet

一、創建SpringBoot項目,僅選擇Web模塊即可




二、在POM文件中添加依賴

<!-- 添加servlet依賴模塊 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- 添加jstl標簽庫依賴模塊 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
<!--添加tomcat依賴模塊.-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!-- 使用jsp引擎,springboot內置tomcat沒有此依賴 -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

三、創建servlet,通過注解@WebServlet指定name和url

項目結構如下

package cn.byuan.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;

@WebServlet(name = "testOneServlet", urlPatterns = "/test_one")// 通過注解@WebServlet指定name和url
public class ServletTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().print("Hello, servlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

四、在啟動類上添加注解,指定掃描servlet所在的包

package cn.byuan;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan("cn.byuan.servlet")// 指定掃描servlet所在的包
public class Test002SpringbootServletApplication {

    public static void main(String[] args) {
        SpringApplication.run(Test002SpringbootServletApplication.class, args);
    }

}

五、啟動項目進行測試

測試地址:http://localhost:8080/test_one

源碼地址:https://github.com/byuan98/springboot-integration/tree/master/test002_springboot_servlet


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM