<base href="<%=basePath%>">

遇到这样的问题,在地址栏上这样访问。
http://localhost:8080/user/user!login.action


struts文件这么配置
<package name="user" namespace="/user" extends="struts-default">

		<action name="user!*"  class="com.q167.action.LoginAction" method="{1}">
			<result name="success">/ok.jsp</result>
			<result name="fail">/error.jsp</result>
		</action>
	</package>


ok.jsp 页面中有这样的代码

<img src="./img/ok.jpg">

这个时候这个ok.jpg的图片不能正常显示,错误信息是:
GET http://localhost:8080/user/img/ok.jpg 404 (Not Found)

而平常你用  http://localhost:8080/ok.jpg 这个图片是正常显示的。

其实意思就是因为你那个action是在namespace='/user' 下触发的,所以那个html里的
图片也被加了一层目录。(虽然这个action的结果跳转到位于webcontent下的ok.jsp,但是它当前的rootPath貌似变化了,就是加了一层/user)

文件路径如下:
\WebContent
           ---\img
                  ---ok.jpg

           ---ok.jsp

我们这里的一个技巧就是要让html里的相对位置的引用别跟着那个被触发的action
的namespace去变动。具体做法如下:



<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1><font color="green">It Works!!!</font></h1>
<img src="./img/ok.jpg">
</body>
</html>



重点在于

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<base href="<%=basePath%>">

猜你喜欢

转载自have-life.iteye.com/blog/1625320