在IE8上有时出问题:IE8有时会忽略<base/>的作用。所以,使用JSP的时候,有两种方案:
所有URL使用 "/"开头,把工程放在根路径(不同工程用不同端口启动)。
或者,所有URL使用<c:url value="/xxx/xx.action"/>,但这会很麻烦。
JSP中使用include时,例如
<!--其中/开始,表示应用的根路径。这里没有什么问题。--> <%@include file="/inc/hello_you.jsp" %>
JSP中会用到样式或JS的URL引用:
<style type="text/css"> body { /* "/"表示域名根路径,和应用根路径是不同的,当应用不是放在域名根目录的时候就会出现混乱 */ /* 注意,如果没有"/"则是相对于该页面,这不是我们想要的 */ background-image:url(/i/bg.JPG); } </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.
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <base href="<%=basePath%>"> <style type="text/css"> body { /* 这里通过base标签使html设置相对位置为应用根目录,不再是相对于页面 */ background-image:url(i/bg.JPG); } </style>
例子代码:
<html> <head> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <base href="<%=basePath%>"> <style type="text/css"> body { background-image:url(i/bg.JPG); } </style> </head> <body> <%@include file="/inc/hello_you.jsp" %> <p>hello world</p> </body> </html>