最近在做驴妈妈旅游网站改版时,遇到了一个关于数据在界面显示的问题。网站使用的是el表达式作为页面数据显示,但在使用过程中,如果读取的字符串中存在‘”’(引号),则会出现错误
例子:title="海螺沟自由行,观"日照金山" 泡温泉,住逸家温泉酒店+金山饭店双人标间_双人套票(CD)" 提示信息title显示:海螺沟自由行,观
针对该问题可以使用如下解决方案
(1)使用替换:title="${title?if_exists?replace(‘"’,”)}"
(2)用EL表达式的自定义函数
首先写格式化字符串的方法。
01
02
03
04
05
06
07
08
09
10
11
|
//这里我将换行符转化为空格," 转化为 \",'转化为 \'; ,也就是转化为JS的转义格式 public static String fs(String s){ if (s!= null && s.length()> 0 ){ s = s.replaceAll( "(\r|\n|\r\n|\n\r)" , " " ); s = s.replaceAll( "\"" , "\\\\" + "\"" ); s = s.replaceAll( "\'" , "\\\\" + "\'" ); return s; } else { return "" ; } } |
在WEB-INF下创建文件夹tags,用来存放标签文件。
然后在tags文件夹下创建formatForJS.tld文件,描述自定义函数。
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
<? xml version = "1.0" encoding = "UTF-8" ?> xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version = "2.0" > < description >A tag library exercising SimpleTag handlers.</ description > < tlib-version >1.0</ tlib-version > < short-name >SimpleTagLibrary</ short-name > < uri >/fs</ uri > < function > < description >format string value for JS</ description > < name >fs</ name > < function-class >kyo.org.ClassName</ function-class > < function-signature >java.lang.String fs(java.lang.String)</ function-signature > </ function > </ taglib > |
配置web.xml
1
2
3
4
5
6
7
8
|
< jsp-config > < taglib > < taglib-location > /WEB-INF/tags/formatForJS.tld </ taglib-location > </ taglib > </ jsp-config > |
在JSP页面的应用.
1
2
3
4
|
<%@ taglib prefix="k" uri="http://www.2016k.com"%> < script type = "text/javascript" > alert('${k:fs(param)}'); </ script > |
如果param中含有单引号,就不会报脚本错误了。
以上代码,在tomcat6下测试通过,但是如果你的应用是部署在Websphere下,则还有需要注意的地方。