Spring Boot系列6-SpringBoot中使用servlet

介紹在SpringBoot中如何使用servlet

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency> 

定義類MyServlet繼承HttpServlet

@WebServlet標記servlet,urlPatterns配置映射路徑

重寫doGet方法

@WebServlet(urlPatterns = "/my/servlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
        resp.getWriter().print("hello this is MyServlet!");
    }
}

配置啓動類

@ServletComponentScan(basePackages = “com.tiankonglanlande.cn.springboot.servlet.servlet”)這個註解作用是 配置要掃描servlet的位置,springboot會自動將包下的servlet注入


@SpringBootApplication
@ServletComponentScan(basePackages = "com.tiankonglanlande.cn.springboot.servlet.servlet")
public class ServletApplication {

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

異步的servlet

配置@WebServlet的屬性asyncSupported = true即可

/**
 * @author 天空藍藍的
 */
@WebServlet(urlPatterns = "/my/ayncservlet",asyncSupported = true)
public class MyAyncServlet extends HttpServlet {

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

        AsyncContext asyncContext = req.getAsyncContext();
        asyncContext.start(()->{
            try {
                resp.getWriter().print("hello this is MyAyncServlet!");
                asyncContext.complete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
 

測試

在瀏覽器訪問:http://localhost:8080/my/servlet

輸出:hello this is MyServlet!

在瀏覽器訪問:http://localhost:8080/my/ayncservlet

輸出:hello this is MyAyncServlet!

可能遇到的問題

1.HTTP method GET is not supported by this URL 解決方法:doGet方法中去掉super.doGet()方法調用

2.java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false) 原因:(1)將req.startAsync()錯寫成req.getAsyncContext(); (2)asyncContext.complete()需要在任務完成後調用

源碼下載鏈接

作者:天空藍藍的,版權所有,歡迎保留原文鏈接進行轉載:) 關注我們的公衆號瞭解更多

原文鏈接:https://www.lskyf.xyz/spring-boot/2018/11/11/SpringBoot系列6-SpringBoot中使用servlet

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章