String getMyHostname(HttpServletRequest request) {
try {
String host = request.getRemoteHost().toUpperCase();
return host;
} catch (Exception e) { return null; }
}
String dealNull(String str) { return str == null ? "" : str; }
Object dealNull(Object obj) { return obj == null ? "" : obj; }
int dealEmpty(String s) { s = dealNull(s); return s.equals("") ? 0 : Integer.parseInt(s); }
String replace(String str, String substr, String restr) {
String[] parts = str.split(substr);
if (parts.length == 0) return "";
StringBuilder sb = new StringBuilder(parts[0]);
for (int i = 1; i < parts.length; i++) {
sb.append(restr).append(parts[i]);
}
return sb.toString();
}
String htmlEncode(String txt) {
txt = replace(txt, "&", "&");
txt = replace(txt, "\"", """);
txt = replace(txt, "<", "<");
txt = replace(txt, ">", ">");
txt = replace(txt, " ", " ");
return txt;
}
String unHtmlEncode(String txt) {
txt = replace(txt, "&", "&");
txt = replace(txt, """, "\"");
txt = replace(txt, "<", "<");
txt = replace(txt, ">", ">");
txt = replace(txt, " ", " ");
return txt;
}
void sAlert(String title, String msg, String focus, JspWriter out) {
out.println("");
}
void sConfirm(String title, String msg, String location, JspWriter out) {
out.println("");
}
int getStringLength(String s) {
try { return s.getBytes("Shift_JIS").length; }
catch (UnsupportedEncodingException e) { return 0; }
}
void formatString(String s, int width, JspWriter out) {
width--;
int len = getStringLength(s);
if (len > width) {
int cut = 0;
for (int i = 1; i <= width; i++) {
if (s.substring(0, i).getBytes("Shift_JIS").length <= width) cut = i;
else break;
}
for (int i = 0; i < cut; i++) {
String ch = s.substring(i, i+1);
out.print(ch.equals(" ") ? " " : htmlEncode(ch));
}
out.print(s.substring(0, cut).getBytes("Shift_JIS").length == width ? "|" : " |");
} else {
for (int i = 0; i < width - len; i++) out.print(" ");
for (int i = 0; i < s.length(); i++) {
String ch = s.substring(i, i+1);
out.print(ch.equals(" ") ? " " : htmlEncode(ch));
}
out.print(htmlEncode(" |"));
}
}
boolean isNumeric(String s) {
try { Integer.parseInt(s); return true; }
catch (NumberFormatException e) { return false; }
}
String mkDate(String dateStr, int mode) {
// mode 0: YYMMDD -> YY/MM/DD
// mode 1: YYMMDD 補零 -> 19/20YY/MM/DD
// mode 2: YYYY/MM/DD -> YYYYMMDD
// mode 3: YYMMDD 判斷世紀 -> CCYYMMDD
// mode 4: YYYYMMDD -> YYYY/MM/DD
// mode 5: YYYY/MM -> YYYYMM
// 具體實現略...
return formatted;
}
這些方法覆蓋了 JSP/Servlet 開發中 80% 的字符串處理、前端交互與數據格式化需求,可直接封裝為工具類復用。