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 {@Overridepublic 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);}}@Overridepublic abstract void doGet(Request request, Response response);@Overridepublic 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;}@Overridepublic String getParamter(String param) {return paramMap.get(param);}@Overridepublic String getMethod() {return httpExchange.getRequestMethod().trim().toUpperCase();}@Overridepublic URI getReuestURI() {return httpExchange.getRequestURI();}@Overridepublic void initRequestParam() {String query = getReuestURI().getQuery();String [] arrayStr = query.split("&");for(String str : arrayStr){paramMap.put(str.split("=")[0], str.split("=")[1]);}}@Overridepublic void initRequestHeader() {for(String s : httpExchange.getRequestHeaders().keySet()){headMap.put(s, httpExchange.getRequestHeaders().get(s));}}@Overridepublic 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();}}@Overridepublic 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;}@Overridepublic 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{@Overridepublic 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.....");}@Overridepublic 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);elsereturn 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 "";elsereturn 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);}}

java HttpServer构建http服务器相关推荐

  1. ktor框架用到了netty吗_教你如何构建异步服务器和客户端的 Kotlin 框架 Ktor

    Ktor 是一个使用 Kotlin 以最小的成本快速创建 Web 应用程序的框架. Ktor 是一个用于在连接系统(connected systems)中构建异步服务器和客户端的 Kotlin 框架. ...

  2. Java Robot对象实现服务器屏幕远程监视

    Java Robot对象实现服务器屏幕远程监视2006-01-16 17:33 作者: xiepan110 出处: BLOG 责任编辑:方舟 摘要: 有时候,在Java应用程序开发中,如:远程监控或远 ...

  3. aws lambda使用_如何使用AWS Lambda和S3构建无服务器URL缩短器

    aws lambda使用 by Daniel Ireson 丹尼尔·埃里森(Daniel Ireson) 如何使用AWS Lambda和S3构建无服务器URL缩短器 (How to build a S ...

  4. Java项目构建打包规范,jenkins2.121.1构建java项目环境,一键打包发布

    该版本为2.121.1,其他版本会稍有不同,仅做参考 1.登录jenkins后,点击左上角"新建任务". 2.填写任务名称,然后选择构建类型(一般是选择构建一个maven项目) 3 ...

  5. java robot 对象_用Java Robot对象实现服务器屏幕远程监视

    用Java Robot对象实现服务器屏幕远程监视 作者:李鲁群 摘要: 有时候,在Java应用程序开发中,如:远程监控或远程教学,常常需要对计算机的屏幕进行截取,由于屏幕截取是比较接近操作系统的操作, ...

  6. 用Apache构建WEB服务器

    用Apache构建WEB服务器 作者:level Apache源于NCSAhttpd服务器,经过多次修改,成为世界上最流行的Web服务器软件之一.Apache取自"a patchy serv ...

  7. Netty构建游戏服务器(一)--基本概念与原理

    一,Netty是什么 1,Netty是由 JBOSS 提供的一个 java开源 框架. 2,Netty是JAR包,一般使用ALL-IN-ONE的JAR包就可以开发了. 3,Netty不需要运行在Tom ...

  8. java web构建_使用Java构建一个宁静的Web服务

    java web构建 介绍 (Introduction) Due to its exponential growth, REST(Representational State Transfer) ha ...

  9. 构建静态服务器_为静态网站构建无服务器联系表

    构建静态服务器 介绍 (Introduction) A few years ago AWS launched static hosting service S3, which was a paradi ...

最新文章

  1. Hyperledger Fabric 核心模块(6)configtxlator工具
  2. 反思项目调试整体过程
  3. vs2010 插件不显示的问题处理。
  4. Navicat连接mysql8.0.1版本出现1251--Client does not support authentication protocol requested by server的解决
  5. 马云给程序员脱离单身的一些建议
  6. 怎么在Telegram电报纸飞机中搜索频道群组机器人教程。
  7. 网页导出的excel无法计算机,网页上不能导出excel表格数据-如何将网页表格导出到excel...
  8. Leetcode 黄金分割点等级简单
  9. java math 三角函数_Java Math类的常用方法,三角函数运算
  10. Weights Biases (一)
  11. 放假在家/异地/无法使用学校局域网-如何快速登录知网/web of science等学术平台
  12. 微信小程序免费资源大全
  13. exchange邮箱一直提示密码错误,密码是正确的,求大佬解答
  14. 【C语言:精准打击】scanf_s()函数与scanf()函数的相关解决方案
  15. 最新版谷歌浏览器的锚点小问题 用jquery做出ctrl+f的搜索效果
  16. 支付宝七(商户会员卡之发放卡券)
  17. 武汉全款买房,普通人不吃不喝需要10年,这位程序员只用了5年
  18. STM32F429的USB外设简介
  19. 大家分享——恢复视力方法
  20. java 递归题目_Java 递归 常见24道题目 总结

热门文章

  1. 「JOISC 2014 Day1」巴士走读
  2. 读这一篇学习推荐引擎的原理与算法
  3. 由于target文件夹被锁定导致maven打包无法执行的问题,Failed to execute goal org.apache.maven.plugins:maven-resources-plugi
  4. java 清空stringbuilder_java stringbuilder 3种清空方法性能比较
  5. 写一段代码在遍历 ArrayList 时移除一个元素?
  6. 浅论语言文字起源:一个业余人类学家的观察
  7. 嘀嗒顺风车主显示服务器走神,我跑嘀嗒遇到的一些问题,给新手参考
  8. 2011孕妇奶粉排行榜
  9. 计算机科学与技术专业考研视觉传达设计,视觉传达考研考什么 视觉传达考研方向...
  10. windows上,cmd终端上一次执行多条指令