Tomcat的学习之路一
- 学tomcat之前,先看个简单的例子
- 这个是启动类
package tomcatDemo; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class Server { public static final String SHUT_DOWN="/SHUTDOWN"; private boolean shutdown=false; public static void main(String[] args) { Server server=new Server(); server.await(); } private void await() { System.out.println(Thread.currentThread().getName()+" is start"); // TODO Auto-generated method stub ServerSocket server = null; try { server = new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1")); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i=0; while(!shutdown){ System.out.println("the thread is running "+ i++); Socket socket=null; OutputStream out; InputStream in; try { socket=server.accept(); out = socket.getOutputStream(); in = socket.getInputStream(); Request request = new Request(in); request.parseUri(); Response response = new Response(out); response.setRequest(request); System.out.println(request.getUri()); if(request.getUri()!=null){ if(request.getUri().startsWith("/servlet/")){ ServerProcessor processor=new ServerProcessor(); processor.process(request,response); }else{ StaticProcessor processor=new StaticProcessor(); processor.process(request,response); } } socket.close(); shutdown=SHUT_DOWN.equals(request.getUri()); System.out.println(shutdown); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } } } }
- 这个是执行动态请求的类,比如servlet
package tomcatDemo; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandler; import javax.servlet.Servlet; public class ServerProcessor { public void process(Request request, Response response) { // TODO Auto-generated method stub String uri = request.getUri(); String servletName= uri.substring(uri.lastIndexOf("/")+1); URLClassLoader loader = null; try { URL[] urls =new URL[1]; URLStreamHandler streamHandler=null; File classPath =new File(Constants.WEB_ROOT); String repository = (new URL("file",null,classPath.getCanonicalPath()+File.separator)).toString(); urls[0] = new URL(null, repository, streamHandler); loader=new URLClassLoader(urls); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Class myClass=null; try { myClass = loader.loadClass(servletName); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Servlet servlet=null; try { servlet = (Servlet) myClass.newInstance(); servlet.service(request, response);; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
- 下面分别是是request和response
package tomcatDemo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import javax.servlet.AsyncContext; import javax.servlet.DispatcherType; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class Request implements ServletRequest { InputStream in; String uri; public Request(InputStream in) { super(); this.in = in; } public String getUri() { return uri; } public void parseUri() throws IOException { StringBuffer sb = new StringBuffer(); byte[] request=new byte[2014]; in.read(request); for (int i = 0; i < request.length; i++) { sb.append((char)request[i]); } int start = sb.indexOf(" "); if(start!=-1){ int end = sb.indexOf(" ", start+1); if(end > start){ uri=sb.substring(start+1,end); } } System.out.println(uri); } @Override public AsyncContext getAsyncContext() { // TODO Auto-generated method stub return null; } @Override public Object getAttribute(String arg0) { // TODO Auto-generated method stub return null; } @Override public Enumeration<String> getAttributeNames() { // TODO Auto-generated method stub return null; } @Override public String getCharacterEncoding() { // TODO Auto-generated method stub return null; } @Override public int getContentLength() { // TODO Auto-generated method stub return 0; } @Override public String getContentType() { // TODO Auto-generated method stub return null; } @Override public DispatcherType getDispatcherType() { // TODO Auto-generated method stub return null; } @Override public ServletInputStream getInputStream() throws IOException { // TODO Auto-generated method stub return null; } @Override public String getLocalAddr() { // TODO Auto-generated method stub return null; } @Override public String getLocalName() { // TODO Auto-generated method stub return null; } @Override public int getLocalPort() { // TODO Auto-generated method stub return 0; } @Override public Locale getLocale() { // TODO Auto-generated method stub return null; } @Override public Enumeration<Locale> getLocales() { // TODO Auto-generated method stub return null; } @Override public String getParameter(String arg0) { // TODO Auto-generated method stub return null; } @Override public Map<String, String[]> getParameterMap() { // TODO Auto-generated method stub return null; } @Override public Enumeration<String> getParameterNames() { // TODO Auto-generated method stub return null; } @Override public String[] getParameterValues(String arg0) { // TODO Auto-generated method stub return null; } @Override public String getProtocol() { // TODO Auto-generated method stub return null; } @Override public BufferedReader getReader() throws IOException { // TODO Auto-generated method stub return null; } @Override public String getRealPath(String arg0) { // TODO Auto-generated method stub return null; } @Override public String getRemoteAddr() { // TODO Auto-generated method stub return null; } @Override public String getRemoteHost() { // TODO Auto-generated method stub return null; } @Override public int getRemotePort() { // TODO Auto-generated method stub return 0; } @Override public RequestDispatcher getRequestDispatcher(String arg0) { // TODO Auto-generated method stub return null; } @Override public String getScheme() { // TODO Auto-generated method stub return null; } @Override public String getServerName() { // TODO Auto-generated method stub return null; } @Override public int getServerPort() { // TODO Auto-generated method stub return 0; } @Override public ServletContext getServletContext() { // TODO Auto-generated method stub return null; } @Override public boolean isAsyncStarted() { // TODO Auto-generated method stub return false; } @Override public boolean isAsyncSupported() { // TODO Auto-generated method stub return false; } @Override public boolean isSecure() { // TODO Auto-generated method stub return false; } @Override public void removeAttribute(String arg0) { // TODO Auto-generated method stub } @Override public void setAttribute(String arg0, Object arg1) { // TODO Auto-generated method stub } @Override public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { // TODO Auto-generated method stub } @Override public AsyncContext startAsync() { // TODO Auto-generated method stub return null; } @Override public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) { // TODO Auto-generated method stub return null; } }
package tomcatDemo; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Locale; import javax.servlet.ServletOutputStream; import javax.servlet.ServletResponse; public class Response implements ServletResponse { OutputStream out; Request request; PrintWriter writer; private static final int SIZE = 2048; public Response(OutputStream out) { super(); this.out = out; } public OutputStream getOut() { return out; } public void setOut(OutputStream out) { this.out = out; } public Request getRequest() { return request; } public void setRequest(Request request) { this.request = request; } public void senndStaticResouce() throws IOException { // TODO Auto-generated method stub byte[] buffer=new byte[SIZE]; FileInputStream fis=null; try{ File file=new File(Constants.WEB_ROOT,request.getUri()); System.out.println(file.getPath()); fis=new FileInputStream(file); int ch=fis.read(buffer,0,SIZE); String header="HTTP/1.1 200 OK \r\n" + "Content-Type:text/html\r\n" + "\r\n"; StringBuilder sb=new StringBuilder(header); if(ch!=-1){ for (int i = 0; i < ch; i++) { sb.append((char)buffer[i]); } ch=fis.read(buffer,0,SIZE); } System.out.println(sb); out.write(sb.toString().getBytes()); }catch (Exception e) { // TODO: handle exception String errorMessage="HTTP/1.1 404 file not found \r\n" + "Content-Type:text/html\r\n" + "Content-Length:23\r\n" + "\r\n" + "<h1>调毛呀,没看到404吗</h1>"; out.write(errorMessage.getBytes()); }finally{ if(fis!=null){ fis.close(); } } } @Override public void flushBuffer() throws IOException { // TODO Auto-generated method stub } @Override public int getBufferSize() { // TODO Auto-generated method stub return 0; } @Override public String getCharacterEncoding() { // TODO Auto-generated method stub return null; } @Override public String getContentType() { // TODO Auto-generated method stub return null; } @Override public Locale getLocale() { // TODO Auto-generated method stub return null; } @Override public ServletOutputStream getOutputStream() throws IOException { // TODO Auto-generated method stub return null; } @Override public PrintWriter getWriter() throws IOException { // TODO Auto-generated method stub writer=new PrintWriter(out,true); return writer; } @Override public boolean isCommitted() { // TODO Auto-generated method stub return false; } @Override public void reset() { // TODO Auto-generated method stub } @Override public void resetBuffer() { // TODO Auto-generated method stub } @Override public void setBufferSize(int arg0) { // TODO Auto-generated method stub } @Override public void setCharacterEncoding(String arg0) { // TODO Auto-generated method stub } @Override public void setContentLength(int arg0) { // TODO Auto-generated method stub } @Override public void setContentType(String arg0) { // TODO Auto-generated method stub } @Override public void setLocale(Locale arg0) { // TODO Auto-generated method stub } }
- 还有常量类
package tomcatDemo; public class Constants { public static final String WEB_ROOT = System.getProperty("user.dir"); }
- 这个是UML图