url匹配问题

url匹配问题


·servel.xml

·web.xml

·前端action

·后端的转发或重定向


url的解析分为
前端解析(html中action,后端的重定向)
后端解析(web.xml,后端转发)。

在后端解析中,/  代表应用的上下文,即name+port+path
在前端解析中,/ 代表name+port
后端解析url需要考虑应用的上下文。

以简单的example为例

工程结构

index.html
<form action="user/logon">
U:<input name="username"></input>
P:<input name="password"></input>
<input type="submit"></input>

web.xml
  <servlet>
  <servlet-name>login</servlet-name>
  <servlet-class>user.login</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>login</servlet-name>
  <url-pattern>/user/logon</url-pattern>
  </servlet-mapping>

user.login
public class login extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
    String username=request.getParameter("username");
    String password=request.getParameter("password");
    String url=request.getRequestURI();
    System.out.println(url);
    //String contentPath=request.getContextPath();
    //System.out.println(contentPath);
    //if(lastcontentString.equals("zero")) {
    //PrintWriter write=response.getWriter();
    //write.write(lastcontentString);//}
    if(username.equals("root")&&password.equals("dota6.78b")) {
        //success();
        try {
            request.getRequestDispatcher("/user/success.html").forward(request, response);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    else {
        //error();
        response.sendRedirect("/test/user/error.html");
        return;
    }

}   
@Override
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
    doGet(request, response);
}

在web.xml中,url匹配路径为/user/logon。即当请求为name+port+path+/user/logon,该动作可以被识别转发到相应处理类上。
在index.xml中,不带/的写法为相对路径,即页面当前路径为name+port+path时,该动作可以被识别。完整补充为name+port+path+/user/logon。
带/的写法应该为/test/user/logon。即name+port保持不变,完全替换url部分。
还可以将请求提交给外部服务器,写法为以http/https开头。
在user.login中,可以看到转发与重定向写法是不同的,
转发为服务器内部动作,url解析由服务器执行,/代表了name+port+path
而重定向是将参数传递给客户端,由客户端解析url,所以传递的参数应该为包含应用上下文的url即path+路径。
那么在user.login中是否可以使用不带/的相对路径呢,如果可以,则该url又是如何拼装匹配的呢
1.将重定向和转发统一修改为user/success.html和user/error.html
The requested resource (/test/user/user/success.html) is not available
可以看到该url拼接的规则统一为 当前应用目录+参数

2.将重定向和转发统一修改为success.html和error.html。
测试完全没问题
神奇的事情发生了,后端并不知道前端页面所在文件夹,经仅仅因为前端请求的url路径参数和待返回的页面所处文件一致,只要名字匹配且可以找到资源,就没有问题。这种写法无疑对命名和资源位置有了很大的限制,所以个人喜欢用绝对路径。

猜你喜欢

转载自blog.csdn.net/qq_20996105/article/details/79347319