diff --git a/14301056/.DS_Store b/14301056/.DS_Store new file mode 100644 index 0000000..02365af Binary files /dev/null and b/14301056/.DS_Store differ diff --git a/14301056/bin/.DS_Store b/14301056/bin/.DS_Store new file mode 100644 index 0000000..3623d60 Binary files /dev/null and b/14301056/bin/.DS_Store differ diff --git a/14301056/bin/jsp/Constants.class b/14301056/bin/jsp/Constants.class new file mode 100755 index 0000000..06d2187 Binary files /dev/null and b/14301056/bin/jsp/Constants.class differ diff --git a/14301056/bin/jsp/HttpServer.class b/14301056/bin/jsp/HttpServer.class new file mode 100755 index 0000000..2bb9977 Binary files /dev/null and b/14301056/bin/jsp/HttpServer.class differ diff --git a/14301056/bin/jsp/Request.class b/14301056/bin/jsp/Request.class new file mode 100755 index 0000000..a7b708c Binary files /dev/null and b/14301056/bin/jsp/Request.class differ diff --git a/14301056/bin/jsp/Response.class b/14301056/bin/jsp/Response.class new file mode 100755 index 0000000..86fc347 Binary files /dev/null and b/14301056/bin/jsp/Response.class differ diff --git a/14301056/bin/jsp/ServletProcessor.class b/14301056/bin/jsp/ServletProcessor.class new file mode 100755 index 0000000..09b6cde Binary files /dev/null and b/14301056/bin/jsp/ServletProcessor.class differ diff --git a/14301056/bin/jsp/StaticResourceProcessor.class b/14301056/bin/jsp/StaticResourceProcessor.class new file mode 100755 index 0000000..c72073d Binary files /dev/null and b/14301056/bin/jsp/StaticResourceProcessor.class differ diff --git a/14301056/bin/jsp/jspReader.class b/14301056/bin/jsp/jspReader.class new file mode 100755 index 0000000..52b18fc Binary files /dev/null and b/14301056/bin/jsp/jspReader.class differ diff --git a/14301056/part/part_1.txt b/14301056/part/part_1.txt new file mode 100755 index 0000000..8c73e95 --- /dev/null +++ b/14301056/part/part_1.txt @@ -0,0 +1,11 @@ +import java.io.IOException; +import java.io.PrintWriter; +import javax.servlet.Servlet; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import java.text.*; +import java.util.*; + +public class \ No newline at end of file diff --git a/14301056/part/part_2.txt b/14301056/part/part_2.txt new file mode 100755 index 0000000..28956d9 --- /dev/null +++ b/14301056/part/part_2.txt @@ -0,0 +1,5 @@ +implements Servlet { + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { + PrintWriter out = response.getWriter(); + out.println("HTTP/1.1 200 OK\r\n"); + out.println(" \ No newline at end of file diff --git a/14301056/part/part_3.txt b/14301056/part/part_3.txt new file mode 100755 index 0000000..45b84d9 --- /dev/null +++ b/14301056/part/part_3.txt @@ -0,0 +1,25 @@ + "); +} + + + public void destroy() { + + } + + + public ServletConfig getServletConfig() { + + return null; + } + + + public String getServletInfo() { + + return null; + } + + + public void init(ServletConfig arg0) throws ServletException { + + } +} \ No newline at end of file diff --git a/14301056/part/part_4.txt b/14301056/part/part_4.txt new file mode 100755 index 0000000..e85bd9f --- /dev/null +++ b/14301056/part/part_4.txt @@ -0,0 +1,7 @@ +"); +out.println(" +out.println( +// +" +File.separator +File.separator +" +" +\" diff --git a/14301056/src/jsp/Constants.java b/14301056/src/jsp/Constants.java new file mode 100755 index 0000000..9a1c72b --- /dev/null +++ b/14301056/src/jsp/Constants.java @@ -0,0 +1,11 @@ +package jsp; + +import java.io.File; + +public class Constants { + public static final String WEB_ROOT = System.getProperty("user.dir") + + File.separator; + public static final String WEB_SERVLET_ROOT = System.getProperty("user.dir") + + File.separator + "target" + File.separator + "classes"; + +} diff --git a/14301056/src/jsp/HttpServer.java b/14301056/src/jsp/HttpServer.java new file mode 100755 index 0000000..7d0639c --- /dev/null +++ b/14301056/src/jsp/HttpServer.java @@ -0,0 +1,254 @@ +package jsp; + +import java.net.Socket; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import jsp.Request; +import jsp.Response; +import jsp.jspReader; + +import java.net.ServerSocket; +import java.net.InetAddress; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.File; +import java.io.IOException; + +public class HttpServer { + + // 关闭服务命令 + private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; + + public static void main(String[] args) { + HttpServer server = new HttpServer(); + // 等待连接请求 + server.await(); + } + + public void await() { + ServerSocket serverSocket = null; + int port = 8080; + try { + // 服务器套接字对象 + serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); + } catch (IOException e) { + e.printStackTrace(); + System.exit(1); + } + + // 循环等待请求 + while (true) { + Socket socket = null; + InputStream input = null; + OutputStream output = null; + try { + // 等待连接,连接成功后,返回一个Socket对象 + socket = serverSocket.accept(); + input = socket.getInputStream(); + output = socket.getOutputStream(); + + // 创建Request对象并解析 + Request request = new Request(input); + request.parse(); + + // 创建 Response 对象 + Response response = new Response(output); + response.setRequest(request); + + // 取到url + String url = request.getUri(); + + // 解析xml + /* + * Boolean canRead = findurl(url); + * + * if(canRead) { + * //解析xml得到类名 + * String servletName = getServeletName(url); + * ServletProcessor processor = new ServletProcessor(); + * processor.process(request,response,servletName); + * } + * else { + * StaticResourceProcessor + * processor = new StaticResourceProcessor(); + * processor.process(request, response); } + */ + String filename = System.getProperty("user.dir")+ File.separator +"jsp" + File.separator + url; + if(new File(filename).exists()) + { + // 转换jsp + jspReader jsp = new jspReader(url.split("/")[1]); + ServletProcessor processor = new ServletProcessor(); + processor.process(request,response,jsp.getServletName()); + } + else + { + System.out.println("找不到该文件!"); + } + + + // 关闭 socket + socket.close(); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + } + + public Boolean findurl(String url) { + Element element = null; + // 可以使用绝对路径 + File f = new File("web.xml"); + + DocumentBuilder db = null; + DocumentBuilderFactory dbf = null; + try { + dbf = DocumentBuilderFactory.newInstance(); + db = dbf.newDocumentBuilder(); + Document dt = db.parse(f); + + // 得到一个elment根元素 + element = dt.getDocumentElement(); + + // 获得根元素下的子节点 + NodeList childNodes = element.getChildNodes(); + + NodeList theNodeList = null; + + // 遍历这些子节点 + for (int i = 0; i < childNodes.getLength(); i++) { + // 获得每个对应位置i的结点 + Node node1 = childNodes.item(i); + + // 匹配每一个servelet-mapping里的uri + if ("servlet-mapping".equals(node1.getNodeName())) { + + NodeList nodeDetail = node1.getChildNodes(); + + for (int j = 0; j < nodeDetail.getLength(); j++) { + Node detail = nodeDetail.item(j); + + if ("url-pattern".equals(detail.getNodeName())) { + // 匹配url + if (url.equals(detail.getTextContent()))// 如果匹配到,返回true + return true; + } + + } + } + } + } + + catch (Exception e) { + System.out.println(e.toString()); + } + + return false; + } + + public String getServeletName(String url) { + String ServeletName = null; + + Element element = null; + // 可以使用绝对路径 + File f = new File("web.xml"); + + DocumentBuilder db = null; + DocumentBuilderFactory dbf = null; + try { + dbf = DocumentBuilderFactory.newInstance(); + db = dbf.newDocumentBuilder(); + Document dt = db.parse(f); + + // 得到一个elment根元素 + element = dt.getDocumentElement(); + + // 获得根元素下的子节点 + NodeList childNodes = element.getChildNodes(); + + NodeList theNodeList = null; + + // 遍历这些子节点 + for (int i = 0; i < childNodes.getLength(); i++) { + // 获得每个对应位置i的结点 + Node node1 = childNodes.item(i); + + // 匹配每一个servelet-mapping里的uri + if ("servlet-mapping".equals(node1.getNodeName())) { + + NodeList nodeDetail = node1.getChildNodes(); + + for (int j = 0; j < nodeDetail.getLength(); j++) { + Node detail = nodeDetail.item(j); + + if ("url-pattern".equals(detail.getNodeName())) { + // 匹配url + if (url.equals(detail.getTextContent()))// 如果匹配到,将该节点取出 + theNodeList = nodeDetail; + } + + } + } + } + + String Sname = null; + // 取出名字 + for (int j = 0; j < theNodeList.getLength(); j++) { + Node detail = theNodeList.item(j); + + if ("servlet-name".equals(detail.getNodeName())) // 匹配name + { + Sname = detail.getTextContent(); + } + + } + + NodeList theNodeList1 = null; + + // 再次遍历,匹配对应servelet-class + for (int i = 0; i < childNodes.getLength(); i++) { + // 获得每个对应位置i的结点 + Node node1 = childNodes.item(i); + + // 匹配每一个servelet里的uri + if ("servlet".equals(node1.getNodeName())) { + + NodeList nodeDetail = node1.getChildNodes(); + + for (int j = 0; j < nodeDetail.getLength(); j++) { + Node detail = nodeDetail.item(j); + + if ("servlet-name".equals(detail.getNodeName())) // 匹配url对应名字 + if (Sname.equals(detail.getTextContent()))// 如果匹配到,将该节点取出 + theNodeList1 = nodeDetail; + } + } + } + // 取出serveletname + for (int j = 0; j < theNodeList1.getLength(); j++) { + Node detail = theNodeList1.item(j); + + if ("servlet-class".equals(detail.getNodeName())) // 匹配 + { + ServeletName = detail.getTextContent(); + } + + } + } + + catch (Exception e) { + e.printStackTrace(); + } + + return ServeletName; + } +} diff --git a/14301056/src/jsp/Request.java b/14301056/src/jsp/Request.java new file mode 100755 index 0000000..6185a1d --- /dev/null +++ b/14301056/src/jsp/Request.java @@ -0,0 +1,188 @@ +package jsp; + +import java.io.InputStream; +import java.io.IOException; +import java.io.BufferedReader; +import java.io.UnsupportedEncodingException; +import java.util.Enumeration; +import java.util.Locale; +import java.util.Map; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletRequest; + +public class Request implements ServletRequest { + + private InputStream input; + private String uri; + + public Request(InputStream input) { + this.input = input; + } + + public String getUri() { + return uri; + } + /** + * + * requestString形式如下: + * GET /index.html HTTP/1.1 + * Host: localhost:8080 + * Connection: keep-alive + * Cache-Control: max-age=0 + * ... + * 该函数目的就是为了获取/index.html字符串 + */ + private String parseUri(String requestString) { + int index1, index2; + index1 = requestString.indexOf(' '); + if (index1 != -1) { + index2 = requestString.indexOf(' ', index1 + 1); + if (index2 > index1) + return requestString.substring(index1 + 1, index2); + } + return null; + } + //从InputStream中读取request信息,并从request中获取uri值 + public void parse() { + // Read a set of characters from the socket + StringBuffer request = new StringBuffer(2048); + int i; + byte[] buffer = new byte[2048]; + try { + i = input.read(buffer); + } catch (IOException e) { + e.printStackTrace(); + i = -1; + } + for (int j = 0; j < i; j++) { + request.append((char) buffer[j]); + } + System.out.print(request.toString()); + uri = parseUri(request.toString()); + } + + /* implementation of the ServletRequest */ + public Object getAttribute(String attribute) { + return null; + } + + public Enumeration getAttributeNames() { + return null; + } + + public String getRealPath(String path) { + return null; + } + + public RequestDispatcher getRequestDispatcher(String path) { + return null; + } + + public boolean isSecure() { + return false; + } + + public String getCharacterEncoding() { + return null; + } + + public int getContentLength() { + return 0; + } + + public String getContentType() { + return null; + } + + public ServletInputStream getInputStream() throws IOException { + return null; + } + + public Locale getLocale() { + return null; + } + + public Enumeration getLocales() { + return null; + } + + public String getParameter(String name) { + return null; + } + + public Map getParameterMap() { + return null; + } + + public Enumeration getParameterNames() { + return null; + } + + public String[] getParameterValues(String parameter) { + return null; + } + + public String getProtocol() { + return null; + } + + public BufferedReader getReader() throws IOException { + return null; + } + + public String getRemoteAddr() { + return null; + } + + public String getRemoteHost() { + return null; + } + + public String getScheme() { + return null; + } + + public String getServerName() { + return null; + } + + public int getServerPort() { + return 0; + } + + public void removeAttribute(String attribute) { + } + + public void setAttribute(String key, Object value) { + } + + public void setCharacterEncoding(String encoding) + throws UnsupportedEncodingException { + } + +@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 int getRemotePort() { + // TODO Auto-generated method stub + return 0; +} + +} diff --git a/14301056/src/jsp/Response.java b/14301056/src/jsp/Response.java new file mode 100755 index 0000000..eb6bd12 --- /dev/null +++ b/14301056/src/jsp/Response.java @@ -0,0 +1,115 @@ +package jsp; + +import java.io.OutputStream; +import java.io.IOException; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.File; +import java.io.PrintWriter; +import java.util.Locale; +import javax.servlet.ServletResponse; +import javax.servlet.ServletOutputStream; + +public class Response implements ServletResponse { + + private static final int BUFFER_SIZE = 1024; + Request request; + OutputStream output; + PrintWriter writer; + + public Response(OutputStream output) { + this.output = output; + } + + public void setRequest(Request request) { + this.request = request; + } + + //将web文件写入到OutputStream字节流中 +//将web文件写入到OutputStream字节流中 +public void sendStaticResource() throws IOException { +byte[] bytes = new byte[BUFFER_SIZE]; +FileInputStream fis = null; +try { +/* request.getUri has been replaced by request.getRequestURI */ +File file = new File(Constants.WEB_ROOT, request.getUri()); +fis = new FileInputStream(file); +/* +* HTTP Response = Status-Line(( general-header | response-header | +* entity-header ) CRLF) CRLF [ message-body ] Status-Line = +* HTTP-Version SP Status-Code SP Reason-Phrase CRLF +*/ +int ch = fis.read(bytes, 0, BUFFER_SIZE); +while (ch != -1) { +output.write(bytes, 0, ch); +ch = fis.read(bytes, 0, BUFFER_SIZE); +} +} catch (FileNotFoundException e) { +String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + + "Content-Type: text/html\r\n" + "Content-Length: 23\r\n" + + "\r\n" + "

File Not Found

"; +output.write(errorMessage.getBytes()); +} finally { +if (fis != null) +fis.close(); +} +} + + + /** implementation of ServletResponse */ + public void flushBuffer() throws IOException { + } + + public int getBufferSize() { + return 0; + } + + public String getCharacterEncoding() { + return null; + } + + public Locale getLocale() { + return null; + } + + public ServletOutputStream getOutputStream() throws IOException { + return null; + } + + public PrintWriter getWriter() throws IOException { + // autoflush is true, println() will flush, + // but print() will not. + writer = new PrintWriter(output, true); + return writer; + } + + public boolean isCommitted() { + return false; + } + + public void reset() { + } + + public void resetBuffer() { + } + + public void setBufferSize(int size) { + } + + public void setContentLength(int length) { + } + + public void setContentType(String type) { + } + + public void setLocale(Locale locale) { + } + +public String getContentType() { + return null; +} + +public void setCharacterEncoding(String arg0) { +} + +} diff --git a/14301056/src/jsp/ServletProcessor.java b/14301056/src/jsp/ServletProcessor.java new file mode 100755 index 0000000..7dc2ae2 --- /dev/null +++ b/14301056/src/jsp/ServletProcessor.java @@ -0,0 +1,56 @@ +package jsp; + +import java.net.URL; +import java.net.URLClassLoader; +import java.net.URLStreamHandler; +import java.io.File; +import java.io.IOException; + +import javax.servlet.Servlet; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import jsp.Request; +import jsp.Response; + +public class ServletProcessor { + + public void process(Request request, Response response,String servletName) { + + //类加载器,用于从指定JAR文件或目录加载类 + URLClassLoader loader = null; + try { + URLStreamHandler streamHandler = null; + //创建类加载器 + System.out.println(System.getProperty("user.dir")+ File.separator+ "work" + File.separator); + loader = new URLClassLoader(new URL[]{new URL(null, "file:" + + System.getProperty("user.dir")+ File.separator+ "work" + File.separator, + streamHandler)}); + } catch (IOException e) { + System.out.println(e.toString()); + } + + Class myClass = null; + try { + //加载对应的servlet类 + myClass = loader.loadClass(servletName); + } catch (ClassNotFoundException e) { + System.out.println(e.toString()); + } + + Servlet servlet = null; + + try { + //生产servlet实例 + servlet = (Servlet) myClass.newInstance(); + //执行ervlet的service方法 + servlet.service((ServletRequest) request,(ServletResponse) response); + } catch (Exception e) { + System.out.println(e.toString()); + } catch (Throwable e) { + System.out.println(e.toString()); + } + + } + +} diff --git a/14301056/src/jsp/StaticResourceProcessor.java b/14301056/src/jsp/StaticResourceProcessor.java new file mode 100755 index 0000000..894e6ef --- /dev/null +++ b/14301056/src/jsp/StaticResourceProcessor.java @@ -0,0 +1,15 @@ +package jsp; + +import java.io.IOException; + +public class StaticResourceProcessor { + + public void process(Request request, Response response) { + try { + response.sendStaticResource(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} + \ No newline at end of file diff --git a/14301056/src/jsp/aa.java b/14301056/src/jsp/aa.java new file mode 100755 index 0000000..e69de29 diff --git a/14301056/src/jsp/jspReader.java b/14301056/src/jsp/jspReader.java new file mode 100755 index 0000000..ca211c8 --- /dev/null +++ b/14301056/src/jsp/jspReader.java @@ -0,0 +1,193 @@ +package jsp; + +import java.io.*; +import java.net.URLClassLoader; +import java.util.Arrays; + +import javax.tools.*; + +public class jspReader { + + private String jspName; + private String jspContent = null; + private String ServeletContent = null; + + public jspReader(String uri) { + jspName = uri; + Read(); + makeServlet(); + } + + public void init() { + + } + + public void Read() { + File f = new File(System.getProperty("user.dir") + File.separator + "jsp" + File.separator + jspName); + + BufferedReader br; + + try { + br = new BufferedReader(new FileReader(f)); + + String line = br.readLine(); + + if(line.contains("<%@")) + { + line = "<% response.setContentType(\"text/html; charset=gb2312\");%>"; + line = line.replace("\"", "&&&&"); + } + + jspContent = line; + + while ((line = br.readLine()) != null) { + + if(line.contains("<%=")) + { + line = line.replace("<%=", "$$out.println("); + line = line.replace("%>", ");&&"); + line = line.replace("\"", "&&&&"); + } + + jspContent = jspContent + " " + line; + } + + br.close(); + // System.out.println(jspContent); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println(jspContent); + } + + public void makeServlet() { + // 读取4个文件 + File f1 = new File(System.getProperty("user.dir") + File.separator + "part" + File.separator + "part_1.txt"); + File f2 = new File(System.getProperty("user.dir") + File.separator + "part" + File.separator + "part_2.txt"); + File f3 = new File(System.getProperty("user.dir") + File.separator + "part" + File.separator + "part_3.txt"); + File f4 = new File(System.getProperty("user.dir") + File.separator + "part" + File.separator + "part_4.txt"); + + BufferedReader br1, br2, br3, br4; + + try { + // 读part4 + br4 = new BufferedReader(new FileReader(f4)); + + String line = null; + + String[] sign = new String[7]; + + sign[0] = br4.readLine(); + sign[1] = "\n" + br4.readLine() ; + sign[2] = sign[0] + br4.readLine(); + sign[3] = br4.readLine(); + sign[4] = br4.readLine(); + sign[5] = br4.readLine(); + sign[6] = br4.readLine(); + + br4.close(); + // + // 替换 + // String ServeletContent1 = jspContent.replace(sign[5], sign[6]); + String ServeletContent1 = jspContent.replace("$$out.println(", sign[2]); + ServeletContent1 = ServeletContent1.replace(");&&",");" + sign[1] ); + ServeletContent1 = ServeletContent1.replace("<%", sign[0]); + ServeletContent1 = ServeletContent1.replace("%>", sign[1]); + ServeletContent1 = ServeletContent1.replace("&&&&", sign[5]); + + + // import-class + br1 = new BufferedReader(new FileReader(f1)); + + line = null; + + ServeletContent = br1.readLine(); + + while ((line = br1.readLine()) != null) { + + ServeletContent = ServeletContent + "\n" + line; + } + + br1.close(); + // + + ServeletContent = ServeletContent + "\n" + jspName.split(".jsp")[0] + "Servlet\n"; + // System.out.println(jspName.split(".jsp")[0]); + + // 读part2 + br2 = new BufferedReader(new FileReader(f2)); + + line = null; + + ServeletContent = ServeletContent + br2.readLine(); + + while ((line = br2.readLine()) != null) { + + ServeletContent = ServeletContent + "\n" + line; + } + + br2.close(); + // + ServeletContent = ServeletContent + ServeletContent1; + // part3 + br3 = new BufferedReader(new FileReader(f3)); + + line = null; + + ServeletContent = ServeletContent + br3.readLine(); + + while ((line = br3.readLine()) != null) { + + ServeletContent = ServeletContent + "\n" + line; + } + + br3.close(); + // + + + + // System.out.println(ServeletContent); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // 创建java + File f = new File(System.getProperty("user.dir") + File.separator + "work" + File.separator + + jspName.split(".jsp")[0] + "Servlet.java"); + try { + if (!f.exists()) { + f.createNewFile(); + } + FileWriter fw = new FileWriter(f); + + fw.write(ServeletContent); + + fw.close(); + + String dir = System.getProperty("user.dir") + File.separator+ "work"; + String filename = jspName.split(".jsp")[0] + "Servlet.java"; + + // 获得系统编译器 + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + + StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); + // 读入源文件 + Iterable fileObject = fileManager.getJavaFileObjects(new File(dir,filename)); + // 编译 + JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, Arrays.asList("-d", "./work"), + null, fileObject); + task.call(); + + fileManager.close(); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + public String getServletName() + { + return jspName.split(".jsp")[0] + "Servlet"; + } +} diff --git a/1stweek/14301056.py b/1stweek/14301056.py new file mode 100644 index 0000000..e69c3d3 --- /dev/null +++ b/1stweek/14301056.py @@ -0,0 +1,58 @@ +# -*- coding: utf8 -*- +# Multi Thread +import socket +import traceback +import thread + + +def ReverseString(ss): + ans = '' + l = len(ss) + while l > 0: + l -= 1 + ans += ss[l] + return ans + +def ClientServer(clientsock, clientaddr): + try: + print(clientsock.getpeername()) + while 1: + data = clientsock.recv(1024) + if not len(data): + break + print(clientsock.getpeername()), + print(': '+str(data)) + back = ReverseString(str(data)) + clientsock.sendall(back + "\n") + # clientsock.sendall("\nI get it!\n") + + except (KeyboardInterrupt,SystemExit): + raise + except: + traceback.print_exc() + try: + clientsock.close() + except KeyboardInterrupt: + raise + except: + traceback.print_exc() + +def main(): + host = '' + port = 3333 + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind((host, port)) + s.listen(1) + while 1: + try: + clientsock, clientaddr=s.accept() + except KeyboardInterrupt: + raise + except: + traceback.print_exc() + continue + thread.start_new_thread(ClientServer, (clientsock, clientaddr)) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/2ndweek/.DS_Store b/2ndweek/.DS_Store new file mode 100644 index 0000000..90206a0 Binary files /dev/null and b/2ndweek/.DS_Store differ diff --git a/2ndweek/simple_wsgi_server-master/.DS_Store b/2ndweek/simple_wsgi_server-master/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/2ndweek/simple_wsgi_server-master/.DS_Store differ diff --git a/2ndweek/simple_wsgi_server-master/.gitignore b/2ndweek/simple_wsgi_server-master/.gitignore new file mode 100755 index 0000000..ee64372 --- /dev/null +++ b/2ndweek/simple_wsgi_server-master/.gitignore @@ -0,0 +1,2 @@ +.idea/ +*.pyc diff --git a/2ndweek/simple_wsgi_server-master/app.py b/2ndweek/simple_wsgi_server-master/app.py new file mode 100755 index 0000000..8e4a2e2 --- /dev/null +++ b/2ndweek/simple_wsgi_server-master/app.py @@ -0,0 +1,10 @@ +# coding: utf-8 +from __future__ import unicode_literals +from wsgiref import simple_server + + +def app(environ, start_response): + status = '200 OK' + response_headers = [('Content-Type', 'text/plain')] + start_response(status, response_headers) + return ['Hello world from a RAPOWSGI application!\n'] diff --git a/2ndweek/simple_wsgi_server-master/middleware.py b/2ndweek/simple_wsgi_server-master/middleware.py new file mode 100755 index 0000000..5bee6ef --- /dev/null +++ b/2ndweek/simple_wsgi_server-master/middleware.py @@ -0,0 +1,14 @@ +# coding: utf-8 + +from __future__ import unicode_literals + + +class TestMiddle(object): + def __init__(self, application): + self.application = application + + def __call__(self, environ, start_response): + if 'postman' in environ.get('USER_AGENT'): + start_response('403 Not Allowed', []) + return ['not allowed!'] + return self.application(environ, start_response) diff --git a/2ndweek/simple_wsgi_server-master/server.py b/2ndweek/simple_wsgi_server-master/server.py new file mode 100755 index 0000000..6fe8669 --- /dev/null +++ b/2ndweek/simple_wsgi_server-master/server.py @@ -0,0 +1,115 @@ +# coding: utf-8 +from __future__ import unicode_literals + +import socket +import StringIO +import sys +import datetime + +from middleware import TestMiddle +from wsgiref import simple_server + + +class WSGIServer(object): + socket_family = socket.AF_INET + socket_type = socket.SOCK_STREAM + request_queue_size = 10 + + def __init__(self, address): + self.socket = socket.socket(self.socket_family, self.socket_type) + self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.socket.bind(address) + self.socket.listen(self.request_queue_size) + host, port = self.socket.getsockname()[:2] + self.host = host + self.port = port + + def set_application(self, application): + self.application = application + + def serve_forever(self): + while 1: + self.connection, client_address = self.socket.accept() + self.handle_request() + + def handle_request(self): + self.request_data = self.connection.recv(1024) + self.request_lines = self.request_data.splitlines() + try: + self.get_url_parameter() + env = self.get_environ() + app_data = self.application(env, self.start_response) + self.finish_response(app_data) + print '[{0}] "{1}" {2}'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), + self.request_lines[0], self.status) + except Exception, e: + pass + + def get_url_parameter(self): + self.request_dict = {'Path': self.request_lines[0]} + for itm in self.request_lines[1:]: + if ':' in itm: + self.request_dict[itm.split(':')[0]] = itm.split(':')[1] + self.request_method, self.path, self.request_version = self.request_dict.get('Path').split() + + def get_environ(self): + env = { + 'wsgi.version': (1, 0), + 'wsgi.url_scheme': 'http', + 'wsgi.input': StringIO.StringIO(self.request_data), + 'wsgi.errors': sys.stderr, + 'wsgi.multithread': False, + 'wsgi.multiprocess': False, + 'wsgi.run_once': False, + 'REQUEST_METHOD': self.request_method, + 'PATH_INFO': self.path, + 'SERVER_NAME': self.host, + 'SERVER_PORT': self.port, + 'USER_AGENT': self.request_dict.get('User-Agent') + } + return env + + def start_response(self, status, response_headers): + headers = [ + ('Date', datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S GMT')), + ('Server', 'RAPOWSGI0.1'), + ] + self.headers = response_headers + headers + self.status = status + + def finish_response(self, app_data): + try: + response = 'HTTP/1.1 {status}\r\n'.format(status=self.status) + for header in self.headers: + response += '{0}: {1}\r\n'.format(*header) + response += '\r\n' + for data in app_data: + response += data + self.connection.sendall(response) + finally: + self.connection.close() + + +if __name__ == '__main__': + port = 8888 + if len(sys.argv) < 2: + sys.exit('璇锋彁渚涘彲鐢ㄧ殑wsgi搴旂敤绋嬪簭, 鏍煎紡涓: 妯″潡鍚.搴旂敤鍚') + elif len(sys.argv) > 2: + port = sys.argv[2] + + + def generate_server(address, application): + server = WSGIServer(address) + server.set_application(TestMiddle(application)) + return server + + + app_path = sys.argv[1] + module, application = app_path.split('.') + module = __import__(module) + application = getattr(module, application) + httpd = generate_server(('', int(port)), application) + print 'RAPOWSGI Server Serving HTTP service on port {0}'.format(port) + print '{0}'.format(datetime.datetime.now(). + strftime('%a, %d %b %Y %H:%M:%S GMT')) + httpd.serve_forever() diff --git a/2ndweek/simple_wsgi_server-master/tornado_wsgi.py b/2ndweek/simple_wsgi_server-master/tornado_wsgi.py new file mode 100755 index 0000000..5959b87 --- /dev/null +++ b/2ndweek/simple_wsgi_server-master/tornado_wsgi.py @@ -0,0 +1,28 @@ +# coding: utf-8 + +from __future__ import unicode_literals + +import datetime +import tornado.web +import tornado.wsgi + +from middleware import TestMiddle +from server import WSGIServer + + +class MainHandler(tornado.web.RequestHandler): + def get(self): + self.write("this is a tornado wsgi application") + + +if __name__ == "__main__": + application = tornado.web.Application([ + (r"/", MainHandler), + ]) + wsgi_app = tornado.wsgi.WSGIAdapter(application) + server = WSGIServer(('', 9090)) + server.set_application(TestMiddle(wsgi_app)) + print 'RAPOWSGI Server Serving HTTP service on port {0}'.format(9090) + print '{0}'.format(datetime.datetime.now(). + strftime('%a, %d %b %Y %H:%M:%S GMT')) + server.serve_forever() diff --git a/3rdweek/.DS_Store b/3rdweek/.DS_Store new file mode 100644 index 0000000..8f77094 Binary files /dev/null and b/3rdweek/.DS_Store differ diff --git a/3rdweek/TestServer/.DS_Store b/3rdweek/TestServer/.DS_Store new file mode 100644 index 0000000..d55f48d Binary files /dev/null and b/3rdweek/TestServer/.DS_Store differ diff --git a/3rdweek/TestServer/.classpath b/3rdweek/TestServer/.classpath new file mode 100755 index 0000000..a95193d --- /dev/null +++ b/3rdweek/TestServer/.classpath @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/3rdweek/TestServer/.idea/compiler.xml b/3rdweek/TestServer/.idea/compiler.xml new file mode 100644 index 0000000..96cc43e --- /dev/null +++ b/3rdweek/TestServer/.idea/compiler.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/.idea/copyright/profiles_settings.xml b/3rdweek/TestServer/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..e7bedf3 --- /dev/null +++ b/3rdweek/TestServer/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/3rdweek/TestServer/.idea/misc.xml b/3rdweek/TestServer/.idea/misc.xml new file mode 100644 index 0000000..8d8dc8d --- /dev/null +++ b/3rdweek/TestServer/.idea/misc.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + 1.8 + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/.idea/modules.xml b/3rdweek/TestServer/.idea/modules.xml new file mode 100644 index 0000000..7047862 --- /dev/null +++ b/3rdweek/TestServer/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/.idea/workspace.xml b/3rdweek/TestServer/.idea/workspace.xml new file mode 100644 index 0000000..fff34dc --- /dev/null +++ b/3rdweek/TestServer/.idea/workspace.xml @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + DEFINITION_ORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1477051260616 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/.project b/3rdweek/TestServer/.project new file mode 100755 index 0000000..0ab11f4 --- /dev/null +++ b/3rdweek/TestServer/.project @@ -0,0 +1,41 @@ + + + TestServer + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/3rdweek/TestServer/.settings/.jsdtscope b/3rdweek/TestServer/.settings/.jsdtscope new file mode 100755 index 0000000..2fc9dba --- /dev/null +++ b/3rdweek/TestServer/.settings/.jsdtscope @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/3rdweek/TestServer/.settings/org.eclipse.jdt.core.prefs b/3rdweek/TestServer/.settings/org.eclipse.jdt.core.prefs new file mode 100755 index 0000000..c537b63 --- /dev/null +++ b/3rdweek/TestServer/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/3rdweek/TestServer/.settings/org.eclipse.wst.common.component b/3rdweek/TestServer/.settings/org.eclipse.wst.common.component new file mode 100755 index 0000000..d4bf8c2 --- /dev/null +++ b/3rdweek/TestServer/.settings/org.eclipse.wst.common.component @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/3rdweek/TestServer/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml b/3rdweek/TestServer/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml new file mode 100755 index 0000000..2c3fdd1 --- /dev/null +++ b/3rdweek/TestServer/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/3rdweek/TestServer/.settings/org.eclipse.wst.common.project.facet.core.xml b/3rdweek/TestServer/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100755 index 0000000..92a5a99 --- /dev/null +++ b/3rdweek/TestServer/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/3rdweek/TestServer/.settings/org.eclipse.wst.jsdt.ui.superType.container b/3rdweek/TestServer/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100755 index 0000000..3bd5d0a --- /dev/null +++ b/3rdweek/TestServer/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/3rdweek/TestServer/.settings/org.eclipse.wst.jsdt.ui.superType.name b/3rdweek/TestServer/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100755 index 0000000..05bd71b --- /dev/null +++ b/3rdweek/TestServer/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/3rdweek/TestServer/.tern-project b/3rdweek/TestServer/.tern-project new file mode 100755 index 0000000..b71c685 --- /dev/null +++ b/3rdweek/TestServer/.tern-project @@ -0,0 +1 @@ +{"ide":{},"libs":["ecma5","browser"],"plugins":{"guess-types":{}}} \ No newline at end of file diff --git a/3rdweek/TestServer/TestServer.iml b/3rdweek/TestServer/TestServer.iml new file mode 100644 index 0000000..5b6bd4c --- /dev/null +++ b/3rdweek/TestServer/TestServer.iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/WebRoot/.DS_Store b/3rdweek/TestServer/WebRoot/.DS_Store new file mode 100644 index 0000000..5227386 Binary files /dev/null and b/3rdweek/TestServer/WebRoot/.DS_Store differ diff --git a/3rdweek/TestServer/WebRoot/META-INF/MANIFEST.MF b/3rdweek/TestServer/WebRoot/META-INF/MANIFEST.MF new file mode 100755 index 0000000..254272e --- /dev/null +++ b/3rdweek/TestServer/WebRoot/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/Constants.class b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/Constants.class new file mode 100755 index 0000000..9712c03 Binary files /dev/null and b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/Constants.class differ diff --git a/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/HttpServer1.class b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/HttpServer1.class new file mode 100755 index 0000000..44db5d3 Binary files /dev/null and b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/HttpServer1.class differ diff --git a/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/LoginServlet.class b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/LoginServlet.class new file mode 100755 index 0000000..5dc2eff Binary files /dev/null and b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/LoginServlet.class differ diff --git a/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/Request.class b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/Request.class new file mode 100755 index 0000000..953f818 Binary files /dev/null and b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/Request.class differ diff --git a/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/Response.class b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/Response.class new file mode 100755 index 0000000..1604611 Binary files /dev/null and b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/Response.class differ diff --git a/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/ServletProcessor1.class b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/ServletProcessor1.class new file mode 100755 index 0000000..2fb030d Binary files /dev/null and b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/ServletProcessor1.class differ diff --git a/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/StaticResourceProcessor.class b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/StaticResourceProcessor.class new file mode 100755 index 0000000..918158a Binary files /dev/null and b/3rdweek/TestServer/WebRoot/WEB-INF/classes/com/dyd/test/StaticResourceProcessor.class differ diff --git a/3rdweek/TestServer/WebRoot/WEB-INF/web.xml b/3rdweek/TestServer/WebRoot/WEB-INF/web.xml new file mode 100755 index 0000000..2144564 --- /dev/null +++ b/3rdweek/TestServer/WebRoot/WEB-INF/web.xml @@ -0,0 +1,25 @@ + + + TestServer + + JAX-RS Tools Generated - Do not modify + JAX-RS Servlet + com.sun.jersey.spi.container.servlet.ServletContainer + 1 + + + JAX-RS Servlet + /jaxrs/* + + + + LoginServlet + + com.dyd.test.LoginServlet + + + LoginServlet + + /TestServer/LoginServlet + + \ No newline at end of file diff --git a/3rdweek/TestServer/WebRoot/index.jsp b/3rdweek/TestServer/WebRoot/index.jsp new file mode 100755 index 0000000..0866042 --- /dev/null +++ b/3rdweek/TestServer/WebRoot/index.jsp @@ -0,0 +1,26 @@ +<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> +<% +String path = request.getContextPath(); +String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; +%> + + + + + + + My JSP 'index.jsp' starting page + + + + + + + + + + This is my JSP page.
+ + diff --git a/3rdweek/TestServer/src/.DS_Store b/3rdweek/TestServer/src/.DS_Store new file mode 100644 index 0000000..0a8bc21 Binary files /dev/null and b/3rdweek/TestServer/src/.DS_Store differ diff --git a/3rdweek/TestServer/src/.idea/compiler.xml b/3rdweek/TestServer/src/.idea/compiler.xml new file mode 100644 index 0000000..96cc43e --- /dev/null +++ b/3rdweek/TestServer/src/.idea/compiler.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/src/.idea/copyright/profiles_settings.xml b/3rdweek/TestServer/src/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..e7bedf3 --- /dev/null +++ b/3rdweek/TestServer/src/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/3rdweek/TestServer/src/.idea/misc.xml b/3rdweek/TestServer/src/.idea/misc.xml new file mode 100644 index 0000000..880e17b --- /dev/null +++ b/3rdweek/TestServer/src/.idea/misc.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/src/.idea/modules.xml b/3rdweek/TestServer/src/.idea/modules.xml new file mode 100644 index 0000000..f669a0e --- /dev/null +++ b/3rdweek/TestServer/src/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/src/.idea/src.iml b/3rdweek/TestServer/src/.idea/src.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/3rdweek/TestServer/src/.idea/src.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/src/.idea/workspace.xml b/3rdweek/TestServer/src/.idea/workspace.xml new file mode 100644 index 0000000..1cb4535 --- /dev/null +++ b/3rdweek/TestServer/src/.idea/workspace.xml @@ -0,0 +1,402 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + DEFINITION_ORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1477041583000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/3rdweek/TestServer/src/com/.DS_Store b/3rdweek/TestServer/src/com/.DS_Store new file mode 100644 index 0000000..6521d00 Binary files /dev/null and b/3rdweek/TestServer/src/com/.DS_Store differ diff --git a/3rdweek/TestServer/src/com/dyd/.DS_Store b/3rdweek/TestServer/src/com/dyd/.DS_Store new file mode 100644 index 0000000..a2eb533 Binary files /dev/null and b/3rdweek/TestServer/src/com/dyd/.DS_Store differ diff --git a/3rdweek/TestServer/src/com/dyd/test/Constants.java b/3rdweek/TestServer/src/com/dyd/test/Constants.java new file mode 100755 index 0000000..cfd6952 --- /dev/null +++ b/3rdweek/TestServer/src/com/dyd/test/Constants.java @@ -0,0 +1,10 @@ +package com.dyd.test; + +import java.io.File; + +public class Constants { + public static final String WEB_ROOT = System.getProperty("user.dir") + + File.separator + "webroot"; + public static final String WEB_SERVLET_ROOT = System.getProperty("user.dir") + + File.separator + "target" + File.separator + "classes"; +} diff --git a/3rdweek/TestServer/src/com/dyd/test/HttpServer1.java b/3rdweek/TestServer/src/com/dyd/test/HttpServer1.java new file mode 100755 index 0000000..01ad311 --- /dev/null +++ b/3rdweek/TestServer/src/com/dyd/test/HttpServer1.java @@ -0,0 +1,76 @@ +package com.dyd.test; +import java.net.Socket; +import java.net.ServerSocket; +import java.net.InetAddress; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.IOException; +//import ex02.pyrmont.Request; +//import ex02.pyrmont.Response; +//import ex02.pyrmont.StaticResourceProcessor; + +public class HttpServer1 { + // 关闭服务命令 + private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; + + public static void main(String[] args) { + // TODO Auto-generated method stub + HttpServer1 server = new HttpServer1(); + //等待连接请求 + server.await(); + } + public void await() { + ServerSocket serverSocket = null; + int port = 8080; + try { + //服务器套接字对象 + serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); + } catch (IOException e) { + e.printStackTrace(); + System.exit(1); + } + + // 循环等待请求 + while (true) { + Socket socket = null; + InputStream input = null; + OutputStream output = null; + try { + //等待连接,连接成功后,返回一个Socket对象 + socket = serverSocket.accept(); + input = socket.getInputStream(); + output = socket.getOutputStream(); + + // 创建Request对象并解析 + Request request = new Request(input); + request.parse(); + // 检查是否是关闭服务命令 + if (request.getUri().equals(SHUTDOWN_COMMAND)) { + break; + } + + // 创建 Response 对象 + Response response = new Response(output); + response.setRequest(request); + + if (request.getUri().startsWith("/servlet/")) { + //请求uri以/servlet/开头,表示servlet请求 + ServletProcessor1 processor = new ServletProcessor1(); + processor.process(request, response); + } else { + //静态资源请求 + StaticResourceProcessor processor = new StaticResourceProcessor(); + processor.process(request, response); + } + + // 关闭 socket + socket.close(); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + } + +} diff --git a/3rdweek/TestServer/src/com/dyd/test/LoginServlet.java b/3rdweek/TestServer/src/com/dyd/test/LoginServlet.java new file mode 100755 index 0000000..5bd830e --- /dev/null +++ b/3rdweek/TestServer/src/com/dyd/test/LoginServlet.java @@ -0,0 +1,44 @@ +package com.dyd.test; + +import javax.servlet.*; + +import java.io.IOException; +import java.io.PrintWriter; + +public class LoginServlet implements Servlet{ + + @Override + public void destroy() { + // TODO Auto-generated method stub + System.out.println("destroy"); + } + + @Override + public ServletConfig getServletConfig() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getServletInfo() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void init(ServletConfig arg0) throws ServletException { + // TODO Auto-generated method stub + System.out.println("init"); + } + + @Override + public void service(ServletRequest arg0, ServletResponse arg1) + throws ServletException, IOException { + // TODO Auto-generated method stub + System.out.println("from service"); + PrintWriter out = arg1.getWriter(); + out.println("Hello. Roses are red."); + out.print("Violets are blue."); + } + +} diff --git a/3rdweek/TestServer/src/com/dyd/test/Request.java b/3rdweek/TestServer/src/com/dyd/test/Request.java new file mode 100755 index 0000000..eb0f6e8 --- /dev/null +++ b/3rdweek/TestServer/src/com/dyd/test/Request.java @@ -0,0 +1,289 @@ +package com.dyd.test; + +import java.io.InputStream; +import java.io.IOException; +import java.io.BufferedReader; +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{ + + private InputStream input; + private String uri; + public Request(InputStream input) { + this.input = input; + } + public String getUri() { + return uri; + } + /** + * + * requestString锟斤拷式锟斤拷锟铰o拷 + * GET /index.html HTTP/1.1 + * Host: localhost:8080 + * Connection: keep-alive + * Cache-Control: max-age=0 + * ... + * 锟矫猴拷锟斤拷目锟侥撅拷锟斤拷为锟剿伙拷取/index.html锟街凤拷锟斤拷 + */ + private String parseUri(String requestString) { + int index1, index2; + index1 = requestString.indexOf(' '); + if (index1 != -1) { + index2 = requestString.indexOf(' ', index1 + 1); + if (index2 > index1) + return requestString.substring(index1 + 1, index2); + } + return null; + } + //锟斤拷InputStream锟叫讹拷取request锟斤拷息锟斤拷锟斤拷锟斤拷request锟叫伙拷取uri值 + public void parse() { + // Read a set of characters from the socket + StringBuffer request = new StringBuffer(2048); + int i; + byte[] buffer = new byte[2048]; + try { + i = input.read(buffer); + } catch (IOException e) { + e.printStackTrace(); + i = -1; + } + for (int j = 0; j < i; j++) { + request.append((char) buffer[j]); + } + System.out.print(request.toString()); + uri = parseUri(request.toString()); + } + @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 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 getLocales() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getParameter(String arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map getParameterMap() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Enumeration 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() throws IllegalStateException { + // TODO Auto-generated method stub + return null; + } + + @Override + public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) + throws IllegalStateException { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getContentLengthLong() { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + +} diff --git a/3rdweek/TestServer/src/com/dyd/test/Response.java b/3rdweek/TestServer/src/com/dyd/test/Response.java new file mode 100755 index 0000000..45b42ec --- /dev/null +++ b/3rdweek/TestServer/src/com/dyd/test/Response.java @@ -0,0 +1,151 @@ +package com.dyd.test; + +import java.io.OutputStream; +import java.io.IOException; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.File; +import java.io.PrintWriter; +import java.util.Locale; + +import javax.servlet.ServletResponse; +import javax.servlet.ServletOutputStream; + +public class Response implements ServletResponse{ + private static final int BUFFER_SIZE = 1024; + Request request; + OutputStream output; + PrintWriter writer; + + public Response(OutputStream output) { + this.output = output; + } + + public void setRequest(Request request) { + this.request = request; + } + //锟斤拷web锟侥硷拷写锟诫到OutputStream锟街斤拷锟斤拷锟斤拷 + public void sendStaticResource() throws IOException { + byte[] bytes = new byte[BUFFER_SIZE]; + FileInputStream fis = null; + try { + /* request.getUri has been replaced by request.getRequestURI */ + File file = new File(Constants.WEB_ROOT, request.getUri()); + fis = new FileInputStream(file); + /* + * HTTP Response = Status-Line(( general-header | response-header | + * entity-header ) CRLF) CRLF [ message-body ] Status-Line = + * HTTP-Version SP Status-Code SP Reason-Phrase CRLF + */ + int ch = fis.read(bytes, 0, BUFFER_SIZE); + while (ch != -1) { + output.write(bytes, 0, ch); + ch = fis.read(bytes, 0, BUFFER_SIZE); + } + } catch (FileNotFoundException e) { + String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + + "Content-Type: text/html\r\n" + "Content-Length: 23\r\n" + + "\r\n" + "

File Not Found

"; + output.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 + return null; + } + + @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 + + } + + @Override + public void setContentLengthLong(long l) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + +} diff --git a/3rdweek/TestServer/src/com/dyd/test/ServletProcessor1.java b/3rdweek/TestServer/src/com/dyd/test/ServletProcessor1.java new file mode 100755 index 0000000..86113b6 --- /dev/null +++ b/3rdweek/TestServer/src/com/dyd/test/ServletProcessor1.java @@ -0,0 +1,48 @@ +package com.dyd.test; + +import java.net.URL; +import java.net.URLClassLoader; +import java.net.URLStreamHandler; +import java.io.IOException; +import javax.servlet.Servlet; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +public class ServletProcessor1 { + public void process(Request request, Response response) { + String uri = request.getUri(); + String servletName = uri.substring(uri.lastIndexOf("/") + 1); + + //类加载器,用于从指定JAR文件或目录加载类 + URLClassLoader loader = null; + try { + URLStreamHandler streamHandler = null; + //创建类加载器 + loader = new URLClassLoader(new URL[]{new URL(null, "file:" + Constants.WEB_SERVLET_ROOT, streamHandler)}); + } catch (IOException e) { + System.out.println(e.toString()); + } + + Class myClass = null; + try { + //加载对应的servlet类 + myClass = loader.loadClass(servletName); + } catch (ClassNotFoundException e) { + System.out.println(e.toString()); + } + + Servlet servlet = null; + + try { + //生产servlet实例 + servlet = (Servlet) myClass.newInstance(); + //执行ervlet的service方法 + servlet.service((ServletRequest) request,(ServletResponse) response); + } catch (Exception e) { + System.out.println(e.toString()); + } catch (Throwable e) { + System.out.println(e.toString()); + } + + } +} diff --git a/3rdweek/TestServer/src/com/dyd/test/StaticResourceProcessor.java b/3rdweek/TestServer/src/com/dyd/test/StaticResourceProcessor.java new file mode 100755 index 0000000..e1efbf6 --- /dev/null +++ b/3rdweek/TestServer/src/com/dyd/test/StaticResourceProcessor.java @@ -0,0 +1,13 @@ +package com.dyd.test; + +import java.io.IOException; +public class StaticResourceProcessor { + public void process(Request request, Response response) { + try { + response.sendStaticResource(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/4thweek/bin/jsp/Constants.class b/4thweek/bin/jsp/Constants.class new file mode 100755 index 0000000..06d2187 Binary files /dev/null and b/4thweek/bin/jsp/Constants.class differ diff --git a/4thweek/bin/jsp/HttpServer.class b/4thweek/bin/jsp/HttpServer.class new file mode 100755 index 0000000..2bb9977 Binary files /dev/null and b/4thweek/bin/jsp/HttpServer.class differ diff --git a/4thweek/bin/jsp/Request.class b/4thweek/bin/jsp/Request.class new file mode 100755 index 0000000..a7b708c Binary files /dev/null and b/4thweek/bin/jsp/Request.class differ diff --git a/4thweek/bin/jsp/Response.class b/4thweek/bin/jsp/Response.class new file mode 100755 index 0000000..86fc347 Binary files /dev/null and b/4thweek/bin/jsp/Response.class differ diff --git a/4thweek/bin/jsp/ServletProcessor.class b/4thweek/bin/jsp/ServletProcessor.class new file mode 100755 index 0000000..09b6cde Binary files /dev/null and b/4thweek/bin/jsp/ServletProcessor.class differ diff --git a/4thweek/bin/jsp/StaticResourceProcessor.class b/4thweek/bin/jsp/StaticResourceProcessor.class new file mode 100755 index 0000000..c72073d Binary files /dev/null and b/4thweek/bin/jsp/StaticResourceProcessor.class differ diff --git a/4thweek/bin/jsp/jspReader.class b/4thweek/bin/jsp/jspReader.class new file mode 100755 index 0000000..52b18fc Binary files /dev/null and b/4thweek/bin/jsp/jspReader.class differ diff --git a/4thweek/part/part_1.txt b/4thweek/part/part_1.txt new file mode 100755 index 0000000..8c73e95 --- /dev/null +++ b/4thweek/part/part_1.txt @@ -0,0 +1,11 @@ +import java.io.IOException; +import java.io.PrintWriter; +import javax.servlet.Servlet; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import java.text.*; +import java.util.*; + +public class \ No newline at end of file diff --git a/4thweek/part/part_2.txt b/4thweek/part/part_2.txt new file mode 100755 index 0000000..28956d9 --- /dev/null +++ b/4thweek/part/part_2.txt @@ -0,0 +1,5 @@ +implements Servlet { + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { + PrintWriter out = response.getWriter(); + out.println("HTTP/1.1 200 OK\r\n"); + out.println(" \ No newline at end of file diff --git a/4thweek/part/part_3.txt b/4thweek/part/part_3.txt new file mode 100755 index 0000000..45b84d9 --- /dev/null +++ b/4thweek/part/part_3.txt @@ -0,0 +1,25 @@ + "); +} + + + public void destroy() { + + } + + + public ServletConfig getServletConfig() { + + return null; + } + + + public String getServletInfo() { + + return null; + } + + + public void init(ServletConfig arg0) throws ServletException { + + } +} \ No newline at end of file diff --git a/4thweek/part/part_4.txt b/4thweek/part/part_4.txt new file mode 100755 index 0000000..e85bd9f --- /dev/null +++ b/4thweek/part/part_4.txt @@ -0,0 +1,7 @@ +"); +out.println(" +out.println( +// +" +File.separator +File.separator +" +" +\" diff --git a/4thweek/src/jsp/Constants.java b/4thweek/src/jsp/Constants.java new file mode 100755 index 0000000..9a1c72b --- /dev/null +++ b/4thweek/src/jsp/Constants.java @@ -0,0 +1,11 @@ +package jsp; + +import java.io.File; + +public class Constants { + public static final String WEB_ROOT = System.getProperty("user.dir") + + File.separator; + public static final String WEB_SERVLET_ROOT = System.getProperty("user.dir") + + File.separator + "target" + File.separator + "classes"; + +} diff --git a/4thweek/src/jsp/HttpServer.java b/4thweek/src/jsp/HttpServer.java new file mode 100755 index 0000000..7d0639c --- /dev/null +++ b/4thweek/src/jsp/HttpServer.java @@ -0,0 +1,254 @@ +package jsp; + +import java.net.Socket; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import jsp.Request; +import jsp.Response; +import jsp.jspReader; + +import java.net.ServerSocket; +import java.net.InetAddress; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.File; +import java.io.IOException; + +public class HttpServer { + + // 关闭服务命令 + private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; + + public static void main(String[] args) { + HttpServer server = new HttpServer(); + // 等待连接请求 + server.await(); + } + + public void await() { + ServerSocket serverSocket = null; + int port = 8080; + try { + // 服务器套接字对象 + serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); + } catch (IOException e) { + e.printStackTrace(); + System.exit(1); + } + + // 循环等待请求 + while (true) { + Socket socket = null; + InputStream input = null; + OutputStream output = null; + try { + // 等待连接,连接成功后,返回一个Socket对象 + socket = serverSocket.accept(); + input = socket.getInputStream(); + output = socket.getOutputStream(); + + // 创建Request对象并解析 + Request request = new Request(input); + request.parse(); + + // 创建 Response 对象 + Response response = new Response(output); + response.setRequest(request); + + // 取到url + String url = request.getUri(); + + // 解析xml + /* + * Boolean canRead = findurl(url); + * + * if(canRead) { + * //解析xml得到类名 + * String servletName = getServeletName(url); + * ServletProcessor processor = new ServletProcessor(); + * processor.process(request,response,servletName); + * } + * else { + * StaticResourceProcessor + * processor = new StaticResourceProcessor(); + * processor.process(request, response); } + */ + String filename = System.getProperty("user.dir")+ File.separator +"jsp" + File.separator + url; + if(new File(filename).exists()) + { + // 转换jsp + jspReader jsp = new jspReader(url.split("/")[1]); + ServletProcessor processor = new ServletProcessor(); + processor.process(request,response,jsp.getServletName()); + } + else + { + System.out.println("找不到该文件!"); + } + + + // 关闭 socket + socket.close(); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + } + + public Boolean findurl(String url) { + Element element = null; + // 可以使用绝对路径 + File f = new File("web.xml"); + + DocumentBuilder db = null; + DocumentBuilderFactory dbf = null; + try { + dbf = DocumentBuilderFactory.newInstance(); + db = dbf.newDocumentBuilder(); + Document dt = db.parse(f); + + // 得到一个elment根元素 + element = dt.getDocumentElement(); + + // 获得根元素下的子节点 + NodeList childNodes = element.getChildNodes(); + + NodeList theNodeList = null; + + // 遍历这些子节点 + for (int i = 0; i < childNodes.getLength(); i++) { + // 获得每个对应位置i的结点 + Node node1 = childNodes.item(i); + + // 匹配每一个servelet-mapping里的uri + if ("servlet-mapping".equals(node1.getNodeName())) { + + NodeList nodeDetail = node1.getChildNodes(); + + for (int j = 0; j < nodeDetail.getLength(); j++) { + Node detail = nodeDetail.item(j); + + if ("url-pattern".equals(detail.getNodeName())) { + // 匹配url + if (url.equals(detail.getTextContent()))// 如果匹配到,返回true + return true; + } + + } + } + } + } + + catch (Exception e) { + System.out.println(e.toString()); + } + + return false; + } + + public String getServeletName(String url) { + String ServeletName = null; + + Element element = null; + // 可以使用绝对路径 + File f = new File("web.xml"); + + DocumentBuilder db = null; + DocumentBuilderFactory dbf = null; + try { + dbf = DocumentBuilderFactory.newInstance(); + db = dbf.newDocumentBuilder(); + Document dt = db.parse(f); + + // 得到一个elment根元素 + element = dt.getDocumentElement(); + + // 获得根元素下的子节点 + NodeList childNodes = element.getChildNodes(); + + NodeList theNodeList = null; + + // 遍历这些子节点 + for (int i = 0; i < childNodes.getLength(); i++) { + // 获得每个对应位置i的结点 + Node node1 = childNodes.item(i); + + // 匹配每一个servelet-mapping里的uri + if ("servlet-mapping".equals(node1.getNodeName())) { + + NodeList nodeDetail = node1.getChildNodes(); + + for (int j = 0; j < nodeDetail.getLength(); j++) { + Node detail = nodeDetail.item(j); + + if ("url-pattern".equals(detail.getNodeName())) { + // 匹配url + if (url.equals(detail.getTextContent()))// 如果匹配到,将该节点取出 + theNodeList = nodeDetail; + } + + } + } + } + + String Sname = null; + // 取出名字 + for (int j = 0; j < theNodeList.getLength(); j++) { + Node detail = theNodeList.item(j); + + if ("servlet-name".equals(detail.getNodeName())) // 匹配name + { + Sname = detail.getTextContent(); + } + + } + + NodeList theNodeList1 = null; + + // 再次遍历,匹配对应servelet-class + for (int i = 0; i < childNodes.getLength(); i++) { + // 获得每个对应位置i的结点 + Node node1 = childNodes.item(i); + + // 匹配每一个servelet里的uri + if ("servlet".equals(node1.getNodeName())) { + + NodeList nodeDetail = node1.getChildNodes(); + + for (int j = 0; j < nodeDetail.getLength(); j++) { + Node detail = nodeDetail.item(j); + + if ("servlet-name".equals(detail.getNodeName())) // 匹配url对应名字 + if (Sname.equals(detail.getTextContent()))// 如果匹配到,将该节点取出 + theNodeList1 = nodeDetail; + } + } + } + // 取出serveletname + for (int j = 0; j < theNodeList1.getLength(); j++) { + Node detail = theNodeList1.item(j); + + if ("servlet-class".equals(detail.getNodeName())) // 匹配 + { + ServeletName = detail.getTextContent(); + } + + } + } + + catch (Exception e) { + e.printStackTrace(); + } + + return ServeletName; + } +} diff --git a/4thweek/src/jsp/Request.java b/4thweek/src/jsp/Request.java new file mode 100755 index 0000000..6185a1d --- /dev/null +++ b/4thweek/src/jsp/Request.java @@ -0,0 +1,188 @@ +package jsp; + +import java.io.InputStream; +import java.io.IOException; +import java.io.BufferedReader; +import java.io.UnsupportedEncodingException; +import java.util.Enumeration; +import java.util.Locale; +import java.util.Map; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletRequest; + +public class Request implements ServletRequest { + + private InputStream input; + private String uri; + + public Request(InputStream input) { + this.input = input; + } + + public String getUri() { + return uri; + } + /** + * + * requestString形式如下: + * GET /index.html HTTP/1.1 + * Host: localhost:8080 + * Connection: keep-alive + * Cache-Control: max-age=0 + * ... + * 该函数目的就是为了获取/index.html字符串 + */ + private String parseUri(String requestString) { + int index1, index2; + index1 = requestString.indexOf(' '); + if (index1 != -1) { + index2 = requestString.indexOf(' ', index1 + 1); + if (index2 > index1) + return requestString.substring(index1 + 1, index2); + } + return null; + } + //从InputStream中读取request信息,并从request中获取uri值 + public void parse() { + // Read a set of characters from the socket + StringBuffer request = new StringBuffer(2048); + int i; + byte[] buffer = new byte[2048]; + try { + i = input.read(buffer); + } catch (IOException e) { + e.printStackTrace(); + i = -1; + } + for (int j = 0; j < i; j++) { + request.append((char) buffer[j]); + } + System.out.print(request.toString()); + uri = parseUri(request.toString()); + } + + /* implementation of the ServletRequest */ + public Object getAttribute(String attribute) { + return null; + } + + public Enumeration getAttributeNames() { + return null; + } + + public String getRealPath(String path) { + return null; + } + + public RequestDispatcher getRequestDispatcher(String path) { + return null; + } + + public boolean isSecure() { + return false; + } + + public String getCharacterEncoding() { + return null; + } + + public int getContentLength() { + return 0; + } + + public String getContentType() { + return null; + } + + public ServletInputStream getInputStream() throws IOException { + return null; + } + + public Locale getLocale() { + return null; + } + + public Enumeration getLocales() { + return null; + } + + public String getParameter(String name) { + return null; + } + + public Map getParameterMap() { + return null; + } + + public Enumeration getParameterNames() { + return null; + } + + public String[] getParameterValues(String parameter) { + return null; + } + + public String getProtocol() { + return null; + } + + public BufferedReader getReader() throws IOException { + return null; + } + + public String getRemoteAddr() { + return null; + } + + public String getRemoteHost() { + return null; + } + + public String getScheme() { + return null; + } + + public String getServerName() { + return null; + } + + public int getServerPort() { + return 0; + } + + public void removeAttribute(String attribute) { + } + + public void setAttribute(String key, Object value) { + } + + public void setCharacterEncoding(String encoding) + throws UnsupportedEncodingException { + } + +@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 int getRemotePort() { + // TODO Auto-generated method stub + return 0; +} + +} diff --git a/4thweek/src/jsp/Response.java b/4thweek/src/jsp/Response.java new file mode 100755 index 0000000..eb6bd12 --- /dev/null +++ b/4thweek/src/jsp/Response.java @@ -0,0 +1,115 @@ +package jsp; + +import java.io.OutputStream; +import java.io.IOException; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.File; +import java.io.PrintWriter; +import java.util.Locale; +import javax.servlet.ServletResponse; +import javax.servlet.ServletOutputStream; + +public class Response implements ServletResponse { + + private static final int BUFFER_SIZE = 1024; + Request request; + OutputStream output; + PrintWriter writer; + + public Response(OutputStream output) { + this.output = output; + } + + public void setRequest(Request request) { + this.request = request; + } + + //将web文件写入到OutputStream字节流中 +//将web文件写入到OutputStream字节流中 +public void sendStaticResource() throws IOException { +byte[] bytes = new byte[BUFFER_SIZE]; +FileInputStream fis = null; +try { +/* request.getUri has been replaced by request.getRequestURI */ +File file = new File(Constants.WEB_ROOT, request.getUri()); +fis = new FileInputStream(file); +/* +* HTTP Response = Status-Line(( general-header | response-header | +* entity-header ) CRLF) CRLF [ message-body ] Status-Line = +* HTTP-Version SP Status-Code SP Reason-Phrase CRLF +*/ +int ch = fis.read(bytes, 0, BUFFER_SIZE); +while (ch != -1) { +output.write(bytes, 0, ch); +ch = fis.read(bytes, 0, BUFFER_SIZE); +} +} catch (FileNotFoundException e) { +String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + + "Content-Type: text/html\r\n" + "Content-Length: 23\r\n" + + "\r\n" + "

File Not Found

"; +output.write(errorMessage.getBytes()); +} finally { +if (fis != null) +fis.close(); +} +} + + + /** implementation of ServletResponse */ + public void flushBuffer() throws IOException { + } + + public int getBufferSize() { + return 0; + } + + public String getCharacterEncoding() { + return null; + } + + public Locale getLocale() { + return null; + } + + public ServletOutputStream getOutputStream() throws IOException { + return null; + } + + public PrintWriter getWriter() throws IOException { + // autoflush is true, println() will flush, + // but print() will not. + writer = new PrintWriter(output, true); + return writer; + } + + public boolean isCommitted() { + return false; + } + + public void reset() { + } + + public void resetBuffer() { + } + + public void setBufferSize(int size) { + } + + public void setContentLength(int length) { + } + + public void setContentType(String type) { + } + + public void setLocale(Locale locale) { + } + +public String getContentType() { + return null; +} + +public void setCharacterEncoding(String arg0) { +} + +} diff --git a/4thweek/src/jsp/ServletProcessor.java b/4thweek/src/jsp/ServletProcessor.java new file mode 100755 index 0000000..7dc2ae2 --- /dev/null +++ b/4thweek/src/jsp/ServletProcessor.java @@ -0,0 +1,56 @@ +package jsp; + +import java.net.URL; +import java.net.URLClassLoader; +import java.net.URLStreamHandler; +import java.io.File; +import java.io.IOException; + +import javax.servlet.Servlet; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import jsp.Request; +import jsp.Response; + +public class ServletProcessor { + + public void process(Request request, Response response,String servletName) { + + //类加载器,用于从指定JAR文件或目录加载类 + URLClassLoader loader = null; + try { + URLStreamHandler streamHandler = null; + //创建类加载器 + System.out.println(System.getProperty("user.dir")+ File.separator+ "work" + File.separator); + loader = new URLClassLoader(new URL[]{new URL(null, "file:" + + System.getProperty("user.dir")+ File.separator+ "work" + File.separator, + streamHandler)}); + } catch (IOException e) { + System.out.println(e.toString()); + } + + Class myClass = null; + try { + //加载对应的servlet类 + myClass = loader.loadClass(servletName); + } catch (ClassNotFoundException e) { + System.out.println(e.toString()); + } + + Servlet servlet = null; + + try { + //生产servlet实例 + servlet = (Servlet) myClass.newInstance(); + //执行ervlet的service方法 + servlet.service((ServletRequest) request,(ServletResponse) response); + } catch (Exception e) { + System.out.println(e.toString()); + } catch (Throwable e) { + System.out.println(e.toString()); + } + + } + +} diff --git a/4thweek/src/jsp/StaticResourceProcessor.java b/4thweek/src/jsp/StaticResourceProcessor.java new file mode 100755 index 0000000..894e6ef --- /dev/null +++ b/4thweek/src/jsp/StaticResourceProcessor.java @@ -0,0 +1,15 @@ +package jsp; + +import java.io.IOException; + +public class StaticResourceProcessor { + + public void process(Request request, Response response) { + try { + response.sendStaticResource(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} + \ No newline at end of file diff --git a/4thweek/src/jsp/aa.java b/4thweek/src/jsp/aa.java new file mode 100755 index 0000000..e69de29 diff --git a/4thweek/src/jsp/jspReader.java b/4thweek/src/jsp/jspReader.java new file mode 100755 index 0000000..ca211c8 --- /dev/null +++ b/4thweek/src/jsp/jspReader.java @@ -0,0 +1,193 @@ +package jsp; + +import java.io.*; +import java.net.URLClassLoader; +import java.util.Arrays; + +import javax.tools.*; + +public class jspReader { + + private String jspName; + private String jspContent = null; + private String ServeletContent = null; + + public jspReader(String uri) { + jspName = uri; + Read(); + makeServlet(); + } + + public void init() { + + } + + public void Read() { + File f = new File(System.getProperty("user.dir") + File.separator + "jsp" + File.separator + jspName); + + BufferedReader br; + + try { + br = new BufferedReader(new FileReader(f)); + + String line = br.readLine(); + + if(line.contains("<%@")) + { + line = "<% response.setContentType(\"text/html; charset=gb2312\");%>"; + line = line.replace("\"", "&&&&"); + } + + jspContent = line; + + while ((line = br.readLine()) != null) { + + if(line.contains("<%=")) + { + line = line.replace("<%=", "$$out.println("); + line = line.replace("%>", ");&&"); + line = line.replace("\"", "&&&&"); + } + + jspContent = jspContent + " " + line; + } + + br.close(); + // System.out.println(jspContent); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println(jspContent); + } + + public void makeServlet() { + // 读取4个文件 + File f1 = new File(System.getProperty("user.dir") + File.separator + "part" + File.separator + "part_1.txt"); + File f2 = new File(System.getProperty("user.dir") + File.separator + "part" + File.separator + "part_2.txt"); + File f3 = new File(System.getProperty("user.dir") + File.separator + "part" + File.separator + "part_3.txt"); + File f4 = new File(System.getProperty("user.dir") + File.separator + "part" + File.separator + "part_4.txt"); + + BufferedReader br1, br2, br3, br4; + + try { + // 读part4 + br4 = new BufferedReader(new FileReader(f4)); + + String line = null; + + String[] sign = new String[7]; + + sign[0] = br4.readLine(); + sign[1] = "\n" + br4.readLine() ; + sign[2] = sign[0] + br4.readLine(); + sign[3] = br4.readLine(); + sign[4] = br4.readLine(); + sign[5] = br4.readLine(); + sign[6] = br4.readLine(); + + br4.close(); + // + // 替换 + // String ServeletContent1 = jspContent.replace(sign[5], sign[6]); + String ServeletContent1 = jspContent.replace("$$out.println(", sign[2]); + ServeletContent1 = ServeletContent1.replace(");&&",");" + sign[1] ); + ServeletContent1 = ServeletContent1.replace("<%", sign[0]); + ServeletContent1 = ServeletContent1.replace("%>", sign[1]); + ServeletContent1 = ServeletContent1.replace("&&&&", sign[5]); + + + // import-class + br1 = new BufferedReader(new FileReader(f1)); + + line = null; + + ServeletContent = br1.readLine(); + + while ((line = br1.readLine()) != null) { + + ServeletContent = ServeletContent + "\n" + line; + } + + br1.close(); + // + + ServeletContent = ServeletContent + "\n" + jspName.split(".jsp")[0] + "Servlet\n"; + // System.out.println(jspName.split(".jsp")[0]); + + // 读part2 + br2 = new BufferedReader(new FileReader(f2)); + + line = null; + + ServeletContent = ServeletContent + br2.readLine(); + + while ((line = br2.readLine()) != null) { + + ServeletContent = ServeletContent + "\n" + line; + } + + br2.close(); + // + ServeletContent = ServeletContent + ServeletContent1; + // part3 + br3 = new BufferedReader(new FileReader(f3)); + + line = null; + + ServeletContent = ServeletContent + br3.readLine(); + + while ((line = br3.readLine()) != null) { + + ServeletContent = ServeletContent + "\n" + line; + } + + br3.close(); + // + + + + // System.out.println(ServeletContent); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // 创建java + File f = new File(System.getProperty("user.dir") + File.separator + "work" + File.separator + + jspName.split(".jsp")[0] + "Servlet.java"); + try { + if (!f.exists()) { + f.createNewFile(); + } + FileWriter fw = new FileWriter(f); + + fw.write(ServeletContent); + + fw.close(); + + String dir = System.getProperty("user.dir") + File.separator+ "work"; + String filename = jspName.split(".jsp")[0] + "Servlet.java"; + + // 获得系统编译器 + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + + StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); + // 读入源文件 + Iterable fileObject = fileManager.getJavaFileObjects(new File(dir,filename)); + // 编译 + JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, Arrays.asList("-d", "./work"), + null, fileObject); + task.call(); + + fileManager.close(); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + public String getServletName() + { + return jspName.split(".jsp")[0] + "Servlet"; + } +} diff --git a/README.md b/README.md index 4fa3a86..f2d6eac 100644 --- a/README.md +++ b/README.md @@ -7,3 +7,14 @@   Multi-User using supported by Multi-Thread銆 Multi-Process will be updated later銆 +  <[1stweek/1430156.py](https://github.com/Gusting/JavaEE-Homework/blob/master/1stweek/14301056.py)> The last committed file is to submit. + +> 2ndweek + +  Simulate WSGI-Server
+ +  ```python server.py app.app 3333``` + +>14301056 + +  The Folder for Update-Homework. \ No newline at end of file