package com.tdt.server.httpserver; import java.io.IOException; import java.net.InetSocketAddress; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.spi.HttpServerProvider; /** * * @author chuer * @Description: 服务器启动类 * @date 2014年11月12日 下午3:53:38 * @version V1.0 */ public class MyHttpServer { //启动服务,监听来自客户端的请求 public static void start() throws IOException { Context.load(); HttpServerProvider provider = HttpServerProvider.provider(); HttpServer httpserver =provider.createHttpServer(new InetSocketAddress(8080), 100);//监听端口8080,能同时接 受100个请求 httpserver.createContext(Context.contextPath, new MyHttpHandler()); httpserver.setExecutor(null); httpserver.start(); System.out.println("server started"); } public static void main(String[] args) throws IOException { start(); } }
package com.tdt.server.httpserver; import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.tdt.server.httpserver.core.Handler; import com.tdt.server.httpserver.core.impl.HttpRequest; import com.tdt.server.httpserver.core.impl.HttpResponse; /** * @author chuer * @Description: 内部消息处理类 * @date 2014年11月12日 下午3:53:44 * @version V1.0 */ public class MyHttpHandler implements HttpHandler { public void handle(HttpExchange httpExchange) throws IOException { HttpRequest request = new HttpRequest(httpExchange); HttpResponse response = new HttpResponse(httpExchange); Handler handler = Context.getHandler(request.getReuestURI().getPath()); handler.service(request, response); } }
package com.tdt.server.httpserver; import java.util.HashMap; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.tdt.server.httpserver.core.impl.HttpHandler; import com.tdt.server.httpserver.utils.XmlUtils; /** * * @author chuer * @Description: 上下文 * @date 2014年11月12日 下午3:53:48 * @version V1.0 */ public class Context { private static Map<String,HttpHandler> contextMap = new HashMap<String,HttpHandler>(); public static String contextPath = ""; public static void load(){ try{ Document doc = XmlUtils.load(Context.class.getResource("/").getPath()+"context.xml"); Element root = doc.getDocumentElement(); contextPath = XmlUtils.getAttribute(root,"context"); Element[] handlers = XmlUtils.getChildrenByName(root, "handler"); for(Element ele : handlers){ String handle_class = XmlUtils.getChildText(ele, "handler-class"); String url_pattern = XmlUtils.getChildText(ele, "url-pattern"); Class<?> cls = Class.forName(handle_class); Object newInstance = cls.newInstance(); if(newInstance instanceof HttpHandler){ contextMap.put(contextPath+url_pattern, (HttpHandler)newInstance); } } }catch(Exception e){ e.printStackTrace(); } } /** * * @param key * @return */ public static HttpHandler getHandler(String key){ return contextMap.get(key); } }
<?xml version="1.0" encoding="UTF-8"?> <httpServer context="/myApp"> <handler> <handler-class>com.tdt.server.httpserver.sample.FirstHandler</handler-class> <url-pattern>/firstHandler</url-pattern> </handler> </httpServer>
package com.tdt.server.httpserver.core; /** * * @author chuer * @Description: 相应类接口 * @date 2014年11月12日 下午3:54:02 * @version V1.0 */ public interface Response { public void write(String result); }
package com.tdt.server.httpserver.core; import java.net.URI; /** * @author chuer * @Description: 请求接口 * @date 2014年11月12日 下午3:54:58 * @version V1.0 */ public interface Request { public final static String GET = "GET"; public final static String POST = "POST"; public String getParamter(String param); public String getMethod(); public URI getReuestURI(); public void initRequestHeader(); public void initRequestParam(); public void initRequestBody(); public String getRequestBody(); }
package com.tdt.server.httpserver.core; /** * @author chuer * @Description: 消息处理接口 * @date 2014年11月12日 下午3:55:10 * @version V1.0 */ public interface Handler { public void service(Request request, Response response); public void doGet(Request request, Response response); public void doPost(Request request, Response response); }
package com.tdt.server.httpserver.core.impl; import com.tdt.server.httpserver.core.Handler; import com.tdt.server.httpserver.core.Request; import com.tdt.server.httpserver.core.Response; public abstract class HttpHandler implements Handler { @Override public void service(Request request, Response response) { request.initRequestHeader(); request.initRequestParam(); if(request.getMethod().equals(Request.GET)){ doGet(request,response); }else if(request.getMethod().equals(Request.POST)){ request.initRequestBody(); doPost(request,response); } } @Override public abstract void doGet(Request request, Response response); @Override public abstract void doPost(Request request, Response response); }
package com.tdt.server.httpserver.core.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import com.sun.net.httpserver.HttpExchange; import com.tdt.server.httpserver.core.Request; public class HttpRequest implements Request { private HttpExchange httpExchange; private Map<String, String> paramMap = new HashMap<String, String>(); private Map<String, List<String>> headMap = new HashMap<String, List<String>>(); private String requestBody = ""; public HttpRequest(HttpExchange httpExchange) { this.httpExchange = httpExchange; } @Override public String getParamter(String param) { return paramMap.get(param); } @Override public String getMethod() { return httpExchange.getRequestMethod().trim().toUpperCase(); } @Override public URI getReuestURI() { return httpExchange.getRequestURI(); } @Override public void initRequestParam() { String query = getReuestURI().getQuery(); String [] arrayStr = query.split("&"); for(String str : arrayStr){ paramMap.put(str.split("=")[0], str.split("=")[1]); } } @Override public void initRequestHeader() { for(String s : httpExchange.getRequestHeaders().keySet()){ headMap.put(s, httpExchange.getRequestHeaders().get(s)); } } @Override public void initRequestBody() { InputStream in = httpExchange.getRequestBody(); // 获得输入流 BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String temp = null; try { while ((temp = reader.readLine()) != null) { requestBody += temp; } } catch (IOException e) { e.printStackTrace(); } } @Override public String getRequestBody() { return requestBody; } public static void main(String[] args) { String query = "aaa=aaa&bbb=bbb"; String [] a = query.split("&"); for(String s : a){ System.out.print(s.split("=")[0]+"="); System.out.println(s.split("=")[1]); } } }
package com.tdt.server.httpserver.core.impl; import java.io.IOException; import java.io.OutputStream; import com.sun.net.httpserver.HttpExchange; import com.tdt.server.httpserver.core.Response; public class HttpResponse implements Response{ private HttpExchange httpExchange; public HttpResponse(HttpExchange httpExchange){ this.httpExchange = httpExchange; } @Override public void write(String result) { try { httpExchange.sendResponseHeaders(200, result.length());// 设置响应头属性及响应信息的长度 OutputStream out = httpExchange.getResponseBody(); // 获得输出流 out.write(result.getBytes()); out.flush(); httpExchange.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.tdt.server.httpserver.sample; import com.tdt.server.httpserver.core.Request; import com.tdt.server.httpserver.core.Response; import com.tdt.server.httpserver.core.impl.HttpHandler; public class FirstHandler extends HttpHandler{ @Override public void doGet(Request request, Response response) { System.out.println("doGet"); System.out.println(request.getParamter("aaa")); System.out.println(request.getParamter("bbb")); response.write("helloWorld....."); } @Override public void doPost(Request request, Response response) { System.out.println("doPost"); System.out.println(request.getRequestBody()); response.write("helloWorld....."); } }
启动服务器类,浏览器输出http://localhost:8080/myApp/firstHandler?aaa=aaa&bbb=bbb
显示hello world....
XmlUtils类是用来解析xml文件的,没有放到这里.
重定向代码实例:
<pre class="java" name="code">Headers responseHeaders = httpExchange.getResponseHeaders(); responseHeaders.add("location", "http://www.baidu.com"); httpExchange.sendResponseHeaders(302, 0); httpExchange.close(); OutputStream out = httpExchange.getResponseBody(); out.write(result.getBytes()); out.flush();
工具类:
package com.tdt.server.httpserver.utils; import java.io.CharArrayReader; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * <p> * Title: XmlUtils * </p> * <p> * Description: XML文件处理工具 * </p> * <p> * Copyright: Copyright (c) 2008 * </p> * <p> * Company: Ocean Blue Mobile Tech. * </p> * * @author chur * @version 1.0 */ public class XmlUtils { public static final String BR = System.getProperty("line.separator"); /** * load a xml file from OS file system and interpret it into a Document no * charset limited * * @param xmlfile * String 文件路径名 * @return Document * @throws Exception */ public static Document load(String xmlfile) throws Exception { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(false); factory.setIgnoringElementContentWhitespace(false); factory.setValidating(false); factory.setCoalescing(false); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(xmlfile); } /** * load a xml file from OS file system and interpret it into a Document no * charset limited * * @param xmlfile * String 文件路径名 * @return Document * @throws Exception */ public static Document load(File xmlfile) throws Exception { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(false); factory.setIgnoringElementContentWhitespace(false); factory.setValidating(false); factory.setCoalescing(false); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(xmlfile); } /** * 取得文件名 * * @param filePath * String * @return String */ public static String getFileName(String filePath) { Pattern p = Pattern.compile("[^\\" + File.separator + "]+.xml"); Matcher m = p.matcher(filePath); if (m.find()) { return m.group().substring(0, m.group().length() - 4); } return ""; } /** * 验证文件名是否合法 * * @param filePath * String * @return String */ public static boolean checkValidity(String filePath) { String[] array = filePath.split("."); if (array[array.length - 1].equals("xml")) { return true; } else { return false; } } public static boolean isXml(String file) { if (file.toLowerCase().endsWith("xml")) { return true; } else { return false; } } /** * load a String without the title tag of xml into a Document * * @param domContent * String 没有head的XML内容 * @return Document * @throws Exception */ public static Document loadStringWithoutTitle(String domContent) throws Exception { domContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + BR + domContent; return XmlUtils.loadString(domContent); } /** * load a String with a title tag of xml into a Document * * @param domContent * String XML内容 * @return Document * @throws Exception */ public static Document loadString(String domContent) throws Exception { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(false); factory.setIgnoringElementContentWhitespace(false); factory.setValidating(false); factory.setCoalescing(false); DocumentBuilder builder = factory.newDocumentBuilder(); char[] chars = new char[domContent.length()]; domContent.getChars(0, domContent.length(), chars, 0); InputSource is = new InputSource(new CharArrayReader(chars)); return (builder.parse(is)); } /** * 根据完整路径得到整个文档的一个子节点的文字 * * @param doc * Document 文档 * @param fullname * String 子节点完整路径 * @return String */ public static String getTextByFullName(Document doc, String fullname) { String path[] = StringUtils.toStringArray(fullname, "."); Element e = doc.getDocumentElement(); for (int i = 1; i < path.length; i++) { e = getChildByName(e, path[i]); } return getText(e); } /** * 根据完整路径得到某个节点的一个子节点的文字 * * @param parent * Element 父节点 * @param fullname * String 子节点完整路径 * @return String */ public static String getTextByFullName(Element parent, String fullname) { String path[] = StringUtils.toStringArray(fullname, "."); Element e = parent; for (int i = 0; i < path.length; i++) { e = getChildByName(e, path[i]); } return getText(e); } /** * 根据一个document对象获取某节点下的property的内容 * @param parent * Element * @param name * String * @return String */ public static String getChildText(Element parent, String name) { Element e = getChildByName(parent, name); if (e == null) { return ""; } return getText(e); } /** * 根据名称得到一个父节点下所有的子节点 * * @param e * Element * @param name * String * @return Element[] */ public static Element[] getChildrenByName(Element e, String name) { NodeList nl = e.getChildNodes(); int max = nl.getLength(); LinkedList<Node> list = new LinkedList<Node>(); for (int i = 0; i < max; i++) { Node n = nl.item(i); if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(name)) { list.add(n); } } return list.toArray(new Element[list.size()]); } /** * 根据名字查找某个节点下的符合该名字的节点 * * @param e * Element 父节点 * @param name * String 子节点名称 * @return Element */ public static Element getChildByName(Element e, String name) { Element[] list = getChildrenByName(e, name); if (list.length == 0) { return null; } if (list.length > 1) { throw new IllegalStateException("Too many (" + list.length + ") '" + name + "' elements found!"); } return list[0]; } /** * 得到一个节点的文字 * * @param e * Element * @return String */ public static String getText(Element e) { NodeList nl = e.getChildNodes(); int max = nl.getLength(); for (int i = 0; i < max; i++) { Node n = nl.item(i); if (n.getNodeType() == Node.TEXT_NODE) { return n.getNodeValue(); } } return ""; } public static String getAttribute(Element e, String name) { return e.getAttribute(name); } /** * get Int value * * @param player * @param name * @return */ public static int getIntValue(Element e) { return Integer.valueOf(getText(e)); } /** * get byte value * * @param player * @param name * @return */ public static byte getByteValue(Element e) { return Byte.valueOf(getText(e)); } /** * 获取Properties格式的xml数据 * * @param root * @return */ public static Map<String, Object> getProperties(Element root) { Map<String, Object> map = new HashMap<String, Object>(); Element[] list = getChildrenByName(root, "property"); for (int i = 0; i < list.length; i++) { String name = list[i].getAttribute("name"); String type = list[i].getAttribute("type"); String valueString = getText(list[i]); try { Class<?> cls = Class.forName(type); Constructor<?> con = cls.getConstructor(new Class<?>[] { String.class }); Object value = con.newInstance(new Object[] { valueString }); map.put(name, value); } catch (Exception e) { System.err.println("Unable to parse property '" + name + "'='" + valueString + "': " + e.toString()); } } return map; } /** * 将dom中的内容存入xmlfile所指的文件中。 dom==null时,xml文件也是空的。 * * @param xmlfile * java.lang.String 保存的文件名 * @param doc * ort.w3c.dom.Document 需要保存的DOM * @throws Exception * 任何异常 */ public static void save(String xmlfile, Document doc) throws Exception { // 首先创建一个DOMSource对象,该构造函数的参数可以是一个Document对象 // doc代表更改后的DOM Tree。 DOMSource doms = new DOMSource(doc); // 创建一个File对象,代表DOM Tree所包含的数据的输出介质,这是一个XML文件。 File f = new File(xmlfile); File dir = f.getParentFile(); dir.mkdirs(); // 创建一个StreamResult对象,该构造函数的参数可以取为File对象。 StreamResult sr = new StreamResult(f); // 下面调用JAXP中的XSLT引擎来实现输出DOM Tree中的数据到XML文件中的功能。 // XSLT引擎的输入为DOMSource对象,输出为StreamResut对象。 try { // 首先创建一个TransformerFactory对象,再由此创建Transformer对象。Transformer // 类相当于一个XSLT引擎。通常我们使用它来处理XSL文件,但是在这里我们使 // 用它来输出XML文档。 TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); // 设置新的输出属性:输出字符编码为UTF-8,XSLT引擎所输出 // 的XML文档如果包含了中文字符,可以正常显示,不会出现所谓的"汉字问题"。 // 请留意OutputKeys类的字符串常数OutputKeys.ENCODING。 Properties properties = t.getOutputProperties(); properties.setProperty(OutputKeys.ENCODING, "UTF-8"); properties.setProperty(OutputKeys.INDENT, "yes"); // 更新XSLT引擎的输出属性。 t.setOutputProperties(properties); // 关键的一步, 调用Transformer对象 (XSLT引擎)的transform()方法,该方法的第一 // 个参数是DOMSource对象,第二个参数是StreamResult对象。 t.transform(doms, sr); } catch (TransformerConfigurationException tce) { tce.printStackTrace(); } catch (TransformerException te) { te.printStackTrace(); } } /** * create a blank Document. * * @param rootElementName * String * @return Document * @throws Exception */ public static Document blankDocument(String rootElementName) throws Exception { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(false); factory.setIgnoringElementContentWhitespace(false); factory.setValidating(false); factory.setCoalescing(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element root = doc.createElement(rootElementName); doc.appendChild(root); return doc; } public static Element createChild(Document doc, Element root, String name) { Element elem = doc.createElement(name); root.appendChild(elem); return elem; } public static void createChildText(Document doc, Element elem, String name, String value) { Element child = doc.createElement(name); child.appendChild(doc.createTextNode(value == null ? "" : value)); elem.appendChild(child); } /** * 创建一个带注释的子节点 * * @param doc * Document * @param elem * Element * @param name * String * @param value * String * @param comment * String */ public static void createChildTextWithComment(Document doc, Element elem, String name, String value, String comment) { Element child = doc.createElement(name); child.appendChild(doc.createTextNode(value == null ? "" : value)); Comment c = doc.createComment(comment); elem.appendChild(c); elem.appendChild(child); } /** * 创建一段注释 * * @param doc * Document * @param comment * String */ public static void createComment(Document doc, String comment) { Comment c = doc.createComment(comment); doc.getDocumentElement().appendChild(c); } public static void createOptionalChildText(Document doc, Element elem, String name, String value) { if (value == null || value.length() == 0) { return; } Element child = doc.createElement(name); child.appendChild(doc.createTextNode(value)); elem.appendChild(child); } public static void applyProperties(Object o, Element root) { Map<String,Object> map = getProperties(root); Iterator<String> it = map.keySet().iterator(); Field[] fields = o.getClass().getFields(); Method[] methods = o.getClass().getMethods(); while (it.hasNext()) { String name = (String) it.next(); Object value = map.get(name); try { for (int i = 0; i < fields.length; i++) { if (fields[i].getName().equalsIgnoreCase(name) && isTypeMatch(fields[i].getType(), value.getClass())) { fields[i].set(o, value); System.err.println("Set field " + fields [i].getName() + "=" + value); break; } } for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equalsIgnoreCase("set" + name) && methods[i].getParameterTypes ().length == 1 && isTypeMatch(methods [i].getParameterTypes()[0], value.getClass())) { methods[i].invoke(o, new Object[] { value }); System.err.println("Set method " + methods [i].getName() + "=" + value); break; } } } catch (Exception e) { System.err.println("Unable to apply property '" + name + "': " + e.toString()); } } } private static boolean isTypeMatch(Class<?> one, Class<?> two) { if (one.equals(two)) { return true; } if (one.isPrimitive()) { if (one.getName().equals("int") && two.getName().equals("java.lang.Integer")) { return true; } if (one.getName().equals("long") && two.getName().equals("java.lang.Long")) { return true; } if (one.getName().equals("float") && two.getName().equals("java.lang.Float")) { return true; } if (one.getName().equals("double") && two.getName().equals("java.lang.Double")) { return true; } if (one.getName().equals("char") && two.getName().equals("java.lang.Character")) { return true; } if (one.getName().equals("byte") && two.getName().equals("java.lang.Byte")) { return true; } if (one.getName().equals("short") && two.getName().equals("java.lang.Short")) { return true; } if (one.getName().equals("boolean") && two.getName().equals("java.lang.Boolean")) { return true; } } return false; } }
package com.tdt.server.httpserver.utils; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtils { /** * Converts a line of text into an array of lower case words. Words are * delimited by the following characters: , .\r\n:/\+ * <p> * In the future, this method should be changed to use a * BreakIterator.wordInstance(). That class offers much more fexibility. * * @param text * a String of text to convert into an array of words * @return text broken up into an array of words. */ public static final String[] toLowerCaseWordArray(String text) { if (text == null || text.length() == 0) { return new String[0]; } StringTokenizer tokens = new StringTokenizer(text, " ,\r\n.:/\\+"); String[] words = new String[tokens.countTokens()]; for (int i = 0; i < words.length; i++) { words[i] = tokens.nextToken().toLowerCase(); } return words; } /** * Converts a line of text into an array of lower case words. Words are * delimited by the following characters: , .\r\n:/\+ * <p> * In the future, this method should be changed to use a * BreakIterator.wordInstance(). That class offers much more fexibility. * * @param text * a String of text to convert into an array of words * @return text broken up into an array of words. */ public static final String[] toStringArray(String text) { if (text == null || text.length() == 0) { return new String[0]; } StringTokenizer tokens = new StringTokenizer(text, ",\r\n/\\"); String[] words = new String[tokens.countTokens()]; for (int i = 0; i < words.length; i++) { words[i] = tokens.nextToken(); } return words; } /** * * Converts a line of text into an array of lower case words. Words are * delimited by the following characters: , .\r\n:/\+ * <p> * In the future, this method should be changed to use a * BreakIterator.wordInstance(). That class offers much more fexibility. * * @param text * a String of text to convert into an array of words * @param token * String * @return String[]broken up into an array of words. */ public static final String[] toStringArray(String text, String token) { if (text == null || text.length() == 0) { return new String[0]; } StringTokenizer tokens = new StringTokenizer(text, token); String[] words = new String[tokens.countTokens()]; for (int i = 0; i < words.length; i++) { words[i] = tokens.nextToken(); } return words; } /** * * @param source * @return */ public static String[] splitOnWhitespace(String source) { int pos = -1; LinkedList<String> list = new LinkedList<String>(); int max = source.length(); for (int i = 0; i < max; i++) { char c = source.charAt(i); if (Character.isWhitespace(c)) { if (i - pos > 1) { list.add(source.substring(pos + 1, i)); } pos = i; } } return list.toArray(new String[list.size()]); } /** * Replayer str * * @param str * @param key * @param replacement * @return */ public static final String replaceAll(String str, String key, String replacement) { if (str != null && key != null && replacement != null && !str.equals("") && !key.equals("")) { StringBuilder strbuf = new StringBuilder(); int begin = 0; int slen = str.length(); int npos = 0; int klen = key.length(); for (; begin < slen && (npos = str.indexOf(key, begin)) >= begin; begin = npos + klen) { strbuf.append(str.substring(begin, npos)).append(replacement); } if (begin == 0) { return str; } if (begin < slen) { strbuf.append(str.substring(begin)); } return strbuf.toString(); } else { return str; } } public static String UnicodeToString(String str) { Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))"); Matcher matcher = pattern.matcher(str); char ch; boolean hasU = false; while (matcher.find()) { hasU = true; ch = (char) Integer.parseInt(matcher.group(2), 16); str = str.replace(matcher.group(1), ch + ""); } String s = str; try{ if(!hasU){ int i = 0; String rstr = ""; while(i+4<=str.length()){ ch = (char) Integer.parseInt(str.substring(i,i=i+4), 16); rstr = rstr+ch; } str = rstr; } }catch(Exception ex){ str = s; ex.printStackTrace(); } return str; } /** 空字符串。 */ public static final String EMPTY_STRING = ""; /** * 比较两个字符串(大小写敏感)。 * <pre> * StringUtil.equals(null, null) = true * StringUtil.equals(null, "abc") = false * StringUtil.equals("abc", null) = false * StringUtil.equals("abc", "abc") = true * StringUtil.equals("abc", "ABC") = false * </pre> * * @param str1 要比较的字符串1 * @param str2 要比较的字符串2 * * @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code> */ public static boolean equals(String str1, String str2) { if (str1 == null) { return str2 == null; } return str1.equals(str2); } /** * 比较两个字符串(大小写不敏感)。 * <pre> * StringUtil.equalsIgnoreCase(null, null) = true * StringUtil.equalsIgnoreCase(null, "abc") = false * StringUtil.equalsIgnoreCase("abc", null) = false * StringUtil.equalsIgnoreCase("abc", "abc") = true * StringUtil.equalsIgnoreCase("abc", "ABC") = true * </pre> * * @param str1 要比较的字符串1 * @param str2 要比较的字符串2 * * @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code> */ public static boolean equalsIgnoreCase(String str1, String str2) { if (str1 == null) { return str2 == null; } return str1.equalsIgnoreCase(str2); } /** * 检查字符串是否是空白:<code>null</code>、空字符串<code>""</code>或只有空白字符。 * <pre> * StringUtil.isBlank(null) = true * StringUtil.isBlank("") = true * StringUtil.isBlank(" ") = true * StringUtil.isBlank("bob") = false * StringUtil.isBlank(" bob ") = false * </pre> * * @param str 要检查的字符串 * * @return 如果为空白, 则返回<code>true</code> */ public static boolean isBlank(String str) { int length; if ((str == null) || ((length = str.length()) == 0)) { return true; } for (int i = 0; i < length; i++) { if (!Character.isWhitespace(str.charAt(i))) { return false; } } return true; } /** * 检查字符串是否不是空白:<code>null</code>、空字符串<code>""</code>或只有空白字符。 * <pre> * StringUtil.isBlank(null) = false * StringUtil.isBlank("") = false * StringUtil.isBlank(" ") = false * StringUtil.isBlank("bob") = true * StringUtil.isBlank(" bob ") = true * </pre> * * @param str 要检查的字符串 * * @return 如果为空白, 则返回<code>true</code> */ public static boolean isNotBlank(String str) { int length; if ((str == null) || ((length = str.length()) == 0)) { return false; } for (int i = 0; i < length; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * 检查字符串是否为<code>null</code>或空字符串<code>""</code>。 * <pre> * StringUtil.isEmpty(null) = true * StringUtil.isEmpty("") = true * StringUtil.isEmpty(" ") = false * StringUtil.isEmpty("bob") = false * StringUtil.isEmpty(" bob ") = false * </pre> * * @param str 要检查的字符串 * * @return 如果为空, 则返回<code>true</code> */ public static boolean isEmpty(String str) { return ((str == null) || (str.length() == 0)); } /** * 检查字符串是否不是<code>null</code>和空字符串<code>""</code>。 * <pre> * StringUtil.isEmpty(null) = false * StringUtil.isEmpty("") = false * StringUtil.isEmpty(" ") = true * StringUtil.isEmpty("bob") = true * StringUtil.isEmpty(" bob ") = true * </pre> * * @param str 要检查的字符串 * * @return 如果不为空, 则返回<code>true</code> */ public static boolean isNotEmpty(String str) { return ((str != null) && (str.length() > 0)); } /** * 在字符串中查找指定字符串,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>。 * <pre> * StringUtil.indexOf(null, *) = -1 * StringUtil.indexOf(*, null) = -1 * StringUtil.indexOf("", "") = 0 * StringUtil.indexOf("aabaabaa", "a") = 0 * StringUtil.indexOf("aabaabaa", "b") = 2 * StringUtil.indexOf("aabaabaa", "ab") = 1 * StringUtil.indexOf("aabaabaa", "") = 0 * </pre> * * @param str 要扫描的字符串 * @param searchStr 要查找的字符串 * * @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code> */ public static int indexOf(String str, String searchStr) { if ((str == null) || (searchStr == null)) { return -1; } return str.indexOf(searchStr); } /** * 在字符串中查找指定字符串,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>。 * <pre> * StringUtil.indexOf(null, *, *) = -1 * StringUtil.indexOf(*, null, *) = -1 * StringUtil.indexOf("", "", 0) = 0 * StringUtil.indexOf("aabaabaa", "a", 0) = 0 * StringUtil.indexOf("aabaabaa", "b", 0) = 2 * StringUtil.indexOf("aabaabaa", "ab", 0) = 1 * StringUtil.indexOf("aabaabaa", "b", 3) = 5 * StringUtil.indexOf("aabaabaa", "b", 9) = -1 * StringUtil.indexOf("aabaabaa", "b", -1) = 2 * StringUtil.indexOf("aabaabaa", "", 2) = 2 * StringUtil.indexOf("abc", "", 9) = 3 * </pre> * * @param str 要扫描的字符串 * @param searchStr 要查找的字符串 * @param startPos 开始搜索的索引值,如果小于0,则看作0 * * @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code> */ public static int indexOf(String str, String searchStr, int startPos) { if ((str == null) || (searchStr == null)) { return -1; } // JDK1.3及以下版本的bug:不能正确处理下面的情况 if ((searchStr.length() == 0) && (startPos >= str.length())) { return str.length(); } return str.indexOf(searchStr, startPos); } /** * 取指定字符串的子串。 * * <p> * 负的索引代表从尾部开始计算。如果字符串为<code>null</code>,则返回<code>null</code>。 * <pre> * StringUtil.substring(null, *, *) = null * StringUtil.substring("", * , *) = ""; * StringUtil.substring("abc", 0, 2) = "ab" * StringUtil.substring("abc", 2, 0) = "" * StringUtil.substring("abc", 2, 4) = "c" * StringUtil.substring("abc", 4, 6) = "" * StringUtil.substring("abc", 2, 2) = "" * StringUtil.substring("abc", -2, -1) = "b" * StringUtil.substring("abc", -4, 2) = "ab" * </pre> * </p> * * @param str 字符串 * @param start 起始索引,如果为负数,表示从尾部计算 * @param end 结束索引(不含),如果为负数,表示从尾部计算 * * @return 子串,如果原始串为<code>null</code>,则返回<code>null</code> */ public static String substring(String str, int start, int end) { if (str == null) { return null; } if (end < 0) { end = str.length() + end; } if (start < 0) { start = str.length() + start; } if (end > str.length()) { end = str.length(); } if (start > end) { return EMPTY_STRING; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } /** * 检查字符串中是否包含指定的字符串。如果字符串为<code>null</code>,将返回<code>false</code>。 * <pre> * StringUtil.contains(null, *) = false * StringUtil.contains(*, null) = false * StringUtil.contains("", "") = true * StringUtil.contains("abc", "") = true * StringUtil.contains("abc", "a") = true * StringUtil.contains("abc", "z") = false * </pre> * * @param str 要扫描的字符串 * @param searchStr 要查找的字符串 * * @return 如果找到,则返回<code>true</code> */ public static boolean contains(String str, String searchStr) { if ((str == null) || (searchStr == null)) { return false; } return str.indexOf(searchStr) >= 0; } /** * <p>Checks if the String contains only unicode digits. * A decimal point is not a unicode digit and returns false.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isNumeric(null) = false * StringUtils.isNumeric("") = true * StringUtils.isNumeric(" ") = false * StringUtils.isNumeric("123") = true * StringUtils.isNumeric("12 3") = false * StringUtils.isNumeric("ab2c") = false * StringUtils.isNumeric("12-3") = false * StringUtils.isNumeric("12.3") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains digits, and is non-null */ public static boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false) { return false; } } return true; } /** * 字符串拼接 * @param object * @return */ public static String assemble(char sep,Object... object){ if(object == null)return null; StringBuilder sb = new StringBuilder(); for(Object obj:object){ if(obj == null)obj=""; sb.append(obj.toString()).append(sep); } String str = ""; if(sb.length()>0){ str = sb.substring(0, sb.length()-1); } return str; } // 6-16个字母和数字组成 private static String regex = "^[A-Za-z0-9]$"; /** * 检测字符串是否符合规则(6-16个字母和数字组成,大小写不敏感) * @param user * @return */ public static boolean checkStringLegal(String user) { boolean isMatch = true; char[] userChars = user.toCharArray(); for(char c : userChars){ isMatch = String.valueOf(c).matches(regex); if(!isMatch){ break; } } return isMatch; } public static String getString(String input) { return getString(input, true, ""); } public static String getString(String input, boolean btrim, String dval) { if (input == null) return dval; try { if (btrim) return trim(input); else return input; } catch (Exception e) { return ""; } } public static String Trim(String str) { return trim(str); } public static String[] Trim(String[] s) { return trim(s); } public static String trim(String str) { if (str == null) return ""; else return str.trim(); } public static String[] trim(String[] s) { if (s == null || s.length <= 0) return s; for (int i = 0; i < s.length; i++) s[i] = trim(s[i]); return s; } public static int getInt(String input, boolean btrim, int dval) { if (input == null) return dval; int val; try { String str = new String(input); if (btrim) str = trim(str); val = Integer.parseInt(str); } catch (Exception e) { val = dval; } return val; } public static int[] getInts(String input) { return getInts(input, ","); } public static int[] getInts(String input, String split) { if (input == null) { return null; } String[] ss = input.split(split); int[] ii = new int[ss.length]; for (int i=0;i<ii.length;i++) { ii[i] = getInt(ss[i]); } return ii; } public static int getInt(String input) { return getInt(input, true, 0); } }