📄 stringutil.java
字号:
/*
* @(#)StringUtil.java 1.0 2003.11.2
*
* Copyright 2003 - 2006 BeanSoft Studio. All rights reserved.
*/
package beansoft.jsp;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Date;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import beansoft.util.OS;
/**
* StringUtil, 字符串工具类, 一些方便的字符串工具方法.
*
* Dependencies: Servlet/JSP API.
*
* @author beansoft
* @version 1.2 2006-07-31
*/
public class StringUtil {
public static String escape(String src) {
int i;
char j;
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length() * 6);
for (i = 0; i < src.length(); i++) {
j = src.charAt(i);
if (Character.isDigit(j) || Character.isLowerCase(j)
|| Character.isUpperCase(j))
tmp.append(j);
else if (j < 256) {
tmp.append("%");
if (j < 16)
tmp.append("0");
tmp.append(Integer.toString(j, 16));
} else {
tmp.append("%u");
tmp.append(Integer.toString(j, 16));
}
}
return tmp.toString();
}
public static String unescape(String src) {
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length());
int lastPos = 0, pos = 0;
char ch;
while (lastPos < src.length()) {
pos = src.indexOf("%", lastPos);
if (pos == lastPos) {
if (src.charAt(pos + 1) == 'u') {
ch = (char) Integer.parseInt(src
.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
} else {
ch = (char) Integer.parseInt(src
.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
} else {
if (pos == -1) {
tmp.append(src.substring(lastPos));
lastPos = src.length();
} else {
tmp.append(src.substring(lastPos, pos));
lastPos = pos;
}
}
}
return tmp.toString();
}
/**
* 获取类路径中的资源文件的物理文件路径.
* NOTE: 仅在 Win32 平台下测试通过开发.
* @date 2005.10.16
* @param resourcePath 资源路径
* @return 配置文件路径
*/
public static String getRealFilePath(String resourcePath) {
java.net.URL inputURL = StringUtil.class
.getResource(resourcePath);
String filePath = inputURL.getFile();
// For windows platform, the filePath will like this:
// /E:/Push/web/WEB-INF/classes/studio/beansoft/smtp/MailSender.ini
// So must remove the first /
if(OS.isWindows() && filePath.startsWith("/")) {
filePath = filePath.substring(1);
}
return filePath;
}
/**
* 将字符串转换为 int.
*
* @param input
* 输入的字串
* @date 2005-07-29
* @return 结果数字
*/
public static int parseInt(String input) {
try {
return Integer.parseInt(input);
} catch (Exception e) {
// TODO: handle exception
}
return 0;
}
/**
* 格式化日期到日时分秒时间格式的显示. d日 HH:mm:ss
*
* @return - String 格式化后的时间
*/
public static String formatDateToDHMSString(java.util.Date date) {
if (date == null) {
return "";
}
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"d日 HH:mm:ss");
return dateFormat.format(date);
}
/**
* 格式化日期到时分秒时间格式的显示.
*
* @return - String 格式化后的时间
*/
public static String formatDateToHMSString(java.util.Date date) {
if (date == null) {
return "";
}
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"HH:mm:ss");
return dateFormat.format(date);
}
/**
* 将时分秒时间格式的字符串转换为日期.
*
* @param input
* @return
*/
public static Date parseHMSStringToDate(String input) {
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"HH:mm:ss");
try {
return dateFormat.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 格式化日期到 Mysql 数据库日期格式字符串的显示.
*
* @return - String 格式化后的时间
*/
public static String formatDateToMysqlString(java.util.Date date) {
if (date == null) {
return "";
}
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return dateFormat.format(date);
}
/**
* 将 Mysql 数据库日期格式字符串转换为日期.
*
* @param input
* @return
*/
public static Date parseStringToMysqlDate(String input) {
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
try {
return dateFormat.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 返回时间字符串, 可读形式的, M月d日 HH:mm 格式. 2004-09-22, LiuChangjiong
*
* @return - String 格式化后的时间
*/
public static String formatDateToMMddHHmm(java.util.Date date) {
if (date == null) {
return "";
}
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"M月d日 HH:mm");
return dateFormat.format(date);
}
/**
* 返回时间字符串, 可读形式的, yy年M月d日HH:mm 格式. 2004-10-04, LiuChangjiong
*
* @return - String 格式化后的时间
*/
public static String formatDateToyyMMddHHmm(java.util.Date date) {
if (date == null) {
return "";
}
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"yy年M月d日HH:mm");
return dateFormat.format(date);
}
/**
* 返回 HTTP 请求的 Referer, 如果没有, 就返回默认页面值.
*
* 仅用于移动博客开发页面命名风格: // Added at 2004-10-12 // 如果前一页面的地址包含 _action.jsp ,
* 为了避免链接出错, 就返回默认页面
*
* 2006-08-02 增加从 url 参数 referer 的判断
*
* @param request -
* HttpServletRequest 对象
* @param defaultPage -
* String, 默认页面
* @return String - Referfer
*/
public static String getReferer(HttpServletRequest request,
String defaultPage) {
String referer = request.getHeader("Referer");// 前一页面的地址, 提交结束后返回此页面
// 获取URL中的referer参数
String refererParam = request.getParameter("referer");
if(!isEmpty(refererParam)) {
referer = refererParam;
}
// Added at 2004-10-12
// 如果前一页面的地址包含 _action.jsp , 为了避免链接出错, 就返回默认页面
if (isEmpty(referer) || referer.indexOf("_action.jsp") != -1) {
referer = defaultPage;
}
return referer;
}
/**
* 生成一个 18 位的 yyyyMMddHHmmss.SSS 格式的日期字符串.
*
* @param date
* Date
* @return String
*/
public static String genTimeStampString(Date date) {
java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(
"yyyyMMddHHmmss.SSS");
return df.format(date);
}
/**
* Write the HTML base tag to support servlet forward calling relative path
* changed problems.
*
* Base is used to ensure that your document's relative links are associated
* with the proper document path. The href specifies the document's
* reference URL for associating relative URLs with the proper document
* path. This element may only be used within the HEAD tag. Example: <BASE
* HREF="http://www.sample.com/hello.htm">
*
* @param pageContext
* the PageContext of the jsp page object
*/
public static void writeHtmlBase(PageContext pageContext) {
HttpServletRequest request = (HttpServletRequest) pageContext
.getRequest();
StringBuffer buf = new StringBuffer("<base href=\"");
buf.append(request.getScheme());
buf.append("://");
buf.append(request.getServerName());
buf.append(":");
buf.append(request.getServerPort());
buf.append(request.getRequestURI());
buf.append("\">");
JspWriter out = pageContext.getOut();
try {
out.write(buf.toString());
} catch (java.io.IOException e) {
}
}
/**
* Get the base path of this request.
*
* @param request -
* HttpServletRequest
* @return String - the base path, eg: http://www.abc.com:8000/someApp/
*/
public static String getBasePath(HttpServletRequest request) {
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + path + "/";
return basePath;
}
/**
* Get the current page's full path of this request. 获取当前页的完整访问 URL 路径.
*
* @author BeanSoft
* @date 2005-08-01
* @param request -
* HttpServletRequest
* @return String - the full url path, eg:
* http://www.abc.com:8000/someApp/index.jsp?param=abc
*/
public static String getFullRequestURL(HttpServletRequest request) {
StringBuffer url = request.getRequestURL();
String qString = request.getQueryString();
if (qString != null) {
url.append('?');
url.append(qString);
}
return url.toString();
}
/**
* Get the current page's full path of this request. 获取当前页的完整访问 URI 路径.
*
* @author BeanSoft
* @date 2005-08-01
* @param request -
* HttpServletRequest
* @return String - the full uri path, eg: /someApp/index.jsp?param=abc
*/
public static String getFullRequestURI(HttpServletRequest request) {
StringBuffer url = new StringBuffer(request.getRequestURI());
String qString = request.getQueryString();
if (qString != null) {
url.append('?');
url.append(qString);
}
return url.toString();
}
// ------------------------------------ 字符串处理方法
// ----------------------------------------------
/**
* 将字符串 source 中的 oldStr 替换为 newStr, 并以大小写敏感方式进行查找
*
* @param source
* 需要替换的源字符串
* @param oldStr
* 需要被替换的老字符串
* @param newStr
* 替换为的新字符串
*/
public static String replace(String source, String oldStr, String newStr) {
return replace(source, oldStr, newStr, true);
}
/**
* 将字符串 source 中的 oldStr 替换为 newStr, matchCase 为是否设置大小写敏感查找
*
* @param source
* 需要替换的源字符串
* @param oldStr
* 需要被替换的老字符串
* @param newStr
* 替换为的新字符串
* @param matchCase
* 是否需要按照大小写敏感方式查找
*/
public static String replace(String source, String oldStr, String newStr,
boolean matchCase) {
if (source == null) {
return null;
}
// 首先检查旧字符串是否存在, 不存在就不进行替换
if (source.toLowerCase().indexOf(oldStr.toLowerCase()) == -1) {
return source;
}
int findStartPos = 0;
int a = 0;
while (a > -1) {
int b = 0;
String str1, str2, str3, str4, strA, strB;
str1 = source;
str2 = str1.toLowerCase();
str3 = oldStr;
str4 = str3.toLowerCase();
if (matchCase) {
strA = str1;
strB = str3;
} else {
strA = str2;
strB = str4;
}
a = strA.indexOf(strB, findStartPos);
if (a > -1) {
b = oldStr.length();
findStartPos = a + b;
StringBuffer bbuf = new StringBuffer(source);
source = bbuf.replace(a, a + b, newStr) + "";
// 新的查找开始点位于替换后的字符串的结尾
findStartPos = findStartPos + newStr.length() - b;
}
}
return source;
}
/**
* 清除字符串结尾的空格.
*
* @param input
* String 输入的字符串
* @return 转换结果
*/
public static String trimTailSpaces(String input) {
if (isEmpty(input)) {
return "";
}
String trimedString = input.trim();
if (trimedString.length() == input.length()) {
return input;
}
return input.substring(0, input.indexOf(trimedString)
+ trimedString.length());
}
/**
* Change the null string value to "", if not null, then return it self, use
* this to avoid display a null string to "null".
*
* @param input
* the string to clear
* @return the result
*/
public static String clearNull(String input) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -