一、通过注解扫描方式实现
1. 通过注解方式创建一个Servlet
在com.suke.springboot.servlet包下创建MyServlet
/*
* http://localhost:9014/014-springboot-filter/MyServlet
* */
@WebServlet(value = "/MyServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("-------doGet------");
resp.getWriter().write("you had me at hello");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("-------doPost------");
}
}
2. 在主应用程序Application类上添加注解
注解:@ServletComponentScan("com.suke.springboot.servlet")
@SpringBootApplication
@ServletComponentScan("com.suke.springboot.web")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. 启动应用SpringBoot,浏览器访问测试
二、通过Spring Boot的配置类实现(组件注册)
1. 创建一个普通的Servlet
ublic class HeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print("He SpringBoot Servlet");
response.getWriter().flush();
response.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
2. 编写一个Spring Boot的配置类,在该类中注册Servlet
@Configuration //添加@Configuration 将此类变为配置变
public class ServletConfig {
/**
* @Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名
* 如下代码相当于
* <beans>
* <bean id="transferService" class="com.acme.TransferServiceImpl"/>
* </beans>
* @return
*/
@Bean
public ServletRegistrationBean heServletRegistrationBean() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new HeServlet(),"/servlet/heServlet");
return servletRegistrationBean;
}
}