第一種方法:
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;
}
}
啟動項目,訪問結果:

