配置方式
webXML
定义标签
<url-pattern>Servlet访问路径
<!--配置Servlet--> <servlet> <!--起个短名--> <servlet-name>demo1</servlet-name> <!--全类名--> <servlet-class>cn.itcast.web.servlet.ServletDemo1</servlet-class> </servlet> <!--映射--> <servlet-mapping> <!--映射名称对应类短名--> <servlet-name>demo1</servlet-name> <!--资源路径--> <url-pattern>/demo1</url-pattern> </servlet-mapping>
注解
定义的<urlpartten>数组:可以为一个servlet定义多个访问路径。
1 package cn.itcast.web.servlet; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 /** 11 * @author 旗木五五开 12 * @create 2020-02-19 0:08 13 */ 14 @WebServlet({"/d4","/dd4","/ddd4"}) 15 //{}多个,数组用大括号 16 public class ServletDemo4 extends HttpServlet { 17 @Override 18 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 19 System.out.println("doGet"); 20 } 21 }
路径定义规则
- /xxx
- /xxx/xxx:多层路径。目录结构
- /*.do
多层路径。目录结构
1 package cn.itcast.web.servlet; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 /** 11 * @author 旗木五五开 12 * @create 2020-02-19 0:08 13 */ 14 @WebServlet("/user/demo4") 15 public class ServletDemo4 extends HttpServlet { 16 @Override 17 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 18 System.out.println("doGet"); 19 } 20 }
*代表任意,想写啥就写啥,写啥都能访问到。直接写/*。后面写什么都能访问到
优先级最低,别的都访问不到,才访问
1 package cn.itcast.web.servlet; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 /** 11 * @author 旗木五五开 12 * @create 2020-02-19 0:08 13 */ 14 @WebServlet("/user/*") 15 public class ServletDemo4 extends HttpServlet { 16 @Override 17 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 18 System.out.println("doGet"); 19 } 20 }
*.do:*所有,do后缀名。注意不要写错,*.啥都行
注意*前不要加/
加了就——报错
1 package cn.itcast.web.servlet; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 /** 11 * @author 旗木五五开 12 * @create 2020-02-19 0:08 13 */ 14 @WebServlet("*.do") 15 public class ServletDemo4 extends HttpServlet { 16 @Override 17 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 18 System.out.println("doGet"); 19 } 20 }