`

java HttpServer构建http服务器

阅读更多
  1. package com.tdt.server.httpserver;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5.   
  6. import com.sun.net.httpserver.HttpServer;  
  7. import com.sun.net.httpserver.spi.HttpServerProvider;  
  8. /** 
  9.  *  
  10.  * @author chuer 
  11.  * @Description: 服务器启动类 
  12.  * @date 2014年11月12日 下午3:53:38  
  13.  * @version V1.0 
  14.  */  
  15. public class MyHttpServer {  
  16.     //启动服务,监听来自客户端的请求  
  17.     public static void start() throws IOException {  
  18.         Context.load();  
  19.           
  20.         HttpServerProvider provider = HttpServerProvider.provider();  
  21.         HttpServer httpserver =provider.createHttpServer(new InetSocketAddress(8080), 100);//监听端口8080,能同时接 受100个请求  
  22.         httpserver.createContext(Context.contextPath, new MyHttpHandler());   
  23.         httpserver.setExecutor(null);  
  24.         httpserver.start();  
  25.         System.out.println("server started");  
  26.     }  
  27.       
  28.       
  29.     public static void main(String[] args) throws IOException {  
  30.         start();  
  31.     }  
  32. }  

 

  1. package com.tdt.server.httpserver;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.sun.net.httpserver.HttpExchange;  
  6. import com.sun.net.httpserver.HttpHandler;  
  7. import com.tdt.server.httpserver.core.Handler;  
  8. import com.tdt.server.httpserver.core.impl.HttpRequest;  
  9. import com.tdt.server.httpserver.core.impl.HttpResponse;  
  10.   
  11. /** 
  12.  * @author chuer 
  13.  * @Description: 内部消息处理类 
  14.  * @date 2014年11月12日 下午3:53:44  
  15.  * @version V1.0 
  16.  */  
  17. public class MyHttpHandler implements HttpHandler {  
  18.   
  19.     public void handle(HttpExchange httpExchange) throws IOException {  
  20.         HttpRequest request = new HttpRequest(httpExchange);  
  21.         HttpResponse response = new HttpResponse(httpExchange);  
  22.         Handler handler = Context.getHandler(request.getReuestURI().getPath());  
  23.         handler.service(request, response);  
  24.   
  25.     }  
  26. }  

 

  1. package com.tdt.server.httpserver;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import org.w3c.dom.Document;  
  7. import org.w3c.dom.Element;  
  8.   
  9. import com.tdt.server.httpserver.core.impl.HttpHandler;  
  10. import com.tdt.server.httpserver.utils.XmlUtils;  
  11. /** 
  12.  *  
  13.  * @author chuer 
  14.  * @Description: 上下文  
  15.  * @date 2014年11月12日 下午3:53:48  
  16.  * @version V1.0 
  17.  */  
  18. public class Context {  
  19.     private static Map<String,HttpHandler> contextMap = new HashMap<String,HttpHandler>();  
  20.     public static String contextPath = "";  
  21.     public static void load(){  
  22.         try{  
  23.             Document doc = XmlUtils.load(Context.class.getResource("/").getPath()+"context.xml");  
  24.             Element root = doc.getDocumentElement();  
  25.               
  26.             contextPath = XmlUtils.getAttribute(root,"context");  
  27.             Element[] handlers = XmlUtils.getChildrenByName(root, "handler");  
  28.             for(Element ele : handlers){  
  29.                 String handle_class = XmlUtils.getChildText(ele, "handler-class");  
  30.                 String url_pattern = XmlUtils.getChildText(ele, "url-pattern");  
  31.                   
  32.                 Class<?> cls = Class.forName(handle_class);  
  33.                 Object newInstance = cls.newInstance();  
  34.                 if(newInstance instanceof HttpHandler){  
  35.                     contextMap.put(contextPath+url_pattern, (HttpHandler)newInstance);  
  36.                 }  
  37.             }  
  38.         }catch(Exception e){  
  39.             e.printStackTrace();  
  40.         }  
  41.     }  
  42.       
  43.     /** 
  44.      *  
  45.      * @param key 
  46.      * @return 
  47.      */  
  48.     public static HttpHandler getHandler(String key){  
  49.         return contextMap.get(key);  
  50.     }  
  51.       
  52. }  

 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <httpServer context="/myApp">  
  3.     <handler>  
  4.         <handler-class>com.tdt.server.httpserver.sample.FirstHandler</handler-class>  
  5.         <url-pattern>/firstHandler</url-pattern>  
  6.     </handler>  
  7.       
  8.       
  9. </httpServer>  

 

  1. package com.tdt.server.httpserver.core;  
  2. /** 
  3.  *  
  4.  * @author chuer 
  5.  * @Description: 相应类接口 
  6.  * @date 2014年11月12日 下午3:54:02  
  7.  * @version V1.0 
  8.  */  
  9. public interface Response {  
  10.       
  11.     public void write(String result);  
  12.       
  13. }  

 

  1. package com.tdt.server.httpserver.core;  
  2.   
  3. import java.net.URI;  
  4. /** 
  5.  * @author chuer 
  6.  * @Description: 请求接口 
  7.  * @date 2014年11月12日 下午3:54:58  
  8.  * @version V1.0 
  9.  */  
  10. public interface Request {  
  11.     public final static String GET = "GET";  
  12.     public final static String POST = "POST";  
  13.   
  14.     public String getParamter(String param);  
  15.   
  16.     public String getMethod();  
  17.   
  18.     public URI getReuestURI();  
  19.   
  20.     public void initRequestHeader();  
  21.       
  22.     public void initRequestParam();  
  23.   
  24.     public void initRequestBody();  
  25.   
  26.     public String getRequestBody();  
  27. }  

 

  1. package com.tdt.server.httpserver.core;  
  2. /** 
  3.  * @author chuer 
  4.  * @Description: 消息处理接口 
  5.  * @date 2014年11月12日 下午3:55:10  
  6.  * @version V1.0 
  7.  */  
  8. public interface Handler {  
  9.     public void service(Request request, Response response);  
  10.   
  11.     public void doGet(Request request, Response response);  
  12.   
  13.     public void doPost(Request request, Response response);  
  14.   
  15. }  

 

  1. package com.tdt.server.httpserver.core.impl;  
  2.   
  3. import com.tdt.server.httpserver.core.Handler;  
  4. import com.tdt.server.httpserver.core.Request;  
  5. import com.tdt.server.httpserver.core.Response;  
  6.   
  7. public abstract class HttpHandler implements Handler {  
  8.   
  9.     @Override  
  10.     public void service(Request request, Response response) {  
  11.         request.initRequestHeader();  
  12.         request.initRequestParam();  
  13.         if(request.getMethod().equals(Request.GET)){  
  14.             doGet(request,response);  
  15.         }else if(request.getMethod().equals(Request.POST)){  
  16.             request.initRequestBody();  
  17.             doPost(request,response);  
  18.         }  
  19.     }  
  20.   
  21.     @Override  
  22.     public abstract void doGet(Request request, Response response);  
  23.   
  24.     @Override  
  25.     public abstract void doPost(Request request, Response response);  
  26.   
  27.       
  28. }  

 

  1. package com.tdt.server.httpserver.core.impl;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.net.URI;  
  8. import java.util.HashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import com.sun.net.httpserver.HttpExchange;  
  13. import com.tdt.server.httpserver.core.Request;  
  14.   
  15. public class HttpRequest implements Request {  
  16.     private HttpExchange httpExchange;  
  17.     private Map<String, String> paramMap = new HashMap<String, String>();  
  18.     private Map<String, List<String>> headMap = new HashMap<String, List<String>>();  
  19.     private String requestBody = "";  
  20.   
  21.     public HttpRequest(HttpExchange httpExchange) {  
  22.         this.httpExchange = httpExchange;  
  23.     }  
  24.   
  25.     @Override  
  26.     public String getParamter(String param) {  
  27.         return paramMap.get(param);  
  28.     }  
  29.   
  30.     @Override  
  31.     public String getMethod() {  
  32.         return httpExchange.getRequestMethod().trim().toUpperCase();  
  33.     }  
  34.   
  35.     @Override  
  36.     public URI getReuestURI() {  
  37.         return httpExchange.getRequestURI();  
  38.     }  
  39.   
  40.     @Override  
  41.     public void initRequestParam() {  
  42.         String query = getReuestURI().getQuery();  
  43.         String [] arrayStr = query.split("&");  
  44.         for(String str : arrayStr){  
  45.             paramMap.put(str.split("=")[0], str.split("=")[1]);  
  46.         }  
  47.           
  48.     }  
  49.   
  50.     @Override  
  51.     public void initRequestHeader() {  
  52.         for(String s : httpExchange.getRequestHeaders().keySet()){  
  53.             headMap.put(s, httpExchange.getRequestHeaders().get(s));  
  54.         }  
  55.     }  
  56.   
  57.     @Override  
  58.     public void initRequestBody() {  
  59.         InputStream in = httpExchange.getRequestBody(); // 获得输入流  
  60.         BufferedReader reader = new BufferedReader(new InputStreamReader(in));  
  61.         String temp = null;  
  62.         try {  
  63.             while ((temp = reader.readLine()) != null) {  
  64.                 requestBody += temp;  
  65.             }  
  66.         } catch (IOException e) {  
  67.             e.printStackTrace();  
  68.         }  
  69.     }  
  70.   
  71.     @Override  
  72.     public String getRequestBody() {  
  73.         return requestBody;  
  74.     }  
  75.       
  76.     public static void main(String[] args) {  
  77.           
  78.         String query = "aaa=aaa&bbb=bbb";  
  79.         String [] a = query.split("&");  
  80.         for(String s : a){  
  81.             System.out.print(s.split("=")[0]+"=");  
  82.             System.out.println(s.split("=")[1]);  
  83.               
  84.         }  
  85.           
  86.           
  87.           
  88.     }  
  89.   
  90. }  

 

  1. package com.tdt.server.httpserver.core.impl;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5.   
  6. import com.sun.net.httpserver.HttpExchange;  
  7. import com.tdt.server.httpserver.core.Response;  
  8.   
  9. public class HttpResponse implements Response{  
  10.     private HttpExchange httpExchange;  
  11.     public HttpResponse(HttpExchange httpExchange){  
  12.         this.httpExchange = httpExchange;  
  13.     }  
  14.       
  15.       
  16.     @Override  
  17.     public void write(String result) {  
  18.         try {  
  19.             httpExchange.sendResponseHeaders(200, result.length());// 设置响应头属性及响应信息的长度  
  20.             OutputStream out = httpExchange.getResponseBody(); // 获得输出流  
  21.             out.write(result.getBytes());  
  22.             out.flush();  
  23.             httpExchange.close();  
  24.         } catch (IOException e) {  
  25.             e.printStackTrace();  
  26.         }   
  27.           
  28.     }  
  29.   
  30.       
  31. }  

 

  1. package com.tdt.server.httpserver.sample;  
  2.   
  3. import com.tdt.server.httpserver.core.Request;  
  4. import com.tdt.server.httpserver.core.Response;  
  5. import com.tdt.server.httpserver.core.impl.HttpHandler;  
  6.   
  7. public class FirstHandler extends HttpHandler{  
  8.   
  9.     @Override  
  10.     public void doGet(Request request, Response response) {  
  11.         System.out.println("doGet");  
  12.           
  13.         System.out.println(request.getParamter("aaa"));  
  14.         System.out.println(request.getParamter("bbb"));  
  15.           
  16.         response.write("helloWorld.....");  
  17.     }  
  18.   
  19.       
  20.     @Override  
  21.     public void doPost(Request request, Response response) {  
  22.         System.out.println("doPost");  
  23.         System.out.println(request.getRequestBody());  
  24.           
  25.         response.write("helloWorld.....");  
  26.     }  
  27.   
  28.       
  29. }  


启动服务器类,浏览器输出http://localhost:8080/myApp/firstHandler?aaa=aaa&bbb=bbb

显示hello world....

 

XmlUtils类是用来解析xml文件的,没有放到这里.

 

重定向代码实例:

  1. <pre class="java" name="code">Headers responseHeaders = httpExchange.getResponseHeaders();  
  2.             responseHeaders.add("location""http://www.baidu.com");  
  3.             httpExchange.sendResponseHeaders(3020);  
  4.             httpExchange.close();  
  5.             OutputStream out = httpExchange.getResponseBody();   
  6.             out.write(result.getBytes());  
  7.             out.flush();  

 

 

工具类:

  1. package com.tdt.server.httpserver.utils;  
  2.   
  3. import java.io.CharArrayReader;  
  4. import java.io.File;  
  5. import java.lang.reflect.Constructor;  
  6. import java.lang.reflect.Field;  
  7. import java.lang.reflect.Method;  
  8. import java.util.HashMap;  
  9. import java.util.Iterator;  
  10. import java.util.LinkedList;  
  11. import java.util.Map;  
  12. import java.util.Properties;  
  13. import java.util.regex.Matcher;  
  14. import java.util.regex.Pattern;  
  15.   
  16. import javax.xml.parsers.DocumentBuilder;  
  17. import javax.xml.transform.OutputKeys;  
  18. import javax.xml.transform.Transformer;  
  19. import javax.xml.transform.TransformerConfigurationException;  
  20. import javax.xml.transform.TransformerException;  
  21. import javax.xml.transform.TransformerFactory;  
  22. import javax.xml.transform.dom.DOMSource;  
  23. import javax.xml.transform.stream.StreamResult;  
  24.   
  25. import org.w3c.dom.Comment;  
  26. import org.w3c.dom.Document;  
  27. import org.w3c.dom.Element;  
  28. import org.w3c.dom.Node;  
  29. import org.w3c.dom.NodeList;  
  30. import org.xml.sax.InputSource;  
  31.   
  32. /** 
  33.  * <p> 
  34.  * Title: XmlUtils 
  35.  * </p> 
  36.  * <p> 
  37.  * Description: XML文件处理工具 
  38.  * </p> 
  39.  * <p> 
  40.  * Copyright: Copyright (c) 2008 
  41.  * </p> 
  42.  * <p> 
  43.  * Company: Ocean Blue Mobile Tech. 
  44.  * </p> 
  45.  *  
  46.  * @author chur 
  47.  * @version 1.0 
  48.  */  
  49. public class XmlUtils {  
  50.     public static final String BR = System.getProperty("line.separator");  
  51.   
  52.     /** 
  53.      * load a xml file from OS file system and interpret it into a Document no 
  54.      * charset limited 
  55.      *  
  56.      * @param xmlfile 
  57.      *            String 文件路径名 
  58.      * @return Document 
  59.      * @throws Exception 
  60.      */  
  61.     public static Document load(String xmlfile) throws Exception {  
  62.         javax.xml.parsers.DocumentBuilderFactory factory =  
  63.   
  64.         javax.xml.parsers.DocumentBuilderFactory.newInstance();  
  65.         factory.setIgnoringComments(false);  
  66.         factory.setIgnoringElementContentWhitespace(false);  
  67.         factory.setValidating(false);  
  68.         factory.setCoalescing(false);  
  69.         DocumentBuilder builder = factory.newDocumentBuilder();  
  70.   
  71.         return builder.parse(xmlfile);  
  72.     }  
  73.   
  74.     /** 
  75.      * load a xml file from OS file system and interpret it into a Document no 
  76.      * charset limited 
  77.      *  
  78.      * @param xmlfile 
  79.      *            String 文件路径名 
  80.      * @return Document 
  81.      * @throws Exception 
  82.      */  
  83.     public static Document load(File xmlfile) throws Exception {  
  84.         javax.xml.parsers.DocumentBuilderFactory factory =  
  85.   
  86.         javax.xml.parsers.DocumentBuilderFactory.newInstance();  
  87.         factory.setIgnoringComments(false);  
  88.         factory.setIgnoringElementContentWhitespace(false);  
  89.         factory.setValidating(false);  
  90.         factory.setCoalescing(false);  
  91.         DocumentBuilder builder = factory.newDocumentBuilder();  
  92.   
  93.         return builder.parse(xmlfile);  
  94.     }  
  95.   
  96.     /** 
  97.      * 取得文件名 
  98.      *  
  99.      * @param filePath 
  100.      *            String 
  101.      * @return String 
  102.      */  
  103.     public static String getFileName(String filePath) {  
  104.         Pattern p = Pattern.compile("[^\\" + File.separator + "]+.xml");  
  105.         Matcher m = p.matcher(filePath);  
  106.         if (m.find()) {  
  107.             return m.group().substring(0, m.group().length() - 4);  
  108.         }  
  109.         return "";  
  110.     }  
  111.   
  112.     /** 
  113.      * 验证文件名是否合法 
  114.      *  
  115.      * @param filePath 
  116.      *            String 
  117.      * @return String 
  118.      */  
  119.     public static boolean checkValidity(String filePath) {  
  120.         String[] array = filePath.split(".");  
  121.         if (array[array.length - 1].equals("xml")) {  
  122.             return true;  
  123.         } else {  
  124.             return false;  
  125.         }  
  126.     }  
  127.   
  128.     public static boolean isXml(String file) {  
  129.         if (file.toLowerCase().endsWith("xml")) {  
  130.             return true;  
  131.         } else {  
  132.             return false;  
  133.         }  
  134.     }  
  135.   
  136.     /** 
  137.      * load a String without the title tag of xml into a Document 
  138.      *  
  139.      * @param domContent 
  140.      *            String 没有head的XML内容 
  141.      * @return Document 
  142.      * @throws Exception 
  143.      */  
  144.     public static Document loadStringWithoutTitle(String domContent)  
  145.             throws Exception {  
  146.         domContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + BR  
  147.                 + domContent;  
  148.         return XmlUtils.loadString(domContent);  
  149.     }  
  150.   
  151.     /** 
  152.      * load a String with a title tag of xml into a Document 
  153.      *  
  154.      * @param domContent 
  155.      *            String XML内容 
  156.      * @return Document 
  157.      * @throws Exception 
  158.      */  
  159.     public static Document loadString(String domContent) throws Exception {  
  160.         javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();  
  161.         factory.setIgnoringComments(false);  
  162.         factory.setIgnoringElementContentWhitespace(false);  
  163.         factory.setValidating(false);  
  164.         factory.setCoalescing(false);  
  165.         DocumentBuilder builder = factory.newDocumentBuilder();  
  166.   
  167.         char[] chars = new char[domContent.length()];  
  168.         domContent.getChars(0, domContent.length(), chars, 0);  
  169.         InputSource is = new InputSource(new CharArrayReader(chars));  
  170.         return (builder.parse(is));  
  171.     }  
  172.   
  173.     /** 
  174.      * 根据完整路径得到整个文档的一个子节点的文字 
  175.      *  
  176.      * @param doc 
  177.      *            Document 文档 
  178.      * @param fullname 
  179.      *            String 子节点完整路径 
  180.      * @return String 
  181.      */  
  182.     public static String getTextByFullName(Document doc, String fullname) {  
  183.         String path[] = StringUtils.toStringArray(fullname, ".");  
  184.         Element e = doc.getDocumentElement();  
  185.         for (int i = 1; i < path.length; i++) {  
  186.             e = getChildByName(e, path[i]);  
  187.         }  
  188.         return getText(e);  
  189.     }  
  190.   
  191.     /** 
  192.      * 根据完整路径得到某个节点的一个子节点的文字 
  193.      *  
  194.      * @param parent 
  195.      *            Element 父节点 
  196.      * @param fullname 
  197.      *            String 子节点完整路径 
  198.      * @return String 
  199.      */  
  200.     public static String getTextByFullName(Element parent, String fullname) {  
  201.         String path[] = StringUtils.toStringArray(fullname, ".");  
  202.         Element e = parent;  
  203.         for (int i = 0; i < path.length; i++) {  
  204.             e = getChildByName(e, path[i]);  
  205.         }  
  206.         return getText(e);  
  207.     }  
  208.   
  209.     /** 
  210.      * 根据一个document对象获取某节点下的property的内容 
  211.      * @param parent 
  212.      *            Element 
  213.      * @param name 
  214.      *            String 
  215.      * @return String 
  216.      */  
  217.     public static String getChildText(Element parent, String name) {  
  218.         Element e = getChildByName(parent, name);  
  219.         if (e == null) {  
  220.             return "";  
  221.         }  
  222.         return getText(e);  
  223.     }  
  224.   
  225.     /** 
  226.      * 根据名称得到一个父节点下所有的子节点 
  227.      *  
  228.      * @param e 
  229.      *            Element 
  230.      * @param name 
  231.      *            String 
  232.      * @return Element[] 
  233.      */  
  234.     public static Element[] getChildrenByName(Element e, String name) {  
  235.         NodeList nl = e.getChildNodes();  
  236.         int max = nl.getLength();  
  237.         LinkedList<Node> list = new LinkedList<Node>();  
  238.         for (int i = 0; i < max; i++) {  
  239.             Node n = nl.item(i);  
  240.             if (n.getNodeType() == Node.ELEMENT_NODE  
  241.                     && n.getNodeName().equals(name)) {  
  242.                 list.add(n);  
  243.             }  
  244.         }  
  245.         return list.toArray(new Element[list.size()]);  
  246.     }  
  247.   
  248.     /** 
  249.      * 根据名字查找某个节点下的符合该名字的节点 
  250.      *  
  251.      * @param e 
  252.      *            Element 父节点 
  253.      * @param name 
  254.      *            String 子节点名称 
  255.      * @return Element 
  256.      */  
  257.     public static Element getChildByName(Element e, String name) {  
  258.         Element[] list = getChildrenByName(e, name);  
  259.         if (list.length == 0) {  
  260.             return null;  
  261.         }  
  262.         if (list.length > 1) {  
  263.             throw new IllegalStateException("Too many (" + list.length + ") '"  
  264.                     + name + "' elements found!");  
  265.         }  
  266.         return list[0];  
  267.     }  
  268.   
  269.     /** 
  270.      * 得到一个节点的文字 
  271.      *  
  272.      * @param e 
  273.      *            Element 
  274.      * @return String 
  275.      */  
  276.     public static String getText(Element e) {  
  277.         NodeList nl = e.getChildNodes();  
  278.         int max = nl.getLength();  
  279.         for (int i = 0; i < max; i++) {  
  280.             Node n = nl.item(i);  
  281.             if (n.getNodeType() == Node.TEXT_NODE) {  
  282.                 return n.getNodeValue();  
  283.             }  
  284.         }  
  285.         return "";  
  286.     }  
  287.   
  288.     public static String getAttribute(Element e, String name) {  
  289.         return e.getAttribute(name);  
  290.     }  
  291.   
  292.     /** 
  293.      * get Int value 
  294.      *  
  295.      * @param player 
  296.      * @param name 
  297.      * @return 
  298.      */  
  299.     public static int getIntValue(Element e) {  
  300.         return Integer.valueOf(getText(e));  
  301.     }  
  302.   
  303.     /** 
  304.      * get byte value 
  305.      *  
  306.      * @param player 
  307.      * @param name 
  308.      * @return 
  309.      */  
  310.     public static byte getByteValue(Element e) {  
  311.         return Byte.valueOf(getText(e));  
  312.     }  
  313.   
  314.     /** 
  315.      * 获取Properties格式的xml数据 
  316.      *  
  317.      * @param root 
  318.      * @return 
  319.      */  
  320.     public static Map<String, Object> getProperties(Element root) {  
  321.         Map<String, Object> map = new HashMap<String, Object>();  
  322.         Element[] list = getChildrenByName(root, "property");  
  323.         for (int i = 0; i < list.length; i++) {  
  324.             String name = list[i].getAttribute("name");  
  325.             String type = list[i].getAttribute("type");  
  326.             String valueString = getText(list[i]);  
  327.             try {  
  328.                 Class<?> cls = Class.forName(type);  
  329.                 Constructor<?> con = cls.getConstructor(new Class<?>[] { String.class  
  330.   
  331.                 });  
  332.                 Object value = con.newInstance(new Object[] { valueString  
  333.   
  334.                 });  
  335.                 map.put(name, value);  
  336.             } catch (Exception e) {  
  337.                 System.err.println("Unable to parse property '" + name +  
  338.   
  339.                 "'='" + valueString + "': " + e.toString());  
  340.             }  
  341.         }  
  342.         return map;  
  343.     }  
  344.   
  345.     /** 
  346.      * 将dom中的内容存入xmlfile所指的文件中。 dom==null时,xml文件也是空的。 
  347.      *  
  348.      * @param xmlfile 
  349.      *            java.lang.String 保存的文件名 
  350.      * @param doc 
  351.      *            ort.w3c.dom.Document 需要保存的DOM 
  352.      * @throws Exception 
  353.      *             任何异常 
  354.      */  
  355.     public static void save(String xmlfile, Document doc) throws Exception {  
  356.         // 首先创建一个DOMSource对象,该构造函数的参数可以是一个Document对象  
  357.         // doc代表更改后的DOM Tree。  
  358.         DOMSource doms = new DOMSource(doc);  
  359.   
  360.         // 创建一个File对象,代表DOM Tree所包含的数据的输出介质,这是一个XML文件。  
  361.         File f = new File(xmlfile);  
  362.         File dir = f.getParentFile();  
  363.         dir.mkdirs();  
  364.         // 创建一个StreamResult对象,该构造函数的参数可以取为File对象。  
  365.         StreamResult sr = new StreamResult(f);  
  366.   
  367.         // 下面调用JAXP中的XSLT引擎来实现输出DOM Tree中的数据到XML文件中的功能。  
  368.         // XSLT引擎的输入为DOMSource对象,输出为StreamResut对象。  
  369.         try {  
  370.             // 首先创建一个TransformerFactory对象,再由此创建Transformer对象。Transformer  
  371.             // 类相当于一个XSLT引擎。通常我们使用它来处理XSL文件,但是在这里我们使  
  372.             // 用它来输出XML文档。  
  373.             TransformerFactory tf = TransformerFactory.newInstance();  
  374.             Transformer t = tf.newTransformer();  
  375.             // 设置新的输出属性:输出字符编码为UTF-8,XSLT引擎所输出  
  376.             // 的XML文档如果包含了中文字符,可以正常显示,不会出现所谓的"汉字问题"。  
  377.             // 请留意OutputKeys类的字符串常数OutputKeys.ENCODING。  
  378.             Properties properties = t.getOutputProperties();  
  379.             properties.setProperty(OutputKeys.ENCODING, "UTF-8");  
  380.             properties.setProperty(OutputKeys.INDENT, "yes");  
  381.             // 更新XSLT引擎的输出属性。  
  382.             t.setOutputProperties(properties);  
  383.             // 关键的一步, 调用Transformer对象 (XSLT引擎)的transform()方法,该方法的第一  
  384.             // 个参数是DOMSource对象,第二个参数是StreamResult对象。  
  385.             t.transform(doms, sr);  
  386.   
  387.         } catch (TransformerConfigurationException tce) {  
  388.             tce.printStackTrace();  
  389.         } catch (TransformerException te) {  
  390.             te.printStackTrace();  
  391.         }  
  392.   
  393.     }  
  394.   
  395.     /** 
  396.      * create a blank Document. 
  397.      *  
  398.      * @param rootElementName 
  399.      *            String 
  400.      * @return Document 
  401.      * @throws Exception 
  402.      */  
  403.     public static Document blankDocument(String rootElementName)  
  404.             throws Exception {  
  405.         javax.xml.parsers.DocumentBuilderFactory factory =  
  406.   
  407.         javax.xml.parsers.DocumentBuilderFactory.newInstance();  
  408.         factory.setIgnoringComments(false);  
  409.         factory.setIgnoringElementContentWhitespace(false);  
  410.         factory.setValidating(false);  
  411.         factory.setCoalescing(false);  
  412.         DocumentBuilder builder = factory.newDocumentBuilder();  
  413.         Document doc = builder.newDocument();  
  414.         Element root = doc.createElement(rootElementName);  
  415.         doc.appendChild(root);  
  416.         return doc;  
  417.     }  
  418.   
  419.     public static Element createChild(Document doc, Element root, String name) {  
  420.         Element elem = doc.createElement(name);  
  421.         root.appendChild(elem);  
  422.         return elem;  
  423.     }  
  424.   
  425.     public static void createChildText(Document doc, Element elem, String name,  
  426.             String value) {  
  427.         Element child = doc.createElement(name);  
  428.         child.appendChild(doc.createTextNode(value == null ? "" : value));  
  429.         elem.appendChild(child);  
  430.     }  
  431.   
  432.     /** 
  433.      * 创建一个带注释的子节点 
  434.      *  
  435.      * @param doc 
  436.      *            Document 
  437.      * @param elem 
  438.      *            Element 
  439.      * @param name 
  440.      *            String 
  441.      * @param value 
  442.      *            String 
  443.      * @param comment 
  444.      *            String 
  445.      */  
  446.     public static void createChildTextWithComment(Document doc, Element elem,  
  447.             String name, String value, String comment) {  
  448.         Element child = doc.createElement(name);  
  449.         child.appendChild(doc.createTextNode(value == null ? "" : value));  
  450.         Comment c = doc.createComment(comment);  
  451.         elem.appendChild(c);  
  452.         elem.appendChild(child);  
  453.   
  454.     }  
  455.   
  456.     /** 
  457.      * 创建一段注释 
  458.      *  
  459.      * @param doc 
  460.      *            Document 
  461.      * @param comment 
  462.      *            String 
  463.      */  
  464.     public static void createComment(Document doc, String comment) {  
  465.         Comment c = doc.createComment(comment);  
  466.         doc.getDocumentElement().appendChild(c);  
  467.     }  
  468.   
  469.     public static void createOptionalChildText(Document doc, Element elem,  
  470.             String name, String value) {  
  471.         if (value == null || value.length() == 0) {  
  472.             return;  
  473.         }  
  474.         Element child = doc.createElement(name);  
  475.         child.appendChild(doc.createTextNode(value));  
  476.         elem.appendChild(child);  
  477.     }  
  478.   
  479.     public static void applyProperties(Object o, Element root) {  
  480.         Map<String,Object> map = getProperties(root);  
  481.         Iterator<String> it = map.keySet().iterator();  
  482.         Field[] fields = o.getClass().getFields();  
  483.         Method[] methods = o.getClass().getMethods();  
  484.         while (it.hasNext()) {  
  485.             String name = (String) it.next();  
  486.             Object value = map.get(name);  
  487.             try {  
  488.                 for (int i = 0; i < fields.length; i++) {  
  489.                     if (fields[i].getName().equalsIgnoreCase(name) && isTypeMatch(fields[i].getType(),  
  490.                         value.getClass())) {  
  491.                         fields[i].set(o, value);  
  492.                         System.err.println("Set field " + fields  
  493.   
  494.                         [i].getName() + "=" + value);  
  495.                         break;  
  496.                     }  
  497.                 }  
  498.                 for (int i = 0; i < methods.length; i++) {  
  499.                     if (methods[i].getName().equalsIgnoreCase("set" + name) && methods[i].getParameterTypes  
  500.   
  501.                     ().length == 1 && isTypeMatch(methods  
  502.   
  503.                     [i].getParameterTypes()[0], value.getClass())) {  
  504.                         methods[i].invoke(o, new Object[] { value  
  505.   
  506.                         });  
  507.                         System.err.println("Set method " + methods  
  508.   
  509.                         [i].getName() + "=" + value);  
  510.                         break;  
  511.                     }  
  512.                 }  
  513.             } catch (Exception e) {  
  514.                 System.err.println("Unable to apply property '" + name + "': " + e.toString());  
  515.             }  
  516.         }  
  517.     }  
  518.   
  519.     private static boolean isTypeMatch(Class<?> one, Class<?> two) {  
  520.         if (one.equals(two)) {  
  521.             return true;  
  522.         }  
  523.         if (one.isPrimitive()) {  
  524.             if (one.getName().equals("int") && two.getName().equals("java.lang.Integer")) {  
  525.                 return true;  
  526.             }  
  527.             if (one.getName().equals("long") && two.getName().equals("java.lang.Long")) {  
  528.                 return true;  
  529.             }  
  530.             if (one.getName().equals("float") && two.getName().equals("java.lang.Float")) {  
  531.                 return true;  
  532.             }  
  533.             if (one.getName().equals("double") && two.getName().equals("java.lang.Double")) {  
  534.                 return true;  
  535.             }  
  536.             if (one.getName().equals("char") && two.getName().equals("java.lang.Character")) {  
  537.                 return true;  
  538.             }  
  539.             if (one.getName().equals("byte") && two.getName().equals("java.lang.Byte")) {  
  540.                 return true;  
  541.             }  
  542.             if (one.getName().equals("short") && two.getName().equals("java.lang.Short")) {  
  543.                 return true;  
  544.             }  
  545.             if (one.getName().equals("boolean") && two.getName().equals("java.lang.Boolean")) {  
  546.                 return true;  
  547.             }  
  548.         }  
  549.         return false;  
  550.     }  
  551. }  


 

  1. package com.tdt.server.httpserver.utils;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.StringTokenizer;  
  5. import java.util.regex.Matcher;  
  6. import java.util.regex.Pattern;  
  7.   
  8. public class StringUtils {  
  9.     /** 
  10.      * Converts a line of text into an array of lower case words. Words are 
  11.      * delimited by the following characters: , .\r\n:/\+ 
  12.      * <p> 
  13.      * In the future, this method should be changed to use a 
  14.      * BreakIterator.wordInstance(). That class offers much more fexibility. 
  15.      *  
  16.      * @param text 
  17.      *            a String of text to convert into an array of words 
  18.      * @return text broken up into an array of words. 
  19.      */  
  20.     public static final String[] toLowerCaseWordArray(String text) {  
  21.         if (text == null || text.length() == 0) {  
  22.             return new String[0];  
  23.         }  
  24.         StringTokenizer tokens = new StringTokenizer(text, " ,\r\n.:/\\+");  
  25.         String[] words = new String[tokens.countTokens()];  
  26.         for (int i = 0; i < words.length; i++) {  
  27.             words[i] = tokens.nextToken().toLowerCase();  
  28.         }  
  29.         return words;  
  30.     }  
  31.   
  32.     /** 
  33.      * Converts a line of text into an array of lower case words. Words are 
  34.      * delimited by the following characters: , .\r\n:/\+ 
  35.      * <p> 
  36.      * In the future, this method should be changed to use a 
  37.      * BreakIterator.wordInstance(). That class offers much more fexibility. 
  38.      *  
  39.      * @param text 
  40.      *            a String of text to convert into an array of words 
  41.      * @return text broken up into an array of words. 
  42.      */  
  43.     public static final String[] toStringArray(String text) {  
  44.         if (text == null || text.length() == 0) {  
  45.             return new String[0];  
  46.         }  
  47.         StringTokenizer tokens = new StringTokenizer(text, ",\r\n/\\");  
  48.         String[] words = new String[tokens.countTokens()];  
  49.         for (int i = 0; i < words.length; i++) {  
  50.             words[i] = tokens.nextToken();  
  51.         }  
  52.         return words;  
  53.     }  
  54.   
  55.     /** 
  56.      * * Converts a line of text into an array of lower case words. Words are 
  57.      * delimited by the following characters: , .\r\n:/\+ 
  58.      * <p> 
  59.      * In the future, this method should be changed to use a 
  60.      * BreakIterator.wordInstance(). That class offers much more fexibility. 
  61.      *  
  62.      * @param text 
  63.      *            a String of text to convert into an array of words 
  64.      * @param token 
  65.      *            String 
  66.      * @return String[]broken up into an array of words. 
  67.      */  
  68.     public static final String[] toStringArray(String text, String token) {  
  69.         if (text == null || text.length() == 0) {  
  70.             return new String[0];  
  71.         }  
  72.         StringTokenizer tokens = new StringTokenizer(text, token);  
  73.         String[] words = new String[tokens.countTokens()];  
  74.         for (int i = 0; i < words.length; i++) {  
  75.             words[i] = tokens.nextToken();  
  76.         }  
  77.         return words;  
  78.     }  
  79.   
  80.     /** 
  81.      *  
  82.      * @param source 
  83.      * @return 
  84.      */  
  85.     public static String[] splitOnWhitespace(String source) {  
  86.         int pos = -1;  
  87.         LinkedList<String> list = new LinkedList<String>();  
  88.         int max = source.length();  
  89.         for (int i = 0; i < max; i++) {  
  90.             char c = source.charAt(i);  
  91.             if (Character.isWhitespace(c)) {  
  92.                 if (i - pos > 1) {  
  93.                     list.add(source.substring(pos + 1, i));  
  94.                 }  
  95.                 pos = i;  
  96.             }  
  97.         }  
  98.         return list.toArray(new String[list.size()]);  
  99.     }  
  100.   
  101.     /** 
  102.      * Replayer str 
  103.      *  
  104.      * @param str 
  105.      * @param key 
  106.      * @param replacement 
  107.      * @return 
  108.      */  
  109.     public static final String replaceAll(String str, String key,  
  110.             String replacement) {  
  111.         if (str != null && key != null && replacement != null  
  112.                 && !str.equals("") && !key.equals("")) {  
  113.             StringBuilder strbuf = new StringBuilder();  
  114.             int begin = 0;  
  115.             int slen = str.length();  
  116.             int npos = 0;  
  117.             int klen = key.length();  
  118.             for (; begin < slen && (npos = str.indexOf(key, begin)) >= begin; begin = npos  
  119.                     + klen) {  
  120.                 strbuf.append(str.substring(begin, npos)).append(replacement);  
  121.             }  
  122.   
  123.             if (begin == 0) {  
  124.                 return str;  
  125.             }  
  126.             if (begin < slen) {  
  127.                 strbuf.append(str.substring(begin));  
  128.             }  
  129.             return strbuf.toString();  
  130.         } else {  
  131.             return str;  
  132.         }  
  133.     }  
  134.       
  135.       
  136.     public static String UnicodeToString(String str) {      
  137.         Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");      
  138.         Matcher matcher = pattern.matcher(str);      
  139.         char ch;     
  140.         boolean hasU = false;  
  141.         while (matcher.find()) {     
  142.             hasU = true;  
  143.             ch = (char) Integer.parseInt(matcher.group(2), 16);       
  144.             str = str.replace(matcher.group(1), ch + "");      
  145.         }   
  146.         String s = str;  
  147.         try{  
  148.             if(!hasU){  
  149.                 int i = 0;  
  150.                 String rstr = "";  
  151.                 while(i+4<=str.length()){  
  152.                     ch = (char) Integer.parseInt(str.substring(i,i=i+4), 16);   
  153.                     rstr = rstr+ch;  
  154.                 }  
  155.                 str = rstr;  
  156.             }  
  157.         }catch(Exception ex){  
  158.             str = s;  
  159.             ex.printStackTrace();  
  160.         }  
  161.         return str;     
  162.     }   
  163.     /** 空字符串。 */  
  164.     public static final String EMPTY_STRING = "";  
  165.   
  166.     /** 
  167.      * 比较两个字符串(大小写敏感)。 
  168.      * <pre> 
  169.      * StringUtil.equals(null, null)   = true 
  170.      * StringUtil.equals(null, "abc")  = false 
  171.      * StringUtil.equals("abc", null)  = false 
  172.      * StringUtil.equals("abc", "abc") = true 
  173.      * StringUtil.equals("abc", "ABC") = false 
  174.      * </pre> 
  175.      * 
  176.      * @param str1 要比较的字符串1 
  177.      * @param str2 要比较的字符串2 
  178.      * 
  179.      * @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code> 
  180.      */  
  181.     public static boolean equals(String str1, String str2) {  
  182.         if (str1 == null) {  
  183.             return str2 == null;  
  184.         }  
  185.   
  186.         return str1.equals(str2);  
  187.     }  
  188.   
  189.     /** 
  190.      * 比较两个字符串(大小写不敏感)。 
  191.      * <pre> 
  192.      * StringUtil.equalsIgnoreCase(null, null)   = true 
  193.      * StringUtil.equalsIgnoreCase(null, "abc")  = false 
  194.      * StringUtil.equalsIgnoreCase("abc", null)  = false 
  195.      * StringUtil.equalsIgnoreCase("abc", "abc") = true 
  196.      * StringUtil.equalsIgnoreCase("abc", "ABC") = true 
  197.      * </pre> 
  198.      * 
  199.      * @param str1 要比较的字符串1 
  200.      * @param str2 要比较的字符串2 
  201.      * 
  202.      * @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code> 
  203.      */  
  204.     public static boolean equalsIgnoreCase(String str1, String str2) {  
  205.         if (str1 == null) {  
  206.             return str2 == null;  
  207.         }  
  208.   
  209.         return str1.equalsIgnoreCase(str2);  
  210.     }  
  211.   
  212.     /** 
  213.      * 检查字符串是否是空白:<code>null</code>、空字符串<code>""</code>或只有空白字符。 
  214.      * <pre> 
  215.      * StringUtil.isBlank(null)      = true 
  216.      * StringUtil.isBlank("")        = true 
  217.      * StringUtil.isBlank(" ")       = true 
  218.      * StringUtil.isBlank("bob")     = false 
  219.      * StringUtil.isBlank("  bob  ") = false 
  220.      * </pre> 
  221.      * 
  222.      * @param str 要检查的字符串 
  223.      * 
  224.      * @return 如果为空白, 则返回<code>true</code> 
  225.      */  
  226.     public static boolean isBlank(String str) {  
  227.         int length;  
  228.   
  229.         if ((str == null) || ((length = str.length()) == 0)) {  
  230.             return true;  
  231.         }  
  232.   
  233.         for (int i = 0; i < length; i++) {  
  234.             if (!Character.isWhitespace(str.charAt(i))) {  
  235.                 return false;  
  236.             }  
  237.         }  
  238.   
  239.         return true;  
  240.     }  
  241.   
  242.     /** 
  243.      * 检查字符串是否不是空白:<code>null</code>、空字符串<code>""</code>或只有空白字符。 
  244.      * <pre> 
  245.      * StringUtil.isBlank(null)      = false 
  246.      * StringUtil.isBlank("")        = false 
  247.      * StringUtil.isBlank(" ")       = false 
  248.      * StringUtil.isBlank("bob")     = true 
  249.      * StringUtil.isBlank("  bob  ") = true 
  250.      * </pre> 
  251.      * 
  252.      * @param str 要检查的字符串 
  253.      * 
  254.      * @return 如果为空白, 则返回<code>true</code> 
  255.      */  
  256.     public static boolean isNotBlank(String str) {  
  257.         int length;  
  258.   
  259.         if ((str == null) || ((length = str.length()) == 0)) {  
  260.             return false;  
  261.         }  
  262.   
  263.         for (int i = 0; i < length; i++) {  
  264.             if (!Character.isWhitespace(str.charAt(i))) {  
  265.                 return true;  
  266.             }  
  267.         }  
  268.   
  269.         return false;  
  270.     }  
  271.   
  272.     /** 
  273.      * 检查字符串是否为<code>null</code>或空字符串<code>""</code>。 
  274.      * <pre> 
  275.      * StringUtil.isEmpty(null)      = true 
  276.      * StringUtil.isEmpty("")        = true 
  277.      * StringUtil.isEmpty(" ")       = false 
  278.      * StringUtil.isEmpty("bob")     = false 
  279.      * StringUtil.isEmpty("  bob  ") = false 
  280.      * </pre> 
  281.      * 
  282.      * @param str 要检查的字符串 
  283.      * 
  284.      * @return 如果为空, 则返回<code>true</code> 
  285.      */  
  286.     public static boolean isEmpty(String str) {  
  287.         return ((str == null) || (str.length() == 0));  
  288.     }  
  289.   
  290.     /** 
  291.      * 检查字符串是否不是<code>null</code>和空字符串<code>""</code>。 
  292.      * <pre> 
  293.      * StringUtil.isEmpty(null)      = false 
  294.      * StringUtil.isEmpty("")        = false 
  295.      * StringUtil.isEmpty(" ")       = true 
  296.      * StringUtil.isEmpty("bob")     = true 
  297.      * StringUtil.isEmpty("  bob  ") = true 
  298.      * </pre> 
  299.      * 
  300.      * @param str 要检查的字符串 
  301.      * 
  302.      * @return 如果不为空, 则返回<code>true</code> 
  303.      */  
  304.     public static boolean isNotEmpty(String str) {  
  305.         return ((str != null) && (str.length() > 0));  
  306.     }  
  307.   
  308.     /** 
  309.      * 在字符串中查找指定字符串,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>。 
  310.      * <pre> 
  311.      * StringUtil.indexOf(null, *)          = -1 
  312.      * StringUtil.indexOf(*, null)          = -1 
  313.      * StringUtil.indexOf("", "")           = 0 
  314.      * StringUtil.indexOf("aabaabaa", "a")  = 0 
  315.      * StringUtil.indexOf("aabaabaa", "b")  = 2 
  316.      * StringUtil.indexOf("aabaabaa", "ab") = 1 
  317.      * StringUtil.indexOf("aabaabaa", "")   = 0 
  318.      * </pre> 
  319.      * 
  320.      * @param str 要扫描的字符串 
  321.      * @param searchStr 要查找的字符串 
  322.      * 
  323.      * @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code> 
  324.      */  
  325.     public static int indexOf(String str, String searchStr) {  
  326.         if ((str == null) || (searchStr == null)) {  
  327.             return -1;  
  328.         }  
  329.   
  330.         return str.indexOf(searchStr);  
  331.     }  
  332.   
  333.     /** 
  334.      * 在字符串中查找指定字符串,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>。 
  335.      * <pre> 
  336.      * StringUtil.indexOf(null, *, *)          = -1 
  337.      * StringUtil.indexOf(*, null, *)          = -1 
  338.      * StringUtil.indexOf("", "", 0)           = 0 
  339.      * StringUtil.indexOf("aabaabaa", "a", 0)  = 0 
  340.      * StringUtil.indexOf("aabaabaa", "b", 0)  = 2 
  341.      * StringUtil.indexOf("aabaabaa", "ab", 0) = 1 
  342.      * StringUtil.indexOf("aabaabaa", "b", 3)  = 5 
  343.      * StringUtil.indexOf("aabaabaa", "b", 9)  = -1 
  344.      * StringUtil.indexOf("aabaabaa", "b", -1) = 2 
  345.      * StringUtil.indexOf("aabaabaa", "", 2)   = 2 
  346.      * StringUtil.indexOf("abc", "", 9)        = 3 
  347.      * </pre> 
  348.      * 
  349.      * @param str 要扫描的字符串 
  350.      * @param searchStr 要查找的字符串 
  351.      * @param startPos 开始搜索的索引值,如果小于0,则看作0 
  352.      * 
  353.      * @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code> 
  354.      */  
  355.     public static int indexOf(String str, String searchStr, int startPos) {  
  356.         if ((str == null) || (searchStr == null)) {  
  357.             return -1;  
  358.         }  
  359.   
  360.         // JDK1.3及以下版本的bug:不能正确处理下面的情况  
  361.         if ((searchStr.length() == 0) && (startPos >= str.length())) {  
  362.             return str.length();  
  363.         }  
  364.   
  365.         return str.indexOf(searchStr, startPos);  
  366.     }  
  367.   
  368.     /** 
  369.      * 取指定字符串的子串。 
  370.      *  
  371.      * <p> 
  372.      * 负的索引代表从尾部开始计算。如果字符串为<code>null</code>,则返回<code>null</code>。 
  373.      * <pre> 
  374.      * StringUtil.substring(null, *, *)    = null 
  375.      * StringUtil.substring("", * ,  *)    = ""; 
  376.      * StringUtil.substring("abc", 0, 2)   = "ab" 
  377.      * StringUtil.substring("abc", 2, 0)   = "" 
  378.      * StringUtil.substring("abc", 2, 4)   = "c" 
  379.      * StringUtil.substring("abc", 4, 6)   = "" 
  380.      * StringUtil.substring("abc", 2, 2)   = "" 
  381.      * StringUtil.substring("abc", -2, -1) = "b" 
  382.      * StringUtil.substring("abc", -4, 2)  = "ab" 
  383.      * </pre> 
  384.      * </p> 
  385.      * 
  386.      * @param str 字符串 
  387.      * @param start 起始索引,如果为负数,表示从尾部计算 
  388.      * @param end 结束索引(不含),如果为负数,表示从尾部计算 
  389.      * 
  390.      * @return 子串,如果原始串为<code>null</code>,则返回<code>null</code> 
  391.      */  
  392.     public static String substring(String str, int start, int end) {  
  393.         if (str == null) {  
  394.             return null;  
  395.         }  
  396.   
  397.         if (end < 0) {  
  398.             end = str.length() + end;  
  399.         }  
  400.   
  401.         if (start < 0) {  
  402.             start = str.length() + start;  
  403.         }  
  404.   
  405.         if (end > str.length()) {  
  406.             end = str.length();  
  407.         }  
  408.   
  409.         if (start > end) {  
  410.             return EMPTY_STRING;  
  411.         }  
  412.   
  413.         if (start < 0) {  
  414.             start = 0;  
  415.         }  
  416.   
  417.         if (end < 0) {  
  418.             end = 0;  
  419.         }  
  420.   
  421.         return str.substring(start, end);  
  422.     }  
  423.   
  424.     /** 
  425.      * 检查字符串中是否包含指定的字符串。如果字符串为<code>null</code>,将返回<code>false</code>。 
  426.      * <pre> 
  427.      * StringUtil.contains(null, *)     = false 
  428.      * StringUtil.contains(*, null)     = false 
  429.      * StringUtil.contains("", "")      = true 
  430.      * StringUtil.contains("abc", "")   = true 
  431.      * StringUtil.contains("abc", "a")  = true 
  432.      * StringUtil.contains("abc", "z")  = false 
  433.      * </pre> 
  434.      * 
  435.      * @param str 要扫描的字符串 
  436.      * @param searchStr 要查找的字符串 
  437.      * 
  438.      * @return 如果找到,则返回<code>true</code> 
  439.      */  
  440.     public static boolean contains(String str, String searchStr) {  
  441.         if ((str == null) || (searchStr == null)) {  
  442.             return false;  
  443.         }  
  444.   
  445.         return str.indexOf(searchStr) >= 0;  
  446.     }  
  447.   
  448.     /** 
  449.      * <p>Checks if the String contains only unicode digits. 
  450.      * A decimal point is not a unicode digit and returns false.</p> 
  451.      * 
  452.      * <p><code>null</code> will return <code>false</code>. 
  453.      * An empty String ("") will return <code>true</code>.</p> 
  454.      * 
  455.      * <pre> 
  456.      * StringUtils.isNumeric(null)   = false 
  457.      * StringUtils.isNumeric("")     = true 
  458.      * StringUtils.isNumeric("  ")   = false 
  459.      * StringUtils.isNumeric("123")  = true 
  460.      * StringUtils.isNumeric("12 3") = false 
  461.      * StringUtils.isNumeric("ab2c") = false 
  462.      * StringUtils.isNumeric("12-3") = false 
  463.      * StringUtils.isNumeric("12.3") = false 
  464.      * </pre> 
  465.      * 
  466.      * @param str  the String to check, may be null 
  467.      * @return <code>true</code> if only contains digits, and is non-null 
  468.      */  
  469.     public static boolean isNumeric(String str) {  
  470.         if (str == null) {  
  471.             return false;  
  472.         }  
  473.         int sz = str.length();  
  474.         for (int i = 0; i < sz; i++) {  
  475.             if (Character.isDigit(str.charAt(i)) == false) {  
  476.                 return false;  
  477.             }  
  478.         }  
  479.         return true;  
  480.     }  
  481.   
  482.     /** 
  483.      * 字符串拼接 
  484.      * @param object 
  485.      * @return 
  486.      */  
  487.     public static String assemble(char sep,Object... object){  
  488.         if(object == null)return null;  
  489.         StringBuilder sb = new StringBuilder();  
  490.         for(Object obj:object){  
  491.             if(obj == null)obj="";  
  492.             sb.append(obj.toString()).append(sep);  
  493.         }  
  494.         String str = "";  
  495.         if(sb.length()>0){  
  496.             str = sb.substring(0, sb.length()-1);  
  497.         }  
  498.         return str;  
  499.     }  
  500.   
  501.     // 6-16个字母和数字组成  
  502.     private static String regex = "^[A-Za-z0-9]$";  
  503.     /** 
  504.      * 检测字符串是否符合规则(6-16个字母和数字组成,大小写不敏感) 
  505.      * @param user 
  506.      * @return 
  507.      */  
  508.     public static boolean checkStringLegal(String user) {  
  509.         boolean isMatch = true;  
  510.         char[] userChars = user.toCharArray();  
  511.         for(char c : userChars){  
  512.             isMatch = String.valueOf(c).matches(regex);  
  513.             if(!isMatch){  
  514.                 break;  
  515.             }  
  516.         }  
  517.         return isMatch;  
  518.     }  
  519.       
  520.   
  521.     public static String getString(String input) {  
  522.         return getString(input, true"");  
  523.     }  
  524.   
  525.     public static String getString(String input, boolean btrim, String dval) {  
  526.         if (input == null)  
  527.             return dval;  
  528.         try {  
  529.             if (btrim)  
  530.                 return trim(input);  
  531.             else  
  532.                 return input;  
  533.         } catch (Exception e) {  
  534.             return "";  
  535.         }  
  536.     }  
  537.   
  538.     public static String Trim(String str) {  
  539.         return trim(str);  
  540.     }  
  541.   
  542.     public static String[] Trim(String[] s) {  
  543.         return trim(s);  
  544.     }  
  545.   
  546.     public static String trim(String str) {  
  547.         if (str == null)  
  548.             return "";  
  549.         else  
  550.             return str.trim();  
  551.     }  
  552.   
  553.     public static String[] trim(String[] s) {  
  554.         if (s == null || s.length <= 0)  
  555.             return s;  
  556.         for (int i = 0; i < s.length; i++)  
  557.             s[i] = trim(s[i]);  
  558.         return s;  
  559.     }  
  560.   
  561.     public static int getInt(String input, boolean btrim, int dval) {  
  562.         if (input == null)  
  563.             return dval;  
  564.         int val;  
  565.         try {  
  566.             String str = new String(input);  
  567.             if (btrim)  
  568.                 str = trim(str);  
  569.             val = Integer.parseInt(str);  
  570.         } catch (Exception e) {  
  571.             val = dval;  
  572.         }  
  573.         return val;  
  574.     }  
  575.       
  576.     public static int[] getInts(String input) {  
  577.         return getInts(input, ",");  
  578.     }  
  579.   
  580.     public static int[] getInts(String input, String split) {  
  581.         if (input == null) {  
  582.             return null;  
  583.         }  
  584.           
  585.         String[] ss = input.split(split);  
  586.         int[] ii = new int[ss.length];  
  587.         for (int i=0;i<ii.length;i++) {  
  588.             ii[i] = getInt(ss[i]);  
  589.         }  
  590.         return ii;  
  591.     }  
  592.   
  593.     public static int getInt(String input) {  
  594.         return getInt(input, true0);  
  595.     }  
  596.       
  597.       
  598. }  
分享到:
评论
1 楼 linjunjie369865393 2017-04-20  
context.xml 内容是什么?求贴出来。

相关推荐

    HTTPServer:Java Web服务器

    Java HTTP服务器 用Java编写的简单HTTP服务器,可以满足[CobSpec]( )的要求。... $ java -jar build/libs/HTTPServer.jar -p PORT -d PATH/TO/PUBLIC/DIRECTORY 运行测试 从根目录运行测试 $ ./gradlew check

    JavaServer Pages (JSP)

    JavaServer Pages (JSP) 技术提供了一种简单快速的方法来创建显示动态生成内容的 Web 页面。由业界处于领先地位的 Sun 公司制定了相关的 JSP 技术规范,该规范定义了如何在服务器和 JSP 页面间进行交互,还描述了...

    java-httpserver:FlaskSinatra风格的真正基础的HTTP服务器,用Java编写(您可能不应该使用)

    httpserver最初是使用的HTTP服务器的一个更通用的版本,它是一个用Java编写的名称不佳,易于使用且简单的HTTP服务器。 我们最初为Storyteller编写了自己的HTTP服务器,因为找不到适合Java的易于集成且相对简单...

    java源码包3

    第一步:运行ServerData.java 启动服务器,然后服务器处于等待状态 第二步:运行LoginData.java 启动(客户端)登陆界面 输入用户名 ip为本机localhost 第三步:在登陆后的界面文本框输入文本,然后发送 可以同时...

    JSF Java Server Faces (JSF)框架

    它提供了一种以组件为中心的用户界面(UI)构建方法,从而简化了Java服务器端应用程序的开发。由于由Java Community Process (JCP) 推动,属于Java EE 5中的技术规范,而受到了厂商的广泛支持。  JSF(Java Server ...

    httpServer:HTTP服务器,用于通过Web访问目录文件

    HTTP服务器描述一个简单的HTTP服务器,用Java内置。怎么跑克隆gradle build , cd进入它, gradle build , java -jar build/libs/httpServer.jar ...版本号该服务器是使用Java 1.8和JUnit 4构建的。

    javahttpserv:Java 10简单HTTP服务器

    Java 10简单HTTP服务器主要目标是使用Java 9/10创建微服务第二个目标是更新代码以将System.out.println(HelloWorld)替换为Web服务器第三个目标:与Travis-CI集成检查java版本java --versionjava 10.0.1 2018-04-17...

    java源码包---java 源码 大量 实例

    第一步:运行ServerData.java 启动服务器,然后服务器处于等待状态 第二步:运行LoginData.java 启动(客户端)登陆界面 输入用户名 ip为本机localhost 第三步:在登陆后的界面文本框输入文本,然后发送 可以同时启动...

    java源码包4

    第一步:运行ServerData.java 启动服务器,然后服务器处于等待状态 第二步:运行LoginData.java 启动(客户端)登陆界面 输入用户名 ip为本机localhost 第三步:在登陆后的界面文本框输入文本,然后发送 可以同时...

    resin java web 容器 服务器

    许多站点都是使用该WEB服务器构建的。 Resin也可以和许多其他的WEB服务器一起工作,比如Apache server和IIS等。Resin支持Servlets 2.3标准和JSP 1.2标准。熟悉ASP和PHP的用户可以发现用Resin来进行JSP编程是件很...

    java源码包2

    第一步:运行ServerData.java 启动服务器,然后服务器处于等待状态 第二步:运行LoginData.java 启动(客户端)登陆界面 输入用户名 ip为本机localhost 第三步:在登陆后的界面文本框输入文本,然后发送 可以同时...

    JAVA上百实例源码以及开源项目

    第一步:运行ServerData.java 启动服务器,然后服务器处于等待状态 第二步:运行LoginData.java 启动(客户端)登陆界面 输入用户名 ip为本机localhost 第三步:在登陆后的界面文本框输入文本,然后发送 可以同时启动...

    JAVA上百实例源码以及开源项目源代码

    第一步:运行ServerData.java 启动服务器,然后服务器处于等待状态 第二步:运行LoginData.java 启动(客户端)登陆界面 输入用户名 ip为本机localhost 第三步:在登陆后的界面文本框输入文本,然后发送 可以同时启动...

    NIOHTTPServer:带有 JDK 的 NIO 示例 HTTP 服务器

    NIOHTTP服务器 带有 JDK 的 NIO 示例 HTTP 服务器 使用以下命令也使用 Maven build 构建项目 ... java -jar target/NIOHTTPServer-1.0-jar-with-dependencies.jar N2 -port 8000 -webroot /www/mysite/

    JAVA_API1.6文档(中文)

    java.rmi.server 提供支持服务器端 RMI 的类和接口。 java.security 为安全框架提供类和接口。 java.security.acl 此包中的类和接口已经被 java.security 包中的类取代。 java.security.cert 提供用于解析和管理...

    成百上千个Java 源码DEMO 4(1-4是独立压缩包)

    Tcp服务端与客户端的JAVA实例源代码 2个目标文件 摘要:Java源码,文件操作,TCP,服务器 Tcp服务端与客户端的JAVA实例源代码,一个简单的Java TCP服务器端程序,别外还有一个客户端的程序,两者互相配合可以开发出超多...

    android-http-server:带有示例Android应用程序的Java中Web服务器和servlet容器的完整零依赖实现

    Android HTTP服务器小型但功能强大的多线程Web服务器,完全用Java SE编写,然后移植到Android。 该服务器实现大多数HTTP 1.1规范,并提供可用于处理动态页面的自定义servlet API。 Servlet API是在官方javax.servlet...

    http-gradle-cache-server:HTTP构建缓存服务器

    缓存中存储的缓存总条目受分配给JVM的堆的限制它能做什么: 缓存gradle构建储存在记忆体中此模式的选项: 复制到另一个节点(如果已配置) 驱逐条目以使用LRU释放内存怎么跑$ java -jar http-cache-se

    JavaServer Faces 2.0完全参考手册(JSF2.0中文版) 1/2

    《JavaServer Faces 2.0完全参考手册》主要内容:搭建开发环境并构建JSF应用程序。理解JSF请求处理生命周期。使用Facelets视图声明语言、托管bean和JSF表达式语言(EL)。按照JSF导航模型声明一个页面,包括新的...

Global site tag (gtag.js) - Google Analytics