功能:在 jsp 页面将 java对象 转换为 json对象 (使用自定义EL函数实现)
步骤:
- 1. 创建 JSP EL 工具类
- 2. 创建 tld 文件
- 3. 配置 web.xml 文件
- 4. 完成 jsp 调用
1. 创建 JSP EL 工具类
package com.ljw.taglib;
import com.alibaba.fastjson.JSON;
/**
* JSP EL 工具类
*
*/
public class ElCommons {
/**
* 将对象中存在值的字段转换成为json串
* @param obj
* @return
*/
public static String toJsonString(Object obj){
// 将java对象转换为json字符串
// * 注意:我这里使用的是阿里巴巴的fastjson转换,可根据自己使用的json库调用转换方法
String jsonString = JSON.toJSONString(obj);
return jsonString;
}
}
2. 创建 tld 文件(文件存放地址 /WEB-INF/el-common.tld)
<?xml version="1.0" encoding="UTF-8"?>
<taglib
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>el</short-name>
<!-- 将对象format成json字符串 -->
<function>
<!-- 指定当前标签的名称 -->
<name>toJsonString</name>
<!-- 指定当前标签的标签处理类 -->
<function-class>com.ljw.taglib.ElCommons</function-class>
<!-- 指定EL页面调用名字中实际调用的方法.指定处理类的实际方法.参数和回调函数要写完整路径 -->
<function-signature>String toJsonString(java.lang.Object)</function-signature>
<!-- 描述信息。 -->
<description>将对象 format 成 json 字符串</description>
<!-- 使用该标签的案例用法 -->
<example>${el:toJsonString(value)}</example>
</function>
</taglib>
3. 配置 web.xml 文件 (在xml中添加此配置)
<jsp-config>
<!-- 自定义标签库 -->
<taglib>
<!-- 配置标签的引用地址 JSP页面中引用时使用-->
<taglib-uri>el-common</taglib-uri>
<!-- 配置标签的TLD文件地址 -->
<taglib-location>/WEB-INF/el-common.tld</taglib-location>
</taglib>
</jsp-config>
4. 完成 jsp 调用
4.1 后台设置数据示例(将对象数据添加至 request(根据自己使用的框架编写相应代码,这里使用 springMVC))
/**
* 查询商品信息页面
* @param id
* @return
*/
@RequestMapping("/show/{id}")
public ModelAndView show(@PathVariable("id")int id) {
ModelAndView view = new ModelAndView("/base/commodity/commodity_show");
CommodityVo model = commodityService.findById(id);
view.addObject("model",model); // 设置 model 对象数据
return view;
}
/**
* 修改商品页面
* @param id
* @return
*/
@RequestMapping("/update_page/{id}")
public ModelAndView update_page(@PathVariable("id")int id) {
ModelAndView view = new ModelAndView("/base/commodity/commodity_update");
Commodity model = commodityService.selectByPrimaryKey(id);
view.addObject("model",model); // 设置 model 对象数据
return view;
}
4.2 jsp 使用示例(导入自定义 taglib)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="el-common" prefix="el" %>
<!DOCTYPE HTML>
<html>
<head>
<title>自定义 el 函数</title>
</head>
<body>
<script type="text/javascript">
var jsonData = ${el:toJsonString(model)}; // model 为后台设置的对象
console.log(jsonData); // 输出 json 对象
</script>
</body>
</html>