分享

java web中servlet、jsp、html 互相访问的路径问题。

 instl 2015-10-24

在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\tomcat\webapps\myapp\


总结:

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


 


 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多