spring boot 注入servlet的方法是借助ServletRegistrationBean这个类
例子如下:
先建一个servlet
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("你的特殊的servlet。。。哦...."); response.getWriter().append("Served at: ").append(request.getContextPath()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
然后注入即可:
@Bean public TestServlet servlet(){ return new TestServlet(); } @Bean public ServletRegistrationBean testServlet(TestServlet servlet) { ServletRegistrationBean registration = new ServletRegistrationBean(servlet); registration.setEnabled(true); registration.addUrlMappings("/servlet/test"); return registration; }
最后访问的接口地址即可看见效果了
这种运用场景是当你的项目引用第三方插件的时候注入servlet的时候产生,或者你不用springmvc。
时间: 2024-10-05 06:12:44