美文网首页
SpringBoot使用Servlet

SpringBoot使用Servlet

作者: 永无止境_ | 来源:发表于2019-03-10 11:11 被阅读0次

一、使用注解方式

1、使用Servlet3注解方式写一个Servlet
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = -4316351735748478174L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("my servlet hello world");
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
2、在main方法添加注解扫描servlet
@ServletComponentScan(basePackages = "com.example.springboot.servlet")

二、通过SpringBoot配置类实现

1、编写一个普通servlet类
public class HeServlet extends HttpServlet {
    private static final long serialVersionUID = -4316351735748478173L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("he servlet hello world");
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
2、编写一个springboot配置类
@Configuration
public class ServletConfig {

    @Bean
    public ServletRegistrationBean heServletRegistrationBean() {
        ServletRegistrationBean registration = new ServletRegistrationBean(new HeServlet(),"/heServlet");
        return registration;
    }
}

相关文章

网友评论

      本文标题:SpringBoot使用Servlet

      本文链接:https://www.haomeiwen.com/subject/aphupqtx.html