java web中路径问题。

转自:http://blog.csdn.net/liang5630/article/details/38474543

如有侵权,请及时联系本人及时删除

在java web种经常出现 404找不到网页的错误,究其原因,一般是访问的路径不对。

java web中的路径使用按我的分法可以分两种情况,当然啦两者使用相对路径是一致,本文只说绝对路径。

情况一、指向外部的web组件和本身关系不大的,这一类的有:html中使用路径的标签,比如<a>标签中的href;servlet和jsp中的重定向sendRedirect(path);

情况二、指向内部的web组件和本身有关系的,这一类我暂时看到的有:servlet或者jsp的转发

假设在myapp项目下有个login.html,index.jsp,还写了两个servletA和servletB.

在web.xml中的地址配置:

<url-pattern>/servlet/servletA</url-pattern>

<url-pattern>/servlet/servletB</url-pattern>

在情况一中:若在路径中以/开头,则这一/相当于http://localhost:8080/

1、login.html有个form表单有提交给servletA,那么action要填的路径:

绝对路径方式:action="/myapp/servlet/servletA"       ------http://localhost:8080/myapp/servlet/servletA

相对路径方式:action="servlet/servletA"                   ------http://localhost:8080/myapp/servlet/servletA

2、login.html有个<a>链接到index.jsp 那么

绝对路径方式:href="/myapp/index.jsp"                      ------http://localhost:8080/myapp/index.jsp

相对路径方式:action="index.jsp"                            ------http://localhost:8080/myapp/index.jsp

3、index.jsp中重定向到servletA

绝对路径方式:sendRedirect("/myapp/servlet/servletA");      ------http://localhost:8080/myapp/servlet/servletA

相对路径方式:sendRedirect("servlet/servletA");     ---http://localhost:8080/myapp/servlet/servletA

在情况二中:若在路径中以/开头,则这一/相当于http://localhost:8080/myapp/

1.servletA转发到servletB

绝对路径方式:request.getRequestDispatcher("/servlet/servletB").forward(request, response);

       --------http://localhost:8080/myapp/servlet/servletB

相对路径方式:request.getRequestDispatcher("servlet/servletB").forward(request, response);

       --------http://localhost:8080/myapp/servlet/servletB

注意:

建议使用绝对路径,相对路径是相对于当前浏览器地址栏的路径(源地址)。

可能会出现:你在某个页面写了一个相对路径(目标路径),因为转发是不改变地址的,那么要是别人是通过转发到达你的这个页面的,那么地址栏的源地址就是不确定的,既然不确定你使用相对路径相对于这个不确定的路径就极有可能出错,所以建议使用绝对路径,这样可避免这种问题。

获得项目路径和绝对路径:

项目路径:String path=request.getContextPath();           ----                /myapp

String p=this.getServletContext().getRealPath("/");     -----   G:environment omcatwebappsmyapp

总结:

这里主要弄明白是指向外部的还内部的,外部时"/"就是代表主机路径,内部时"/"就是代表当前项目路径.

原文地址:https://www.cnblogs.com/hhls/p/5398383.html