浅析Tomcat(一)
想必大家都知道Tomcat其实就是servlet容器。负责servlet前期的准备工作。在这里简单用代码模拟一下Tomcat的工作。
首先牵涉到网络,那么网络编程是少不了的。
1.这个类就是一个servlet服务的工具,程序从这里开始
package com.arz.server;import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.Map;import java.util.StringTokenizer;public class Request { private int port; private String host; private String urlPattern; private Map<String,String> map = new HashMap<String,String>(); private String method; private String headInfo; private InputStream inStream; protected Request(InputStream inStream,int port) { this.inStream = inStream; this.port = port; parseRequestHead(); } private void parseRequestHead(){ byte[] buf = new byte[1024]; try{ inStream.read(buf); headInfo = new String(buf); System.out.println(headInfo); method = headInfo.substring(0,headInfo.indexOf("/")).trim(); System.out.println("请求方式:"+method); host = headInfo.substring(headInfo.indexOf("Host:")+5,headInfo.indexOf(":"+port)).trim(); System.out.println("请求地址:"+host); //?? if(method.equalsIgnoreCase("get")){ parseGetString(); }else if (method.equalsIgnoreCase("post")){ parsePostString(); } }catch(IOException e){ e.printStackTrace(); } } private void parsePostString(){ urlPattern = headInfo.substring(5, headInfo.indexOf("HTTP/")).trim(); String dataString = headInfo.substring(headInfo.lastIndexOf("\r\n")).trim(); //?? StringTokenizer st = new StringTokenizer(dataString,"&"); while(st.hasMoreTokens()){ String[] ss = st.nextToken().split("="); map.put(ss[0], ss[1]); } } private void parseGetString(){ String url = headInfo.substring(4, headInfo.indexOf("HTTP/")); if(url.indexOf("?")==-1){ urlPattern = url.trim(); }else{ urlPattern = url.substring(0, url.indexOf("?")).trim(); String dataString = url.substring(url.indexOf("?")+1).trim(); StringTokenizer st = new StringTokenizer(dataString,"&"); while(st.hasMoreTokens()){ String[] ss = st.nextToken().split("="); map.put(ss[0], ss[1]); } } } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUrlPattern() { return urlPattern; } public void setUrlPattern(String urlPattern) { this.urlPattern = urlPattern; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getHeadInfo() { return headInfo; } public void setHeadInfo(String headInfo) { this.headInfo = headInfo; } public String getParameter(String name){ if(map != null && map.size() > 0){ return (String)map.get(name); } return null; } }