【javaee2022】在springboot中集成servlet的玩法

SpringBoot中集成Servlet的复古玩法

1 复古的玩法,在springboot中集成servlet

之所以称为复古,因为玩springboot都可以直接使用springmvc去用控制器来搞定servlet要做的角色了。
而在学习之初,也可以先学习一下servlet的“组件+容器”的玩法

2 实现的思路

1 方式一:全注解方式
    在启动类上加上@ServletComponentScan注解
    编写完Servlet后,在组件上加上@WebServlet(name="zfhServletName",urlPattern="/zfhTest")
2 方式二:直接使用java配置类方式
    写一个类,然后加上@Configuration注解
    在类中注册自己写的servlet组件,也就是bean,并配置相应的url参数即可        

3 实现代码

3.1 实现方式1

//启动类上加入Servlet扫描注解
@SpringBootApplication
@ServletComponentScan
public class SpringbootservletApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootservletApplication.class, args);
    }
}
//编写Servlet类
@WebServlet(name="zfhServlet",urlPatterns = "/zfhTest")
public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
        System.out.println("fhzheng提醒你 -servlet已经开始运行");
    }
}
采用以上方式编写代码后,我们可以使用
http://localhost:8080/test访问servlet了

3.2 实现方式2

@SpringBootApplication
public class SpringbootservletApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootservletApplication.class, args);
    }
}
//编写servlet
public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
        System.out.println("fhzheng提醒你 -servlet已经开始运行");
    }
}
//编写configuration类
package com.zfh;
import com.zfh.servlet.TestServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServletConfig {
    /**
     * 多个Servlet 需实例化多个ServletRegistrationBean实例
     */
    @Bean
    public ServletRegistrationBean getServletRegistrationBean() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new TestServlet());
        //Servlet既可以使用 test01也可以使用test02访问
        bean.addUrlMappings("/test02");
        bean.addUrlMappings("/test01");
        return bean;
    }
}
-------编写以上代码后,我们可以使用----
http://localhost:8080/test01 访问servlet了
http://localhost:8080/test02 访问servlet了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值