Do javaweb development of the most commonly used a thing El expression, this thing is a very useful thing, but sometimes we deal with complex string manipulation, it is a little bit, this time we need to use a custom method to achieve more concise and convenient things.
The following custom El expression that turns an object into a JSON string is used to illustrate this custom process:
Elfunctions.java
import net.sf.json.JSONObject;publicclass ElFunctions{ publicstatictoJsonString(Object obj){ // 将java对象转换为json对象 JSONObject json = JSONObject.fromObject(obj); String str = json.toString(); return str; }}
Mobai-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 the object as a JSON string -- <function> <name>toJSONString</name> <function-class>Com.mobai.taglib.functions.ElFunctions</function-class> <function-signature>String tojsonstring (Java.lang.Object)</function-signature> <description>Format the object as a JSON string</Description> <example>${el:tojsonstring (Value)}</Example> </function></taglib>
Xml
<?xml version= "1.0" encoding= "UTF-8"?> <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> <!--The reference address of the configuration label is referenced in the JSP page using the <Taglib-uri>Mobai.com/el-common</Taglib-uri> <!--configuration label TLD file address-- <taglib-location>/web-inf/mobai-el-common.tld</taglib-location> </taglib> </jsp-config> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </Web-app>
index.jsp
<%@ taglib uri="mobai.com/el-common" prefix="el" %><body> ${el:toJsonString(user)}</body>
The above is probably the key code of the function, here only a way to convert the JSON string, the others can be customized according to the needs of a variety of methods to use.
Custom El expression, convert object to JSON format, key code