SpringBoot(六):SpringBoot中如何使用Servlet?

第一种方法:

1.使用Servlet3的注解方式编写一个Servlet

2.在main方法的主类上添加注解:

@ServletComponentScan(basePackages = "com.example.springbootweb.servlet")
如图:

访问结果:

第二种方式:

通过springboot的配置类实现

1.编写一个普通的Servlet 类上没有注解

2.编写一个Springboot的配置类:

上面一张配置拦截器的时候写过配置类,这里我直接增加一个方法

代码如下:

package com.example.springbootweb.config;

import com.example.springbootweb.interceptor.LoginInterceptor;
import com.example.springbootweb.servlet.HeServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration   // 等价于一个spring的xml文件 比如applicationContext.xml
public class WebConfig implements WebMvcConfigurer {
      /**
     * @Bean 注解相当于spring 的xml配置中的一个
     *
     * <bean id="xxx" class="xxx.xxx.xxx.."></bean>
     *方法名等于id
     * 方法返回类型等于class
     *
     *
     */
    @Bean
    public ServletRegistrationBean heServletRegistrationBean(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HeServlet(),"/heServlet");
        return registrationBean;
    }
}

  启动项目,访问结果:

 

 

转载于:https://www.cnblogs.com/shenlailai/p/10464272.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值