📄 stringutil.java
字号:
/**
* 获得指定表单域的值, 并将单个的 ' 换成 ''; SQL 规则:如果单引号中的字符串包含一个嵌入的引号, 可以使用两个单引号表示嵌入的单引号。
*/
public String requestSql(HttpServletRequest request, String fieldName) {
return replaceSql(request1(request, fieldName));
}
/**
* 根据 Cookie 名称得到请求中的 Cookie 值, 需要事先给 _request 一个初始值; 如果 Cookie 值是 null, 则返回 ""
*/
public static String getCookieValue(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return "";
}
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals(name)) {
// 需要对 Cookie 中的汉字进行 URL 反编码, 适用版本: Tomcat 4.0
return decode(cookie.getValue());
// 不需要反编码, 适用版本: JSWDK 1.0.1
//return cookie.getValue();
}
}
// A cookie may not return a null value, may return a ""
return "";
}
// 返回指定表单名的数组
public String[] getParameterValues(HttpServletRequest request, String name) {
// POST 方法的参数没有编码错误
//if (request.getMethod().equalsIgnoreCase("POST")) {
// 文件上传模式
//if(isUploadMode) {
// return request.getParameterValues(name);
//}
// -- For Tomcat 4.0
//return request.getParameterValues(name);
// -- For JSWDK 1.0.1
/*
* String values[] = _request.getParameterValues(name); if(values !=
* null) { for(int i = 0; i < values.length; i++) { values[i] =
* toChi(values[i]); } } return values;
*/
//}
//else {
// 将通过 GET 方式发送的中文字符解码(但是必须使用 java.net.URLEncoder 进行中文字符参数的编码)
// 解码时需使用内码转换, 也可使用反编码, 即: return decode(_request.getParameter(name));
// 问题: decode() 仅适用于 JDK 1.3 + Tomcat 4.0
String encoding = request.getCharacterEncoding();
if("GBK".equalsIgnoreCase(encoding) || "GB2312".equalsIgnoreCase(encoding)) {
return request.getParameterValues(name);
}
String values[] = request.getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = toChi(values[i]);
}
}
return values;
//}
}
/**
* 删除指定的 Web 应用程序目录下所上传的文件
*
* @param application
* JSP/Servlet 的 ServletContext
* @param filePath
* 相对文件路径
*/
public static void deleteFile(ServletContext application, String filePath) {
if (!isEmpty(filePath)) {
String physicalFilePath = application.getRealPath(filePath);
if (!isEmpty(physicalFilePath)) {
java.io.File file = new java.io.File(physicalFilePath);
file.delete();
}
}
}
/**
* 在指定的 Web 应用程序目录下以指定路径创建文件
*
* @param application
* JSP/Servlet 的 ServletContext
* @param filePath
* 相对文件路径
*/
public static boolean createFile(ServletContext application, String filePath) {
if (!isEmpty(filePath)) {
String physicalFilePath = application.getRealPath(filePath);
if (!isEmpty(physicalFilePath)) {
java.io.File file = new java.io.File(physicalFilePath);
try {
// 创建文件
return file.createNewFile();
} catch (IOException e) {
System.err.println("Unable to create file " + filePath);
}
}
}
return false;
}
/**
* 在指定的 Web 应用程序目录下以指定路径创建目录.
*
* @param application
* JSP/Servlet 的 ServletContext
* @param filePath
* 相对文件路径
*/
public static boolean createDir(ServletContext application, String filePath) {
if (!isEmpty(filePath)) {
String physicalFilePath = application.getRealPath(filePath);
if (!isEmpty(physicalFilePath)) {
try {
// 创建目录
java.io.File dir = new java.io.File(application
.getRealPath(filePath));
return dir.mkdirs();
} catch (Exception e) {
System.err
.println("Unable to create directory " + filePath);
}
}
}
return false;
}
/**
* 检查指定的 Web 应用程序目录下的文件是否存在.
*
* @param application
* JSP/Servlet 的 ServletContext
* @param filePath
* 相对文件路径
* @return boolean - 文件是否存在
*/
public static boolean checkFileExists(ServletContext application,
String filePath) {
if (!isEmpty(filePath)) {
String physicalFilePath = application.getRealPath(filePath);
if (!isEmpty(physicalFilePath)) {
java.io.File file = new java.io.File(physicalFilePath);
return file.exists();
}
}
return false;
}
/**
* 获取文件图标名.
* Date: 2005-10
* @param application JSP/Servlet 的 ServletContext
* @param iconDirPath 图标文件夹的路径
* @param fileName 需要处理的文件名
* @return 图标文件相对路径
*/
public static String getFileIcon(ServletContext application,
String iconDirPath, String fileName) {
String ext = getExtension(fileName);
String filePath = iconDirPath + ext + ".gif";
// return filePath;
if(checkFileExists(application, filePath)) {
return filePath;
}
return iconDirPath + "file.gif";
}
/**
* 输出分页显示的结果.
*
* @param page
* 当前页面
* @param recordCount
* 所有结果
* @param pageSize
* 一页显示的多少
* @param pageCountSize
* 前后跳页的多少
* @param linkpageurl
* 连接页面的 URL 字符串
* @return 分页结果的字符串.
*/
public static String paging(int page, int recordCount, int pageSize,
int pageCountSize, String linkpageurl) {
int PageCount = -1; //页面总数
String LinkPageName = linkpageurl;
String LinkText = "";
int StartPage;
int TempPage;
int TempPageCount;
TempPage = (page - 1) % pageCountSize; //唱赣瘤 备窃
StartPage = page - TempPage; //矫累 其捞瘤 备窃
TempPageCount = recordCount % pageSize;
if (TempPageCount == 0) {
PageCount = recordCount / pageSize;
} else {
PageCount = (recordCount / pageSize) + 1; //傈眉 其捞瘤 荐
}
String txtPrev = " [前" + pageCountSize + "页] ";
String txtNext = " [后" + pageCountSize + "页] ";
String txtStart = " [首页] ";
String txtEnd = " [末页] ";
//贸澜栏肺
if (StartPage - 1 > 0) {
LinkText += "<a href='" + LinkPageName + "&page=1' title='到此页'>"
+ txtStart + "</a>";
} else {
LinkText += txtStart;
}
//捞傈 10俺..
if (StartPage - 1 > 0) {
LinkText += "<a href='" + LinkPageName + "&page=" + (StartPage - 1)
+ "' title='到第" + pageCountSize + "页'>" + txtPrev + "</a>";
} else {
LinkText += txtPrev;
}
for (int i = StartPage; i < StartPage + pageCountSize; i++) {
if (i < PageCount + 1) {
LinkText += "<a href='" + LinkPageName + "&page=";
LinkText += i + "' title='" + i + "页'>";
if (i == page) {
LinkText += "<b>[" + i + "]</b>";
} else {
LinkText += "[" + i + "]";
}
LinkText += "</a>";
}
}
//中间页面
if (StartPage + pageCountSize - PageCount - 1 < 0) {
LinkText += "<a href='" + LinkPageName + "&page="
+ (StartPage + pageCountSize) + "' title='到第"
+ pageCountSize + "页'>" + txtNext + "</a>";
} else {
LinkText += txtNext;
}
//最后一页
if (StartPage + pageCountSize <= PageCount) {
LinkText += "<a href='" + LinkPageName + "&page=" + PageCount
+ "' title='最后一页'>" + txtEnd + "</a>";
} else {
LinkText += txtEnd;
}
return LinkText;
}
/**
* Gets the absolute pathname of the class or resource file containing the
* specified class or resource name, as prescribed by the current classpath.
*
* @param resourceName
* Name of the class or resource name.
* @return the absolute pathname of the given resource
*/
public static String getPath(String resourceName) {
if (!resourceName.startsWith("/")) {
resourceName = "/" + resourceName;
}
//resourceName = resourceName.replace('.', '/');
java.net.URL classUrl = new StringUtil().getClass().getResource(
resourceName);
if (classUrl != null) {
//System.out.println("\nClass '" + className +
//"' found in \n'" + classUrl.getFile() + "'");
//System.out.println("\n资源 '" + resourceName +
//"' 在文件 \n'" + classUrl.getFile() + "' 中找到.");
return classUrl.getFile();
}
//System.out.println("\nClass '" + className +
//"' not found in \n'" +
//System.getProperty("java.class.path") + "'");
//System.out.println("\n资源 '" + resourceName +
//"' 没有在类路径 \n'" +
//System.getProperty("java.class.path") + "' 中找到");
return null;
}
/**
* 将日期转换为中文表示方式的字符串(格式为 yyyy年MM月dd日 HH:mm:ss).
*/
public static String dateToChineseString(Date date) {
if (date == null) {
return "";
}
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"yyyy年MM月dd日 HH:mm:ss");
return dateFormat.format(date);
}
/**
* 将日期转换为 14 位的字符串(格式为yyyyMMddHHmmss).
*/
public static String dateTo14String(Date date) {
if (date == null) {
return null;
}
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"yyyyMMddHHmmss");
return dateFormat.format(date);
}
/**
* 将 14 位的字符串(格式为yyyyMMddHHmmss)转换为日期.
*/
public static Date string14ToDate(String input) {
if (isEmpty(input)) {
return null;
}
if (input.length() != 14) {
return null;
}
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
"yyyyMMddHHmmss");
try {
return dateFormat.parse(input);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
// -----------------------------------------------------------
// ---------- 字符串和数字转换工具方法, 2004.03.27 添加 --------
//------------------------------------------------------------
public static byte getByte(HttpServletRequest httpservletrequest, String s) {
if (httpservletrequest.getParameter(s) == null
|| httpservletrequest.getParameter(s).equals("")) {
return 0;
}
return Byte.parseByte(httpservletrequest.getParameter(s));
}
/**
* Reading a parameter as integer from the http servlet request.
*
*/
public static int getInt(HttpServletRequest httpservletrequest, String s) {
if (httpservletrequest.getParameter(s) == null
|| httpservletrequest.getParameter(s).equals("")) {
return 0;
}
return Integer.parseInt(httpservletrequest.getParameter(s));
}
public static long getLong(HttpServletRequest httpservletrequest, String s) {
if (httpservletrequest.getParameter(s) == null
|| httpservletrequest.getParameter(s).equals("")) {
return 0L;
}
return Long.parseLong(httpservletrequest.getParameter(s));
}
public static short getShort(HttpServletRequest httpservletrequest, String s) {
if (httpservletrequest.getParameter(s) == null
|| httpservletrequest.getParameter(s).equals("")) {
return 0;
}
return Short.parseShort(httpservletrequest.getParameter(s));
}
/**
* 将 TEXT 文本转换为 HTML 代码, 已便于网页正确的显示出来.
*
* @param input
* 输入的文本字符串
* @return 转换后的 HTML 代码
*/
public static String textToHtml(String input) {
if (isEmpty(input)) {
return "";
}
input = replace(input, "<", "<");
input = replace(input, ">", ">");
input = replace(input, "\n", "<br>\n");
input = replace(input, "\t", " ");
input = replace(input, " ", " ");
return input;
}
public static String toQuoteMark(String s) {
s = replaceString(s, "'", "'");
s = replaceString(s, "\"", """);
s = replaceString(s, "\r\n", "\n");
return s;
}
public static String replaceChar(String s, char c, char c1) {
if (s == null) {
return "";
}
return s.replace(c, c1);
}
public static String replaceString(String s, String s1, String s2) {
if (s == null || s1 == null || s2 == null) {
return "";
}
return s.replaceAll(s1, s2);
}
public static String toHtml(String s) {
s = replaceString(s, "<", "<");
s = replaceString(s, ">", ">");
return s;
}
public static String toBR(String s) {
s = replaceString(s, "\n", "<br>\n");
s = replaceString(s, "\t", " ");
s = replaceString(s, " ", " ");
return s;
}
public static String toSQL(String s) {
s = replaceString(s, "\r\n", "\n");
return s;
}
public static String replaceEnter(String s) throws NullPointerException {
return s.replaceAll("\n", "<br>");
}
public static String replacebr(String s) throws NullPointerException {
return s.replaceAll("<br>", "\n");
}
public static String replaceQuote(String s) throws NullPointerException {
return s.replaceAll("'", "''");
}
// Test only.
public static void main(String[] args) throws Exception {
//System.out.println(textToHtml("1<2\r\n<b>Bold</b>"));
//System.out.println(scriptAlert("oh!"));
//System.out.println(scriptRedirect("http://localhost/"));
// System.out.println(StringUtil.getPath("/databaseconfig.properties"));
// java.io.File file = new java.io.File("e:\\Moblog\\abcd\\");
//
// file.mkdir();
Date time = (parseHMSStringToDate("12:23:00"));
System.out.println(time.toLocaleString());
Date nowTime = parseHMSStringToDate(formatDateToHMSString(new Date()));
System.out.println(nowTime.toLocaleString());
// GregorianCalendar cal = new GregorianCalendar();
// cal.setTime(new Date());
// cal.add(cal.YEAR, -cal.get(cal.YEAR) + 1970);
// cal.add(cal.MONTH, -cal.get(cal.MONTH));
// cal.add(cal.DATE, -cal.get(cal.DATE) + 1);
//
// System.out.println(cal.getTime().toLocaleString());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -