SpringBoot 官方文档示例:(62) ServletContextInitializer的用法
原创
©著作权归作者所有:来自51CTO博客作者wx62e0d796b5814的原创作品,请联系作者获取转载授权,否则将追究法律责任
可以通过ServletContextInitializer来向容器注册Servlet
一、定义Servlet
package com.example.config;
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;
public class MyServlet3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getOutputStream().println("hello world3...");
}
}
二、注册Servlet
package com.example.config;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@Configuration
public class MyServletContextInitializer implements ServletContextInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addServlet("myServlet3", new MyServlet3()).addMapping("/welcome3");
}
}
三、postman测试: