JSP页面返回JSON数据

  1. 创建方法
 public static String renderJson(HttpServletResponse response, String content){  
    response.setContentType("application/json");  
    response.setCharacterEncoding("UTF-8");  
    response.setHeader("Cache-Control", "no-cache");  
    java.io.PrintWriter pw = null;  
    try{  
        pw = response.getWriter();  
        pw.write(content);  
    }catch (Exception e){  
        //  
    }finally{  
        pw.close();  
    }  
    return null;  
}  
  1. 在JSP中引入
public static String renderJson(HttpServletResponse response, String content){  
    response.setContentType("application/json");  
    response.setCharacterEncoding("UTF-8");  
    response.setHeader("Cache-Control", "no-cache");  
    java.io.PrintWriter pw = null;  
    try{  
        pw = response.getWriter();  
        pw.write(content);  
    }catch (Exception e){  
        //  
    }finally{  
        pw.close();  
    }  
    return null;  
}  
JSP 中获取 JSON 数据可以通过以下步骤完成: 1. 导入必要的包: ```java <%@ page import="java.io.BufferedReader" %> <%@ page import="java.io.InputStreamReader" %> <%@ page import="java.net.URL" %> <%@ page import="java.net.HttpURLConnection" %> ``` 2. 建立与 JSON 数据源的连接: ```java String urlStr = "https://example.com/data.json"; // JSON 数据源的 URL URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); ``` 3. 读取返回JSON 数据: ```java BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder jsonStr = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { jsonStr.append(line); } reader.close(); connection.disconnect(); ``` 4. 解析 JSON 数据: 使用 JSON 解析库(如 Jackson、Gson 等)将获取到的 JSON 字符串解析为 Java 对象或者集合,以便在 JSP 中使用。 以下是一个简单示例,使用 Gson 库将 JSON 字符串解析为 Java 对象: ```java <%@ page import="com.google.gson.Gson" %> <%@ page import="com.example.DataModel" %> <!-- 示例中的 DataModel 是自定义的 Java 类,根据实际情况修改 --> <% String urlStr = "https://example.com/data.json"; // JSON 数据源的 URL URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder jsonStr = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { jsonStr.append(line); } reader.close(); connection.disconnect(); Gson gson = new Gson(); DataModel data = gson.fromJson(jsonStr.toString(), DataModel.class); %> ``` 在上述示例中,`DataModel` 是一个自定义的 Java 类,用于映射 JSON 数据的结构。你需要根据实际情况修改 `DataModel` 类的定义以适应你的 JSON 数据结构。 完成以上步骤后,`data` 对象将包含从 JSON 数据源中获取的数据,你可以在 JSP 页面中使用它进行展示或其他操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值