📄 stringutil.java
字号:
return isEmpty(input) ? "" : input;
}
/**
* Return the limited length string of the input string (added at:April 10,
* 2004).
*
* @param input
* String
* @param maxLength
* int
* @return String processed result
*/
public static String limitStringLength(String input, int maxLength) {
if (isEmpty(input))
return "";
if (input.length() <= maxLength) {
return input;
} else {
return input.substring(0, maxLength - 3) + "...";
}
}
/**
* 将字符串转换为一个 JavaScript 的 alert 调用. eg: htmlAlert("What?"); returns
* <SCRIPT language="JavaScript">alert("What?")</SCRIPT>
*
* @param message
* 需要显示的信息
* @return 转换结果
*/
public static String scriptAlert(String message) {
return "<SCRIPT language=\"JavaScript\">alert(\"" + message
+ "\");</SCRIPT>";
}
/**
* 将字符串转换为一个 JavaScript 的 document.location 改变调用. eg: htmlAlert("a.jsp");
* returns <SCRIPT
* language="JavaScript">document.location="a.jsp";</SCRIPT>
*
* @param url
* 需要显示的 URL 字符串
* @return 转换结果
*/
public static String scriptRedirect(String url) {
return "<SCRIPT language=\"JavaScript\">document.location=\"" + url
+ "\";</SCRIPT>";
}
/**
* 返回脚本语句 <SCRIPT language="JavaScript">history.back();</SCRIPT>
*
* @return 脚本语句
*/
public static String scriptHistoryBack() {
return "<SCRIPT language=\"JavaScript\">history.back();</SCRIPT>";
}
/**
* 滤除帖子中的危险 HTML 代码, 主要是脚本代码, 滚动字幕代码以及脚本事件处理代码
*
* @param content
* 需要滤除的字符串
* @return 过滤的结果
*/
public static String replaceHtmlCode(String content) {
if (isEmpty(content)) {
return "";
}
// 需要滤除的脚本事件关键字
String[] eventKeywords = { "onmouseover", "onmouseout", "onmousedown",
"onmouseup", "onmousemove", "onclick", "ondblclick",
"onkeypress", "onkeydown", "onkeyup", "ondragstart",
"onerrorupdate", "onhelp", "onreadystatechange", "onrowenter",
"onrowexit", "onselectstart", "onload", "onunload",
"onbeforeunload", "onblur", "onerror", "onfocus", "onresize",
"onscroll", "oncontextmenu" };
content = replace(content, "<script", "<script", false);
content = replace(content, "</script", "</script", false);
content = replace(content, "<marquee", "<marquee", false);
content = replace(content, "</marquee", "</marquee", false);
// FIXME 加这个过滤换行到 BR 的功能会把原始 HTML 代码搞乱 2006-07-30
// content = replace(content, "\r\n", "<BR>");
// 滤除脚本事件代码
for (int i = 0; i < eventKeywords.length; i++) {
content = replace(content, eventKeywords[i],
"_" + eventKeywords[i], false); // 添加一个"_", 使事件代码无效
}
return content;
}
/**
* 滤除 HTML 代码 为文本代码.
*/
public static String replaceHtmlToText(String input) {
if (isEmpty(input)) {
return "";
}
return setBr(setTag(input));
}
/**
* 滤除 HTML 标记.
* 因为 XML 中转义字符依然有效, 因此把特殊字符过滤成中文的全角字符.
* @author beansoft
* @param s 输入的字串
* @return 过滤后的字串
*/
public static String setTag(String s) {
int j = s.length();
StringBuffer stringbuffer = new StringBuffer(j + 500);
char ch;
for (int i = 0; i < j; i++) {
ch = s.charAt(i);
if (ch == '<') {
stringbuffer.append("<");
// stringbuffer.append("〈");
} else if (ch == '>') {
stringbuffer.append(">");
// stringbuffer.append("〉");
} else if (ch == '&') {
stringbuffer.append("&");
// stringbuffer.append("〃");
} else if (ch == '%') {
stringbuffer.append("%%");
// stringbuffer.append("※");
} else {
stringbuffer.append(ch);
}
}
return stringbuffer.toString();
}
/** 滤除 BR 代码 */
public static String setBr(String s) {
int j = s.length();
StringBuffer stringbuffer = new StringBuffer(j + 500);
for (int i = 0; i < j; i++) {
if (s.charAt(i) == '\n' || s.charAt(i) == '\r') {
continue;
}
stringbuffer.append(s.charAt(i));
}
return stringbuffer.toString();
}
/** 滤除空格 */
public static String setNbsp(String s) {
int j = s.length();
StringBuffer stringbuffer = new StringBuffer(j + 500);
for (int i = 0; i < j; i++) {
if (s.charAt(i) == ' ') {
stringbuffer.append(" ");
} else {
stringbuffer.append(s.charAt(i) + "");
}
}
return stringbuffer.toString();
}
/**
* 判断字符串是否全是数字字符.
*
* @param input
* 输入的字符串
* @return 判断结果, true 为全数字, false 为还有非数字字符
*/
public static boolean isNumeric(String input) {
if (isEmpty(input)) {
return false;
}
for (int i = 0; i < input.length(); i++) {
char charAt = input.charAt(i);
if (!Character.isDigit(charAt)) {
return false;
}
}
return true;
}
/**
* 转换由表单读取的数据的内码(从 ISO8859 转换到 gb2312).
*
* @param input
* 输入的字符串
* @return 转换结果, 如果有错误发生, 则返回原来的值
*/
public static String toChi(String input) {
try {
byte[] bytes = input.getBytes("ISO8859-1");
return new String(bytes, "GBK");
} catch (Exception ex) {
}
return input;
}
/**
* 转换由表单读取的数据的内码到 ISO(从 GBK 转换到ISO8859-1).
*
* @param input
* 输入的字符串
* @return 转换结果, 如果有错误发生, 则返回原来的值
*/
public static String toISO(String input) {
return changeEncoding(input, "GBK", "ISO8859-1");
}
/**
* 转换字符串的内码.
*
* @param input
* 输入的字符串
* @param sourceEncoding
* 源字符集名称
* @param targetEncoding
* 目标字符集名称
* @return 转换结果, 如果有错误发生, 则返回原来的值
*/
public static String changeEncoding(String input, String sourceEncoding,
String targetEncoding) {
if (input == null || input.equals("")) {
return input;
}
try {
byte[] bytes = input.getBytes(sourceEncoding);
return new String(bytes, targetEncoding);
} catch (Exception ex) {
}
return input;
}
/**
* 将单个的 ' 换成 ''; SQL 规则:如果单引号中的字符串包含一个嵌入的引号,可以使用两个单引号表示嵌入的单引号.
*/
public static String replaceSql(String input) {
return replace(input, "'", "''");
}
/**
* 对给定字符进行 URL 编码
*/
public static String encode(String value) {
if (isEmpty(value)) {
return "";
}
try {
value = java.net.URLEncoder.encode(value, "GB2312");
} catch (Exception ex) {
ex.printStackTrace();
}
return value;
}
/**
* 对给定字符进行 URL 解码
*
* @param value
* 解码前的字符串
* @return 解码后的字符串
*/
public static String decode(String value) {
if (isEmpty(value)) {
return "";
}
try {
return java.net.URLDecoder.decode(value, "GB2312");
} catch (Exception ex) {
ex.printStackTrace();
}
return value;
}
/**
* 判断字符串是否未空, 如果为 null 或者长度为0, 均返回 true.
*/
public static boolean isEmpty(String input) {
return (input == null || input.length() == 0);
}
/**
* 获得输入字符串的字节长度(即二进制字节数), 用于发送短信时判断是否超出长度.
*
* @param input
* 输入字符串
* @return 字符串的字节长度(不是 Unicode 长度)
*/
public static int getBytesLength(String input) {
if (input == null) {
return 0;
}
int bytesLength = input.getBytes().length;
//System.out.println("bytes length is:" + bytesLength);
return bytesLength;
}
/**
* 检验字符串是否未空, 如果是, 则返回给定的出错信息.
*
* @param input
* 输入的字符串
* @param errorMsg
* 出错信息
* @return 空串返回出错信息
*/
public static String isEmpty(String input, String errorMsg) {
if (isEmpty(input)) {
return errorMsg;
}
return "";
}
/**
* 得到文件的扩展名.
*
* @param fileName
* 需要处理的文件的名字.
* @return the extension portion of the file's name.
*/
public static String getExtension(String fileName) {
if (fileName != null) {
int i = fileName.lastIndexOf('.');
if (i > 0 && i < fileName.length() - 1) {
return fileName.substring(i + 1).toLowerCase();
}
}
return "";
}
/**
* 得到文件的前缀名.
* @date 2005-10-18
*
* @param fileName
* 需要处理的文件的名字.
* @return the prefix portion of the file's name.
*/
public static String getPrefix(String fileName) {
if (fileName != null) {
fileName = fileName.replace('\\', '/');
if(fileName.lastIndexOf("/") > 0) {
fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
}
int i = fileName.lastIndexOf('.');
if (i > 0 && i < fileName.length() - 1) {
return fileName.substring(0, i);
}
}
return "";
}
/**
* 得到文件的短路径, 不保护目录.
* @date 2005-10-18
*
* @param fileName
* 需要处理的文件的名字.
* @return the short version of the file's name.
*/
public static String getShortFileName(String fileName) {
if (fileName != null) {
String oldFileName = new String(fileName);
fileName = fileName.replace('\\', '/');
// Handle dir
if(fileName.endsWith("/")) {
int idx = fileName.indexOf('/');
if(idx == -1 || idx == fileName.length() - 1) {
return oldFileName;
} else {
return oldFileName.substring(idx + 1, fileName.length() - 1);
}
}
if(fileName.lastIndexOf("/") > 0) {
fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
}
return fileName;
}
return "";
}
/**
* 获取表单参数并做默认转码, 从 ISO8859-1 转换到 GBK.
*
* @author BeanSoft
* @date 2005-08-01
*
* @param request
* HttpServletRequest 对象
* @param fieldName
* 参数名
* @return 取得的表单值
*/
public static String getParameter(HttpServletRequest request,
String fieldName) {
// // 判断编码是否已经指定
// String encoding = request.getCharacterEncoding();
//
// if("GBK".equalsIgnoreCase(encoding) || "GB2312".equalsIgnoreCase(encoding)) {
// return request.getParameter(fieldName);
// }
//
// return request(request, fieldName);
// 2005-08-01 临时修改
// try {
// request.setCharacterEncoding("UTF-8");
// } catch (UnsupportedEncodingException e) {
// // TODO auto generated try-catch
// e.printStackTrace();
// }
return request.getParameter(fieldName);
}
// ------------------------------------ JSP 参数处理方法
// ----------------------------------------------
/** 一个与 ASP 类似的方法, 返回表单域的值, 并转换内码 */
public static String request(HttpServletRequest request, String fieldName) {
// POST 方法的参数有编码错误
if (request.getMethod().equalsIgnoreCase("POST")) {
// JSP Smart upload 的 request 对象没有中文问题
// try {
// if (request instanceof com.jspsmart.upload.Request) {
// // 2004-04-02, Fix the encoding bug on SCO open server(Unix,
// // os.name=OpenServer)
// // when running jsp smart at tomcat 3.1.1,
// // but on Windows and Linux no this problems
// if (System.getProperty("os.name").toLowerCase().indexOf(
// "openserver") != -1) {
// return toChi(request.getParameter(fieldName));
// } else {
// return request.getParameter(fieldName);
// }
// }
// } catch (Throwable ex) {
// // Throwable -- 防止未导入 smartupload 类库时出错
// System.err.println(ex);
// }
// 文件上传模式
//if(isUploadMode) {
// return request.getParameter(fieldName);
//}
// For Tomcat 4.0.6
return toChi(request.getParameter(fieldName));
}
// 将通过 GET 方式发送的中文字符解码(但是必须使用 java.net.URLEncoder 进行中文字符参数的编码)
// 解码时需使用内码转换, 也可使用反编码, 即: return
// decode(request.getParameter(fieldName));
// 问题: decode() 仅适用于 JDK 1.3 + Tomcat 4.0
return toChi(request.getParameter(fieldName));
}
/** 如果表单的值是 null, 则返回 "", 避免 NullPointerException */
public String request1(HttpServletRequest request, String fieldName) {
String s = request(request, fieldName);
if (s == null) {
return "";
}
return s;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -