自定义EL表达式,将对象转成json格式,关键代码

做javaweb开发的最常用的一个东西el表达式,这个东西是个很好用的东西,但有些时候我们处理复杂的字符串操作,就有些相形见绌了,这个时候就需要用自定义的方法去实现更多简洁方便的事情。

下面自定义一个将对象转成json字符串的自定义el表达式用来讲解这个自定义的过程:

ElFunctions.java

import net.sf.json.JSONObject;
public class ElFunctions{

    public static String toJsonString(Object obj){
        // 将java对象转换为json对象
        JSONObject json = JSONObject.fromObject(obj);
        String str = json.toString();
        return str;
    }
}

mobai-el-common.tld


<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.0tlib-version>
    <short-name>elshort-name>

    
    <function>
        <name>toJsonStringname>

        <function-class>com.mobai.taglib.functions.ElFunctionsfunction-class>
        <function-signature>String toJsonString(java.lang.Object)function-signature>

        <description>将对象format成json字符串description>
        <example>${el:toJsonString(value)}example>
    function>
taglib>

web.xml

  
<web-app version="2.5" 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-app_2_5.xsd">  
    <jsp-config>  
        <taglib>  
              
            <taglib-uri>mobai.com/el-commontaglib-uri>  
              
            <taglib-location>/WEB-INF/mobai-el-common.tldtaglib-location>  
        taglib>  
    jsp-config>  
    <welcome-file-list>  
        <welcome-file>index.jspwelcome-file>  
    welcome-file-list>  
web-app>

index.jsp

<%@ taglib uri="mobai.com/el-common" prefix="el" %>
<body>
    ${el:toJsonString(user)}
body>  

以上大概就是该功能的关键代码了,这里只列举了一个转换json字符串的方法,其他的大家可以根据需要去自定义各种各样的方法来用。

你可能感兴趣的:(Java,漫漫编程路)