JSP如何获取JSON数据:实用方法与最佳实践
在Web开发中,JSP(JavaServer Pages)作为Java EE的经典视图技术,常用于动态页面渲染,而JSON(JavaScript Object Notation)因其轻量级、易解析的特性,已成为前后端数据交互的主流格式,本文将详细介绍JSP获取JSON数据的多种方法,包括从服务器端传递、从客户端AJAX请求获取,以及处理JSON数据的实用技巧,帮助开发者高效实现前后端数据交互。
从服务器端获取JSON数据(最常用场景)
JSP本质上是服务器端渲染技术,获取JSON数据的核心思路是:在Servlet或Controller层生成JSON数据,然后通过request或session作用域传递给JSP页面,最终在JSP中解析并展示,以下是具体实现步骤:
服务器端生成JSON数据
通常使用Jackson、Gson或Fastjson等JSON库将Java对象转换为JSON字符串,以Jackson为例:
(1)添加依赖
在pom.xml中引入Jackson核心库(Maven示例):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
(2)Servlet中生成JSON并传递给JSP
// UserController.java
@WebServlet("/userList")
public class UserController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1. 模拟业务数据:List<User>
List<User> userList = new ArrayList<>();
userList.add(new User(1, "张三", "zhangsan@example.com"));
userList.add(new User(2, "李四", "lisi@example.com"));
// 2. 使用Jackson将List转换为JSON字符串
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(userList);
// 3. 将JSON数据存入request作用域
request.setAttribute("userJson", jsonStr);
// 4. 转发到JSP页面
request.getRequestDispatcher("/userList.jsp").forward(request, response);
}
}
JSP页面解析JSON数据
JSP中解析JSON数据有两种主流方式:使用JSTL标签库+EL表达式或直接使用JavaScript解析。
(1)方式一:JSTL+EL(适合简单场景)
通过<c:out>或直接输出JSON字符串,但需注意转义特殊字符(如、<等)。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>用户列表(JSTL+EL)</title>
</head>
<body>
<h2>用户JSON数据:</h2>
<pre><c:out value="${userJson}"/></pre>
<!-- 如果需要遍历JSON数组,需结合JavaScript(见方式二) -->
</body>
</html>
(2)方式二:JavaScript解析(推荐,适合复杂交互)
通过JSP内置的<%= %>脚本或EL表达式将JSON字符串传递给JavaScript,再使用JSON.parse()解析。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>用户列表(JavaScript解析)</title>
</head>
<body>
<h2>用户列表:</h2>
<table id="userTable" border="1" style="width: 100%; text-align: center;">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
</tr>
</thead>
<tbody>
<!-- 数据将通过JavaScript动态填充 -->
</tbody>
</table>
<script>
// 1. 从JSP作用域获取JSON字符串(EL表达式或脚本)
var userJson = '${userJson}'; // EL表达式自动转义,但需确保JSON格式正确
// 或者使用脚本(更灵活,避免EL转义问题):
// <%
// String userJson = (String) request.getAttribute("userJson");
// %>
// var userJson = '<%= userJson %>';
// 2. 解析JSON字符串并渲染表格
try {
var userList = JSON.parse(userJson); // 解析为JavaScript数组
var tbody = document.getElementById("userTable").getElementsByTagName("tbody")[0];
userList.forEach(function(user) {
var row = tbody.insertRow();
row.insertCell(0).textContent = user.id;
row.insertCell(1).textContent = user.name;
row.insertCell(2).textContent = user.email;
});
} catch (e) {
console.error("JSON解析失败:", e);
document.getElementById("userTable").innerHTML = "<tr><td colspan='3'>数据加载失败</td></tr>";
}
</script>
</body>
</html>
关键点:
- 使用EL表达式
${userJson}时,JSP会自动对特殊字符(如、<)进行HTML转义,避免XSS攻击,但需确保JSON字符串本身格式正确(如无未转义的)。 - 如果JSON字符串包含复杂字符(如换行符、
<等),推荐使用JSP脚本<%= %>直接输出,并手动调用StringEscapeUtils.escapeHtml4()(Apache Commons Lang)进行转义。
从客户端AJAX请求获取JSON数据(异步交互场景)
当JSP页面需要异步获取JSON数据时(如分页加载、实时搜索),可通过AJAX(Fetch API或jQuery.ajax)向服务器发送请求,并在回调函数中处理返回的JSON数据。
使用原生Fetch API(现代浏览器推荐)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>AJAX获取JSON数据</title>
</head>
<body>
<h2>异步加载用户列表:</h2>
<button id="loadBtn">加载用户</button>
<div id="userList"></div>
<script>
document.getElementById("loadBtn").addEventListener("click", function() {
// 1. 发送GET请求获取JSON数据
fetch('/userList') // 假设Servlet映射路径为/userList
.then(response => {
if (!response.ok) {
throw new Error("网络响应异常");
}
return response.text(); // 先获取文本(避免直接解析为JSON时出错)
})
.then(jsonStr => {
// 2. 解析JSON字符串
try {
var userList = JSON.parse(jsonStr);
// 3. 渲染数据
var html = "<ul>";
userList.forEach(function(user) {
html += "<li>ID: " + user.id + ", 姓名: " + user.name + ", 邮箱: " + user.email + "</li>";
});
html += "</ul>";
document.getElementById("userList").innerHTML = html;
} catch (e) {
console.error("JSON解析失败:", e);
document.getElementById("userList").innerHTML = "<p>数据解析错误</p>";
}
})
.catch(error => {
console.error("请求失败:", error);
document.getElementById("userList").innerHTML = "<p>加载失败,请重试</p>";
});
});
</script>
</body>
</html>
使用jQuery.ajax(兼容性更好)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%-- 引入jQuery库 --%>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<html>
<head>jQuery AJAX获取JSON</title>
</head>
<body>
<h2>jQuery异步加载用户:</h2>
<button id="loadBtn">加载用户</button>
<div id="userList"></div>
<script>
$("#loadBtn").click(function() {
$.ajax({
url: "/userList", // 请求地址
type: "GET", // 请求方法
dataType: "json", // 预期服务器返回JSON数据(jQuery自动解析)
success: function(data) { // data为已解析的JavaScript对象
var html = "<ul>";
data.forEach(function(user) {
html += "<li>ID: " + user.id + ", 姓名: " + user.name + "</li>";
});
html += "</ul>";
$("#userList").html(html);
},
error: function(xhr, status, error) {
console.error("请求失败:", error);
$("#userList").html("<p>加载失败</p>");
}
});
});
</script>
</body>
</html>
关键点:
fetch的`response



还没有评论,来说两句吧...