方式一
pom依赖
只要项目中引入了spring-boot-starter-web,就不需要再单独引用servlet,因为依赖的webmvc中引入了servlet
自定义servlet类继承自HttpServlet,添加@WebServlet
@WebServlet(urlPatterns = "/portal/*")
public class HelloServlet extends HttpServlet {
public HelloServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
System.out.println("=====================Hello "+ name +", this is doGet Filter===================");
PrintWriter writer = resp.getWriter();
writer.write("Your request parameter is " + name);
writer.flush();
writer.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("=====================Hello doPost Filter===================");
super.doPost(req, resp);
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("=====================Hello doPut Filter===================");
super.doPut(req, resp);
}
}
启动类上加@ServletComponentScan
@SpringBootApplication
// SpringBoot启动时自动扫描@WebServlet
@ServletComponentScan
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
发送请求测试
方式二
pom依赖
只要项目中引入了spring-boot-starter-web,就不需要再单独引用servlet,因为依赖的webmvc中引入了servlet
自定义servlet类继承自HttpServlet
注意:此时Servlet类上不需要添加@WebServlet注解
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
System.out.println("=====================Hello "+ name +", this is doGet Filter===================");
PrintWriter writer = resp.getWriter();
writer.write("Your request parameter is " + name);
writer.flush();
writer.close();
}
}
启动类注册servlet为一个bean
注意:此时启动类上也不需要加@ServletComponentScan注解去扫描加有@WebServlet注解的servlet类
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
@Bean
public ServletRegistrationBean getRegistrationBean() {
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new TestServlet(), "/test");
// 通过构造设置urlMappings或者通过addUrlMappings方法
registrationBean.addUrlMappings("/test");
return registrationBean;
}
}
发送请求测试