springboot thymeleaf在前端设置全局变量让js取到

在使用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>

(参考:

Thymeleaf 内置对象之获取web根路径

thymeleaf中的内联

https://blog.csdn.net/bear_lam/article/details/80278590

这段代码一般会放在head的模板文件中加载,这样在该页面的其他js中都能取到这个baseUrl

回到一开始举的jsp那个例子,其中的ajax请求就可以写成,

$.ajax({
	url : baseUrl + "/student/queryAllStudent",
	type : "post",
	...
});


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值