springboot整合servlet方式二

1.创建一个springboot项目

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.util.concurrent.ListenableFutureCallbackRegistry;

import com.test.filter.SecondFilter;
import com.test.listener.SecondListener;
import com.test.servlet.Hello02Servlet;

@SpringBootApplication
public class App2 {
	public static void main(String[] args) {
		SpringApplication.run(App2.class, args);
	}
	@Bean
	public ServletRegistrationBean getServlet(){
		ServletRegistrationBean bean=new ServletRegistrationBean(new Hello02Servlet(),"/hello02");
		return bean;
	}
}

2.创建一个servlet类

package com.test.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * springboot整合servlet方式一
 * <servlet>
 * 		<servlet-name>hello</servlet-name>
 * 		<servlet-class>com.test.servlet.HelloServlet</servlet-class>
 * </servlet>
 * <servlet-mapping>
 * 		<servlet-name>hello</servlet-name>
 * 		<url-pattern>/hello</url-pattern>
 * </servlet-mapping>
 * @author 26920
 *
 */
public class Hello02Servlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("hello02======");
		super.doGet(req, resp);
	}
}

3.相比注解方式,在servlet类中不用做任何处理,可以在springboot配置类中加方法创建bean,只要有@Configuration注解的类都是配置类,@SpringBootApplication注解是一个组合注解包含@Configuration,所以我在类中写了个方法,方法名随便但方法的返回类型必须是ServletRegistrationBean。ServletRegistrationBean类中可以设置访问路几个。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值