ServletRegistrationBean 用来做在 servlet 3.0+容器中注册 servlet 的功能,但更具有SpringBean 友好性。
项目结构
![](https://i-blog.csdnimg.cn/blog_migrate/811b8afac08b8afc3b0f113a6dbc241a.png)
1. 创建 Servlet
package com.it.web;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
//创建servlet类
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//使用HttpServletResponse输出数据,应答结果
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("执行的是Servlet");
out.flush();
out.close();
}
}
2. 注册 Servlet
package com.it.config;
import com.it.web.MyServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebApplicationConfig {
//定义方法,注册servlet对象
@Bean
public ServletRegistrationBean servletRegistrationBean(){
//第一个参数是servlet对象,第二个参数是url地址
ServletRegistrationBean bean=new ServletRegistrationBean(new MyServlet(),
"/myservlet");
return bean;
}
}
3. 主启动类
package com.it;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.启动主类,在浏览器中访问myservlet