SpringBoot访问Servlet

SpringBoot访问servlet API方式有两种:

第一种方式

  • 编写Servlet,然后在上面加相应注解@WebServlet(value = "/user.do")
  • 在入口添加@ServletComponentScan注解
package vip.fkandy.demo1;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/user.do")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = -576843248227499148L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.getWriter().println("user servlet");
	}
}

 

package vip.fkandy.demo1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@ServletComponentScan // 扫描Servlet路径,也可以指定basePackages
@RestController
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	@GetMapping(value = "/hello")
	public String hello() {
		return "hello";
	}
}

第二种方式

  • Servlet 2.5 时候,获取Servlet API
  • 创建添加@SpringBootConfiguration配置类,通过ServletRegistrationBean创建
package vip.fkandy.demo2;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BookServlet extends HttpServlet {
	private static final long serialVersionUID = 6128933432188184158L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.getWriter().println("book servlet");
	}
}

 

package vip.fkandy.demo2;

import java.util.Arrays;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootConfiguration
public class ServletConfiguration {
	/**
	 * Servlet
	 * @return
	 */
	@Bean
	public ServletRegistrationBean<BookServlet> createBookServlet() {
		ServletRegistrationBean<BookServlet> servlet = new ServletRegistrationBean<BookServlet>(new BookServlet(),
				"/book.do");
		return servlet;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值