码迷,mamicode.com
首页 > 编程语言 > 详细

spring boot servlet 注入

时间:2017-01-06 16:48:58      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:引用   第三方   pos   span   post   ext   ted   pen   res   

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。

spring boot servlet 注入

标签:引用   第三方   pos   span   post   ext   ted   pen   res   

原文地址:http://www.cnblogs.com/huzi007/p/6256520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!