(1)urlPatterns几种写法

  • 几种写法
    • @WebServlet(urlPatterns = “/demo”)
    • @WebServlet(value = “/demo”)
    • @WebServlet(“/demo”) ``` package com.code.web;

import javax.servlet.*; import javax.servlet.annotation.WebServlet; import java.io.IOException;

@WebServlet(value = “/demo”) public class HelloServlet implements Servlet {

  1. /**
  2. * 被创建的时候,调用1次
  3. * @param servletConfig
  4. * @throws ServletException
  5. */
  6. @Override
  7. public void init(ServletConfig servletConfig) throws ServletException {
  8. System.out.println("init");
  9. }
  10. /**
  11. * 获取ServletConfig配置对象
  12. */
  13. @Override
  14. public ServletConfig getServletConfig() {
  15. System.out.println("getServletConfig");
  16. return null;
  17. }
  18. /**
  19. * 调用的时候,多次调用多次执行
  20. */
  21. @Override
  22. public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
  23. System.out.println("service");
  24. }
  25. @Override
  26. public String getServletInfo() {
  27. System.out.println("getServletInfo");
  28. return null;
  29. }
  30. /**
  31. * 销毁的时候,执行1次
  32. */
  33. @Override
  34. public void destroy() {
  35. System.out.println("destroy");
  36. }

}

  1. - WebServlet注解的几种

public @interface WebServlet { String name() default “”;

  1. String[] value() default {};
  2. String[] urlPatterns() default {};
  3. int loadOnStartup() default -1;
  4. WebInitParam[] initParams() default {};
  5. boolean asyncSupported() default false;
  6. String smallIcon() default "";
  7. String largeIcon() default "";
  8. String description() default "";
  9. String displayName() default "";

}

  1. - urlPatterns是数组,一个Servlet可以定义多个访问路径

@WebServlet({“/d1”,”/d2”}) public class Servlet2 extends GenericServlet

  1. - 其他写法

//多级目录 @WebServlet(“/d1/d1”) // 通配符 @WebServlet(“/d1/“) // xx.action 不能加/ @WebServlet(“.action”) ```