在使用jsp时,我们多会采用下面的方式来取到contextPath
<%@ 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">
<html>
<head>
<title>Awesome Application</title>
<script type="text/javascript" src="<%=path%>/common/js/jquery/1.8.3/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var path = $("#path").val();
$.ajax({
url : path + "/student/queryAllStudent",
type : "post",
...
});
});
</script>
</head>
<body>
<input id="path" value="<%=path%>"/>
...
</body>
</html>
要么是直接拿到页面上的java变量path,或者是先用隐藏域存放path值,然后在js中取到
现在使用springboot和thymeleaf,同样需要拿到contextPath
1.对于页面上引用js,css等,可以使用@,themeleaf会自动在路径前加contextPath
如jquery-1.8.3的全路径为/resources/static/common/js/jquery/1.8.3/jquery-1.8.3.js,只要改写成
<script type="text/javascript" th:src="@{/static/common/js/jquery/1.8.3/jquery-1.8.3.js}"></script>
如页面上需要跳转超链接,有一个“编辑学生”超链接,实际想要访问的地址为(“studentMgmt”是contextPath)
localhost:8080/studentMgmt/student/findStudentById/1,
jsp页面一般会写成:
<a href="<%=path%>/student/findStudentById/${studentId}">编辑学生</a>
在thymeleaf可以写成:
<a th:href="@{'/student/findStudentById/'+${studentId}}" th:text="编辑学生"></a>
2.在js代码中获取contextPath,但又不想借助隐藏域的方式
可以在当前html初始化加载时,创建全局变量。
<script type="text/javascript" th:inline="javascript">
const baseUrl = [[${#servletContext.contextPath}]];
// 或者 const baseUrl = [[${#request.getContextPath()}]];
</script>
(参考:
https://blog.csdn.net/bear_lam/article/details/80278590
)
这段代码一般会放在head的模板文件中加载,这样在该页面的其他js中都能取到这个baseUrl
回到一开始举的jsp那个例子,其中的ajax请求就可以写成,
$.ajax({
url : baseUrl + "/student/queryAllStudent",
type : "post",
...
});