jsp 相对路径问题 (转)

来源:互联网 发布:java多线程是多核吗 编辑:程序博客网 时间:2024/06/14 09:44
2012-11-2修改: 
在IE8上有时出问题:IE8有时会忽略<base/>的作用。所以,使用JSP的时候,有两种方案: 
所有URL使用 "/"开头,把工程放在根路径(不同工程用不同端口启动)。 
或者,所有URL使用<c:url value="/xxx/xx.action"/>,但这会很麻烦。 



JSP中使用include时,例如 
Jsp代码  收藏代码
  1. <!--其中/开始,表示应用的根路径。这里没有什么问题。-->  
  2. <%@include file="/inc/hello_you.jsp" %>  


JSP中会用到样式或JS的URL引用: 
Html代码  收藏代码
  1. <style type="text/css">  
  2. body   
  3. {  
  4. /* "/"表示域名根路径,和应用根路径是不同的,当应用不是放在域名根目录的时候就会出现混乱 */  
  5. /* 注意,如果没有"/"则是相对于该页面,这不是我们想要的 */  
  6. background-image:url(/i/bg.JPG);  
  7. }  
  8. </style>  


常见的解决方法:使用base标签 
The <base> tag specifies the base URL/target for all relative URLs in a document. 
The <base> tag goes inside the <head> element. 
Java代码  收藏代码
  1. <%  
  2. String path = request.getContextPath();  
  3. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  4. %>  
  5. <base href="<%=basePath%>">   
  6. <style type="text/css">  
  7. body   
  8. {  
  9. /* 这里通过base标签使html设置相对位置为应用根目录,不再是相对于页面 */  
  10. background-image:url(i/bg.JPG);  
  11. }  
  12. </style>  


例子代码: 
Html代码  收藏代码
  1. <html>  
  2. <head>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7. <base href="<%=basePath%>">   
  8. <style type="text/css">  
  9. body   
  10. {  
  11. background-image:url(i/bg.JPG);  
  12. }  
  13. </style>  
  14. </head>  
  15.   
  16. <body>  
  17. <%@include file="/inc/hello_you.jsp" %>  
  18. <p>hello world</p>  
  19.   
  20. </body>  
  21.   
  22. </html>