📄 jsstringtag.java
字号:
/* * Core - Library of useful classes that are used in many CyberDemia projects. * Copyright (C) 2004 CyberDemia Research and Services * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * See the COPYING file located in the top-level-directory of * the archive of this library for complete text of license. */package com.cyberdemia.jsp;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import java.io.IOException;/** * JSStringTag encodes its body to ensure that it can be safely used as a * Javascript String literal. * * @author Alexander Yap * @version $Revision: 1.1 $ at $Date: 2004/03/22 06:56:39 $ by $Author: alexycyap $ * */public class JSStringTag extends BodyTagSupport{ public int doAfterBody() throws JspException { BodyContent body = getBodyContent(); String encodedStr = encodeJSString(body.getString()); body.clearBody(); try { getPreviousOut().print(encodedStr); } catch (IOException ioex) { throw new JspException("Error rewriting encoded Url " + encodedStr, ioex); } return SKIP_BODY; } static public String encodeJSString(String text) { if (text == null) { return ""; } char[] tempChars = text.toCharArray(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < tempChars.length; i++) { char ch = tempChars[i]; switch (ch) { case '\'': buffer.append('\\'); buffer.append('\''); break; case '\"': buffer.append('\\'); buffer.append('\"'); break; case '\\': if (i < tempChars.length - 1) { // Allows \n to be interpreted as new line inside // Javascript String if (tempChars[i + 1] == 'n') { buffer.append(ch); break; } } buffer.append('\\'); buffer.append('\\'); break; default: // Escape all other characters that are not letters, // numbers or whitespaces if (Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) { buffer.append(ch); } else { String hexStr = Integer.toHexString(ch); int hexStrLen = hexStr.length(); if (hexStrLen == 1) { hexStr = "0" + hexStr; } else if (hexStrLen > 2) { hexStr = hexStr.substring(hexStrLen - 2, hexStrLen); } buffer.append("\\x"); buffer.append(hexStr); } } } return buffer.toString(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -