SpringBoot使用Servlet
项目依赖:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
通过注解MyServlet 并继承HttpServlet重写它的方法.
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("myServlet");
resp.getWriter().write("myServlet to page");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
最后需要在启动类扫描Servlet所在包。
@SpringBootApplication
@ServletComponentScan(basePackages = "com.jiuyue.servlet")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
另一种方式
public class HeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("heServlet");
resp.getWriter().write("heServlet to page");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
使用@Configuration注解配置类,相当于xml文件中配置了Servlet。在配置类中使用@Bean注解注册Servlet.
@Configuration
public class ServletConfig {
@Bean
public ServletRegistrationBean ServletRegistrationBean(){
ServletRegistrationBean registration =
new ServletRegistrationBean(new HeServlet(),"/heServlet");
return registration;
}
}