springboot中使用servlet


需要在springboot的啟動類Webapplication上加上注解,對指定包進行掃描:

@ServletComponentScan("com.bjpowernode.springboot.servlet")

com.bjpowernode.springboot.servlet是包的全名,servlet文件所在的包。

 

servlet類上需要加上注解,配置映射路徑,才能被解析:

@WebServlet(urlPatterns = "/myservlet")

 

完整代碼示例:

package com.bjpowernode.springboot.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(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("my springboot servlet……測試中文輸出");
        response.getWriter().flush();
        response.getWriter().close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

啟動類的代碼:

package com.bjpowernode.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@MapperScan("com.bjpowernode.springboot.mapper") //取代在mapper接口上配置的@Mapper
@ServletComponentScan("com.bjpowernode.springboot.servlet")//掃描Servlet包
@EnableTransactionManagement //開啟事務支持
public class WebApplication {

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

}

 


免責聲明!

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



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