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;
}
}