form中的action与<url-pattern>的理解

一、<form action="Test/Login" method="post">

在action中有两种表示方式:

1、"/Test/Login"  说明是相对于web服务器的根目录,可以理解为  http://localhost:8080/Test/Login

2、“Test/Login”  说明是相对于当前web应用程序的根目录,可以理解为  http://localhost:8080/项目名称/Test/Login

二、@WebServlet(name="Login",urlPatterns={"/Test/Login"})

urlPatterns与<url-pattern>的作用相同

urlPatterns代表了servlet的路径,即当URI为:http://localhost:8080/项目名称/Test/Login?name=""时,web容器会调用名字为Login的servlet为用户提供服务。

所以说action是与urlPatterns相对应的,即action中的URL需要填写urlPatterns中的URL。

再额外记录几点:

    1、当html在webroot/html文件夹时,action中的URL需要为“../Test/Login”表示将路径改到"http://localhost:8080/项目名称/"下,否则URL将为“http://localhost:8080/项目名称/html/Test/Login”

    2、当urlPatterns={"/Test/Login"}时,如果要在其修饰的servlet中使用response.sendRedirect(url),URL会为http://localhost:8080/项目名称/Test/url,即在Test/下添加了url。这是就需要根据实际情况,令url="../"+url。

原文地址:https://www.cnblogs.com/l1019/p/6511523.html