我们在页面中访问另一页面,或者跳转到另一页面时,需要页面的url。
如在addUser.jsp页面中,点击ajax提交按钮,会访问
http://localhost:8080/firstSpringMVC/user/ajaxSaveUser:
又如,在addUser.jsp页面中,需要引入jquery的js文件:
<script type="text/javascript" src="http://localhost:8080/firstSpringMVC/js/jquery-1.11.2.min.js"></script>
在项目实战中肯定不能这么写。
解决方法有两个:
1) 方案一
使用request的方法拼接地址,当然最好的办法是提出一个公共的jsp,其他jsp直接引用就好了。
创建一个common.jsp,内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
Integer port = request.getServerPort();
String basePath = null;
if (port == 80){
basePath = request.getScheme() + "://" + request.getServerName() + path;
}
else{
basePath = request.getScheme() + "://" + request.getServerName() + ":" + port + path;
}
pageContext.setAttribute("basePath", basePath);
%>
在addUser.jsp中先引入common.jsp
<%@include file="../common/common.jsp"%>
因为common.jsp在当前jsp上一级的common目录下。
再将使用http://localhost:8080/firstSpringMVC的地方改为${basePath}
如:引用js时:
<script type="text/javascript" src="http://localhost:8080/firstSpringMVC/js/jquery-1.11.2.min.js"></script>
改为:
<script type="text/javascript" src="${basePath}/js/jquery-1.11.2.min.js"></script>
运行起来后,查看页面源码,发现此处会被渲染为http://localhost:8080/firstSpringMVC。
注:javascript中的js代码中不要这么用。因为此代码可能会放到一个单独的js文件中去。使用${basePath}可能渲染不成功。因此在addUser.jsp中增加如下代码:
<script type="text/javascript">var basePath = "${basePath}";</script>
然后在js文件中直接使用basePath变量。
改为:
2) 方案二
1.定义一个类派生自ServletContextAware:
public class BasePathExpsoer implements ServletContextAware{
private ServletContext application;
private String rootPath;
public void init(){
rootPath = application.getContextPath();
application.setAttribute("rootPath", rootPath);
}
@Override
public void setServletContext(ServletContext arg0) {
this.application = arg0;
}
}
2.配置文件中增加配置:
在springMVC-servlet.xml配置文件中增加如下配置
<!-- 统一路径 -->
<bean id="path" class="com.gary.util.BasePathExpsoer" init-method="init"></bean>
3.应用
将
<script type="text/javascript" src="${basePath}/js/jquery-1.11.2.min.js"></script>
改为:
<script type="text/javascript" src="${rootPath}/js/jquery-1.11.2.min.js"></script>
运行起来后,会被渲染为:/firstSpringMVC
即,相对路径。
注:如果js不在本服务器路径中,而是在其他服务器路径,需要从配置中读取,增加配置如下:
<bean id="path" class="com.gary.util.BasePathExpsoer" init-method="init">
<property name="rootPath" value="http://www.baidu.com/XXX"></property>
</bean>
类增加rootPath的set和get方法:
public String getRootPath() {
return rootPath;
}
public void setRootPath(String rootPath) {
this.rootPath = rootPath;
}
同时将init方法也做一点调整:
public void init(){
if ((rootPath == null) || (rootPath.isEmpty())){
rootPath = application.getContextPath();
}
application.setAttribute("rootPath", rootPath);
}
启动服务,访问addUser页面,查看源码可以看到
src="${rootPath}/js/jquery-1.11.2.min.js"
被渲染为了
src="http://www.baidu.com/XXX/js/jquery-1.11.2.min.js"