servlet3.0开始支持注解。web.xml已经不是项目必须的配置。可以使用 @WebServlet,代码如下但
@WebServlet(name = "myTestServlet",urlPatterns = "/myServlet")
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.getWriter().print("使用的ServlerTest");
resp.getWriter().close();
}
}
servlet 3.0说不适用web.xml需要在META-INF/services创建一个javax.servlet.ServletContainerInitializer引导文件,指定初始化配置类:
The implementation of JAX-WS runtime isn't typically bundled in each and every
war file. The implementation would bundle an implementation of the
ServletContainerInitializer (shown below) and the container would look
that up using the services API (the jar file will bundle in it's META-INF/services
directory a file called javax.servlet.ServletContainerInitializer that will
point to the JAXWSServletContainerInitializer shown below).
@HandlesTypes(WebService.class)
JAXWSServletContainerInitializer
implements ServletContainerInitializer
{
public void onStartup(Set<Class<?>> c, ServletContext ctx)
throws ServletException {
// JAX-WS specific code here to initialize the runtime
// and setup the mapping etc.
ServletRegistration reg = ctx.addServlet("JAXWSServlet",
"com.sun.webservice.JAXWSServlet");
reg.addServletMapping("/foo");
}
在springweb中就是这样实现的
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer
实现了Servlet容器初始化接口,和加载 WebApplicationInitializer的所有实现
SpringBoot中使用Servlet
在SpringBootApplication上使用@ServletComponentScan注解后,Servlet、Filter、Listener可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册
例如:启动类指定servlet扫描路径
@SpringBootApplication(scanBasePackages="com.test")
@ServletComponentScan(value = {"com.test.web.listener"}) //指定Servlet扫描地址
public class OpensmsApp {
public static void main(String[] args) {
SpringApplication.run(OpensmsApp.class);
}
}
@WebListener
public class SendCtccSmsListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
//servlet容器监听事件
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
//servlet容器销毁时业务处理
}
}