其他分享
首页 > 其他分享> > SpringBoot 注册Servlet三大组件【Servlet、Filter、Listener】-原生代码+@Bean+效果展示

SpringBoot 注册Servlet三大组件【Servlet、Filter、Listener】-原生代码+@Bean+效果展示

作者:互联网

由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。
注册三大组件,class MyServlet()/class MyListener/ class MyFilter 需要自己亲自编写!!

class MyServlet

package com.szs.springboot04.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServlet extends HttpServlet {

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().print("Hello MyServlet!!!");
    }
}

ServletRegistrationBean 注册

@Configuration
public class MyServerConfig {
    /**
     * 注册三大组件
     */
    @Bean
    public ServletRegistrationBean myServlet(){
        ServletRegistrationBean registrationBean =
                new ServletRegistrationBean(new MyServlet(),"/myServlet");
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

标签:SpringBoot,Servlet,resp,javax,Listener,MyServlet,import,servlet,class
来源: https://www.cnblogs.com/zhazhaacmer/p/10460404.html