方式1:
①继承 javax.servlet.http.HttpServlet,重写Servlet的doGet、doPost等方法,并用javax.servlet.annotation.WebServlet注解指定路径
package com.example.demo.servlet;
...
@WebServlet(urlPatterns={"/myServlet"}) //-指定请求路径
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.write("Hello myServlet.");
writer.flush();
writer.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
②启动类添加Servlet扫描注解 org.springframework.boot.web.servlet.ServletComponentScan,扫描指定包
@SpringBootApplication
@ServletComponentScan("com.example.demo.servlet")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
方式2:
①继承 javax.servlet.http.HttpServlet,重写Servlet的doGet、doPost等方法
package com.example.demo.servlet;
...
public class MyConfServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.write("Hello myConfServlet.");
writer.flush();
writer.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
②编写Servlet配置类,配置自定义的Servlet
package com.example.demo.config;
...
@Configuration //配置类
public class ServletConfig {
@Bean //注册为ServletRegistrationBean
public ServletRegistrationBean myConfServletRegistrationBean() {
return new ServletRegistrationBean(new MyConfServlet(), "/myConfServlet");
}
}