how2j.cn

-->
下载区
文件名 文件大小
请先登录 11m
增值内容 11m
11m
请先登录 699k
增值内容 699k
699k

解压rar如果失败,请用5.21版本或者更高版本的winrar

点击下载 winrar5.21

5分55秒
本视频采用html5方式播放,如无法正常播放,请将浏览器升级至最新版本,推荐火狐,chrome,360浏览器。 如果装有迅雷,播放视频呈现直接下载状态,请调整 迅雷系统设置-基本设置-启动-监视全部浏览器 (去掉这个选项)。 chrome 的 视频下载插件会影响播放,如 IDM 等,请关闭或者切换其他浏览器

步骤 1 : 拓扑图点亮   
步骤 2 : 客户端跳转   
步骤 3 : Response   
步骤 4 : InvokeServlet   
步骤 5 : JspServlet   
步骤 6 : Constant   
步骤 7 : HttpProcessor   
步骤 8 : ClientJumpServlet   
步骤 9 : web.xml   
步骤 10 : jump1.jsp   
步骤 11 : TestTomcat   
步骤 12 : 比较可运行项目,快速定位问题   

增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
拓扑图点亮
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.http; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import javax.servlet.http.Cookie; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; public class Response extends BaseResponse { private StringWriter stringWriter; private PrintWriter writer; private String contentType; private byte[] body; private int status; private List<Cookie> cookies; private String redirectPath; public Response(){ this.stringWriter = new StringWriter(); this.writer = new PrintWriter(stringWriter); this.contentType = "text/html"; this.cookies = new ArrayList<>(); } public String getRedirectPath() { return this.redirectPath; } public void sendRedirect(String redirect) throws IOException { this.redirectPath = redirect; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public PrintWriter getWriter() { return writer; } public byte[] getBody() throws UnsupportedEncodingException { if(null==body) { String content = stringWriter.toString(); body = content.getBytes("utf-8"); } return body; } public void setBody(byte[] body) { this.body = body; } @Override public void setStatus(int status) { this.status = status; } @Override public int getStatus() { return status; } public void addCookie(Cookie cookie) { cookies.add(cookie); } public List<Cookie> getCookies() { return this.cookies; } public String getCookiesHeader() { if(null==cookies) return ""; String pattern = "EEE, d MMM yyyy HH:mm:ss 'GMT'"; SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.ENGLISH); StringBuffer sb = new StringBuffer(); for (Cookie cookie : getCookies()) { sb.append("\r\n"); sb.append("Set-Cookie: "); sb.append(cookie.getName() + "=" + cookie.getValue() + "; "); if (-1 != cookie.getMaxAge()) { //-1 mean forever sb.append("Expires="); Date now = new Date(); Date expire = DateUtil.offset(now, DateField.MINUTE, cookie.getMaxAge()); sb.append(sdf.format(expire)); sb.append("; "); } if (null != cookie.getPath()) { sb.append("Path=" + cookie.getPath()); } } return sb.toString(); } }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.servlets; import cn.how2j.diytomcat.catalina.Context; import cn.how2j.diytomcat.http.Request; import cn.how2j.diytomcat.http.Response; import cn.how2j.diytomcat.util.Constant; import cn.hutool.core.util.ReflectUtil; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class InvokerServlet extends HttpServlet { private static InvokerServlet instance = new InvokerServlet(); public static synchronized InvokerServlet getInstance() { return instance; } private InvokerServlet() { } public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { Request request = (Request) httpServletRequest; Response response = (Response) httpServletResponse; String uri = request.getUri(); Context context = request.getContext(); String servletClassName = context.getServletClassName(uri); try { Class servletClass = context.getWebappClassLoader().loadClass(servletClassName); Object servletObject = context.getServlet(servletClass); ReflectUtil.invoke(servletObject, "service", request, response); if(null!=response.getRedirectPath()) response.setStatus(Constant.CODE_302); else response.setStatus(Constant.CODE_200); } catch (Exception e) { throw new RuntimeException(e); } } }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.servlets; import cn.how2j.diytomcat.catalina.Context; import cn.how2j.diytomcat.classloader.JspClassLoader; import cn.how2j.diytomcat.http.Request; import cn.how2j.diytomcat.http.Response; import cn.how2j.diytomcat.util.Constant; import cn.how2j.diytomcat.util.JspUtil; import cn.how2j.diytomcat.util.WebXMLUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; public class JspServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static JspServlet instance = new JspServlet(); public static synchronized JspServlet getInstance() { return instance; } private JspServlet() { } public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { try { Request request = (Request) httpServletRequest; Response response = (Response) httpServletResponse; String uri = request.getRequestURI(); if ("/".equals(uri)) uri = WebXMLUtil.getWelcomeFile(request.getContext()); String fileName = StrUtil.removePrefix(uri, "/"); File file = FileUtil.file(request.getRealPath(fileName)); File jspFile = file; if (jspFile.exists()) { Context context = request.getContext(); String path = context.getPath(); String subFolder; if ("/".equals(path)) subFolder = "_"; else subFolder = StrUtil.subAfter(path, '/', false); String servletClassPath = JspUtil.getServletClassPath(uri, subFolder); File jspServletClassFile = new File(servletClassPath); if (!jspServletClassFile.exists()) { JspUtil.compileJsp(context, jspFile); } else if (jspFile.lastModified() > jspServletClassFile.lastModified()) { JspUtil.compileJsp(context, jspFile); JspClassLoader.invalidJspClassLoader(uri, context); } String extName = FileUtil.extName(file); String mimeType = WebXMLUtil.getMimeType(extName); response.setContentType(mimeType); JspClassLoader jspClassLoader = JspClassLoader.getJspClassLoader(uri, context); String jspServletClassName = JspUtil.getJspServletClassName(uri, subFolder); Class jspServletClass = jspClassLoader.loadClass(jspServletClassName); HttpServlet servlet = context.getServlet(jspServletClass); servlet.service(request,response); if(null!=response.getRedirectPath()) response.setStatus(Constant.CODE_302); else response.setStatus(Constant.CODE_200); } else { response.setStatus(Constant.CODE_404); } } catch (Exception e) { throw new RuntimeException(e); } } }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.util; import cn.hutool.system.SystemUtil; import java.io.File; public class Constant { public static final int CODE_200 = 200; public static final int CODE_302 = 302; public static final int CODE_404 = 404; public static final int CODE_500 = 500; public static final String response_head_200 = "HTTP/1.1 200 OK\r\n" + "Content-Type: {}{}" + "\r\n\r\n"; public static final String response_head_200_gzip = "HTTP/1.1 200 OK\r\nContent-Type: {}{}\r\n" + "Content-Encoding:gzip" + "\r\n\r\n"; public static final String response_head_302 = "HTTP/1.1 302 Found\r\nLocation: {}\r\n\r\n"; public static final String response_head_404 = "HTTP/1.1 404 Not Found\r\n" + "Content-Type: text/html\r\n\r\n"; public static final String response_head_500 = "HTTP/1.1 500 Internal Server Error\r\n" + "Content-Type: text/html\r\n\r\n"; public static final String textFormat_404 = "<html><head><title>DIY Tomcat/1.0.1 - Error report</title><style>" + "<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} " + "H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} " + "H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} " + "BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} " + "B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} " + "P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}" + "A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> " + "</head><body><h1>HTTP Status 404 - {}</h1>" + "<HR size='1' noshade='noshade'><p><b>type</b> Status report</p><p><b>message</b> <u>{}</u></p><p><b>description</b> " + "<u>The requested resource is not available.</u></p><HR size='1' noshade='noshade'><h3>DiyTocmat 1.0.1</h3>" + "</body></html>"; public static final String textFormat_500 = "<html><head><title>DIY Tomcat/1.0.1 - Error report</title><style>" + "<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} " + "H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} " + "H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} " + "BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} " + "B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} " + "P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}" + "A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> " + "</head><body><h1>HTTP Status 500 - An exception occurred processing {}</h1>" + "<HR size='1' noshade='noshade'><p><b>type</b> Exception report</p><p><b>message</b> <u>An exception occurred processing {}</u></p><p><b>description</b> " + "<u>The server encountered an internal error that prevented it from fulfilling this request.</u></p>" + "<p>Stacktrace:</p>" + "<pre>{}</pre>" + "<HR size='1' noshade='noshade'><h3>DiyTocmat 1.0.1</h3>" + "</body></html>"; public final static File webappsFolder = new File(SystemUtil.get("user.dir"),"webapps"); public final static File rootFolder = new File(webappsFolder,"ROOT"); public static final File confFolder = new File(SystemUtil.get("user.dir"),"conf"); public static final File serverXmlFile = new File(confFolder, "server.xml"); public static final File webXmlFile = new File(confFolder, "web.xml"); public static final File contextXmlFile = new File(confFolder, "context.xml"); public static final String workFolder = SystemUtil.get("user.dir") + File.separator + "work"; }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.catalina; import cn.how2j.diytomcat.http.Request; import cn.how2j.diytomcat.http.Response; import cn.how2j.diytomcat.servlets.DefaultServlet; import cn.how2j.diytomcat.servlets.InvokerServlet; import cn.how2j.diytomcat.servlets.JspServlet; import cn.how2j.diytomcat.util.Constant; import cn.how2j.diytomcat.util.SessionManager; import cn.how2j.diytomcat.util.WebXMLUtil; import cn.hutool.core.util.*; import cn.hutool.log.LogFactory; import javax.servlet.Servlet; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; public class HttpProcessor { public void execute(Socket s, Request request, Response response){ try { String uri = request.getUri(); if(null==uri) return; prepareSession(request, response); Context context = request.getContext(); String servletClassName = context.getServletClassName(uri); if(null!=servletClassName) InvokerServlet.getInstance().service(request,response); else if(uri.endsWith(".jsp")) JspServlet.getInstance().service(request,response); else DefaultServlet.getInstance().service(request,response); if(Constant.CODE_200 == response.getStatus()){ handle200(s, request, response); return; } if(Constant.CODE_302 == response.getStatus()){ handle302(s, response); return; } if(Constant.CODE_404 == response.getStatus()){ handle404(s, uri); return; } } catch (Exception e) { LogFactory.get().error(e); handle500(s,e); } finally{ try { if(!s.isClosed()) s.close(); } catch (IOException e) { e.printStackTrace(); } } } private void handle200(Socket s, Request request, Response response) throws IOException { OutputStream os = s.getOutputStream(); String contentType = response.getContentType(); byte[] body = response.getBody(); String cookiesHeader = response.getCookiesHeader(); boolean gzip = isGzip(request, body, contentType); String headText; if (gzip) headText = Constant.response_head_200_gzip; else headText = Constant.response_head_200; headText = StrUtil.format(headText, contentType, cookiesHeader); if (gzip) body = ZipUtil.gzip(body); byte[] head = headText.getBytes(); byte[] responseBytes = new byte[head.length + body.length]; ArrayUtil.copy(head, 0, responseBytes, 0, head.length); ArrayUtil.copy(body, 0, responseBytes, head.length, body.length); os.write(responseBytes,0,responseBytes.length); os.flush(); os.close(); } private void handle404(Socket s, String uri) throws IOException { OutputStream os = s.getOutputStream(); String responseText = StrUtil.format(Constant.textFormat_404, uri, uri); responseText = Constant.response_head_404 + responseText; byte[] responseByte = responseText.getBytes("utf-8"); os.write(responseByte); } private void handle302(Socket s, Response response) throws IOException { OutputStream os = s.getOutputStream(); String redirectPath = response.getRedirectPath(); String head_text = Constant.response_head_302; String header = StrUtil.format(head_text, redirectPath); byte[] responseBytes = header.getBytes("utf-8"); os.write(responseBytes); } private void handle500(Socket s, Exception e) { try { OutputStream os = s.getOutputStream(); StackTraceElement stes[] = e.getStackTrace(); StringBuffer sb = new StringBuffer(); sb.append(e.toString()); sb.append("\r\n"); for (StackTraceElement ste : stes) { sb.append("\t"); sb.append(ste.toString()); sb.append("\r\n"); } String msg = e.getMessage(); if (null != msg && msg.length() > 20) msg = msg.substring(0, 19); String text = StrUtil.format(Constant.textFormat_500, msg, e.toString(), sb.toString()); text = Constant.response_head_500 + text; byte[] responseBytes = text.getBytes("utf-8"); os.write(responseBytes); } catch (IOException e1) { e1.printStackTrace(); } } public void prepareSession(Request request, Response response) { String jsessionid = request.getJSessionIdFromCookie(); HttpSession session = SessionManager.getSession(jsessionid, request, response); request.setSession(session); } private boolean isGzip(Request request, byte[] body, String mimeType) { String acceptEncodings= request.getHeader("Accept-Encoding"); if(!StrUtil.containsAny(acceptEncodings, "gzip")) return false; Connector connector = request.getConnector(); if (mimeType.contains(";")) mimeType = StrUtil.subBefore(mimeType, ";", false); if (!"on".equals(connector.getCompression())) return false; if (body.length < connector.getCompressionMinSize()) return false; String userAgents = connector.getNoCompressionUserAgents(); String[] eachUserAgents = userAgents.split(","); for (String eachUserAgent : eachUserAgents) { eachUserAgent = eachUserAgent.trim(); String userAgent = request.getHeader("User-Agent"); if (StrUtil.containsAny(userAgent, eachUserAgent)) return false; } String mimeTypes = connector.getCompressableMimeType(); String[] eachMimeTypes = mimeTypes.split(","); for (String eachMimeType : eachMimeTypes) { if (mimeType.equals(eachMimeType)) return true; } return false; } }
步骤 8 :

ClientJumpServlet

edit
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.javaweb; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ClientJumpServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendRedirect("hello"); } }
package cn.how2j.javaweb;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ClientJumpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.sendRedirect("hello");
	}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>cn.how2j.javaweb.HelloServlet</servlet-class> <init-param> <param-name>author</param-name> <param-value>how2j(servlet)</param-value> </init-param> <init-param> <param-name>site</param-name> <param-value>http://how2j.cn(servlet)</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>ParamServlet</servlet-name> <servlet-class>cn.how2j.javaweb.ParamServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ParamServlet</servlet-name> <url-pattern>/param</url-pattern> </servlet-mapping> <servlet> <servlet-name>HeaderServlet</servlet-name> <servlet-class>cn.how2j.javaweb.HeaderServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HeaderServlet</servlet-name> <url-pattern>/header</url-pattern> </servlet-mapping> <servlet> <servlet-name>SetCookieServlet</servlet-name> <servlet-class>cn.how2j.javaweb.SetCookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SetCookieServlet</servlet-name> <url-pattern>/setCookie</url-pattern> </servlet-mapping> <servlet> <servlet-name>GetCookieServlet</servlet-name> <servlet-class>cn.how2j.javaweb.GetCookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetCookieServlet</servlet-name> <url-pattern>/getCookie</url-pattern> </servlet-mapping> <servlet> <servlet-name>SetSessionServlet</servlet-name> <servlet-class>cn.how2j.javaweb.SetSessionServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SetSessionServlet</servlet-name> <url-pattern>/setSession</url-pattern> </servlet-mapping> <servlet> <servlet-name>GetSessionServlet</servlet-name> <servlet-class>cn.how2j.javaweb.GetSessionServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetSessionServlet</servlet-name> <url-pattern>/getSession</url-pattern> </servlet-mapping> <servlet> <servlet-name>ClientJumpServlet</servlet-name> <servlet-class>cn.how2j.javaweb.ClientJumpServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ClientJumpServlet</servlet-name> <url-pattern>/jump1</url-pattern> </servlet-mapping> </web-app>
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
<% response.sendRedirect("hello"); %>
<%
    response.sendRedirect("hello");
%>
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.test; import cn.how2j.diytomcat.util.MiniBrowser; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.NetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.ZipUtil; import cn.hutool.http.HttpUtil; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import sun.net.www.content.text.plain; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestTomcat { private static int port = 18080; private static String ip = "127.0.0.1"; @BeforeClass public static void beforeClass() { //所有测试开始前看diy tomcat 是否已经启动了 if(NetUtil.isUsableLocalPort(port)) { System.err.println("请先启动 位于端口: " +port+ " 的diy tomcat,否则无法进行单元测试"); System.exit(1); } else { System.out.println("检测到 diy tomcat已经启动,开始进行单元测试"); } } @Test public void testHelloTomcat() { String html = getContentString("/"); Assert.assertEquals(html,"Hello DIY Tomcat from how2j.cn"); } @Test public void testTimeConsumeHtml() throws InterruptedException { ThreadPoolExecutor threadPool = new ThreadPoolExecutor(20, 20, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10)); TimeInterval timeInterval = DateUtil.timer(); for(int i = 0; i<3; i++){ threadPool.execute(new Runnable(){ public void run() { getContentString("/timeConsume.html"); } }); } threadPool.shutdown(); threadPool.awaitTermination(1, TimeUnit.HOURS); long duration = timeInterval.intervalMs(); Assert.assertTrue(duration < 3000); } @Test public void testaIndex() { String html = getContentString("/a"); Assert.assertEquals(html,"Hello DIY Tomcat from index.html@a"); } @Test public void testbIndex() { String html = getContentString("/b/"); Assert.assertEquals(html,"Hello DIY Tomcat from index.html@b"); } @Test public void test404() { String response = getHttpString("/not_exist.html"); containAssert(response, "HTTP/1.1 404 Not Found"); } @Test public void test500() { String response = getHttpString("/500.html"); containAssert(response, "HTTP/1.1 500 Internal Server Error"); } @Test public void testaTxt() { String response = getHttpString("/a.txt"); containAssert(response, "Content-Type: text/plain"); } @Test public void testPNG() { byte[] bytes = getContentBytes("/logo.png"); int pngFileLength = 1672; Assert.assertEquals(pngFileLength, bytes.length); } @Test public void testPDF() { byte[] bytes = getContentBytes("/etf.pdf"); int pngFileLength = 3590775; Assert.assertEquals(pngFileLength, bytes.length); } @Test public void testhello() { String html = getContentString("/j2ee/hello"); Assert.assertEquals(html,"Hello DIY Tomcat from HelloServlet"); } @Test public void testJavawebHello() { String html = getContentString("/javaweb/hello"); containAssert(html,"Hello DIY Tomcat from HelloServlet@javaweb"); } @Test public void testJavawebHelloSingleton() { String html1 = getContentString("/javaweb/hello"); String html2 = getContentString("/javaweb/hello"); Assert.assertEquals(html1,html2); } @Test public void testgetParam() { String uri = "/javaweb/param"; String url = StrUtil.format("http://{}:{}{}", ip,port,uri); Map<String,Object> params = new HashMap<>(); params.put("name","meepo"); String html = MiniBrowser.getContentString(url, params, true); Assert.assertEquals(html,"get name:meepo"); } @Test public void testpostParam() { String uri = "/javaweb/param"; String url = StrUtil.format("http://{}:{}{}", ip,port,uri); Map<String,Object> params = new HashMap<>(); params.put("name","meepo"); String html = MiniBrowser.getContentString(url, params, false); Assert.assertEquals(html,"post name:meepo"); } @Test public void testheader() { String html = getContentString("/javaweb/header"); Assert.assertEquals(html,"how2j mini brower / java1.8"); } @Test public void testsetCookie() { String http = getHttpString("/javaweb/setCookie"); containAssert(http,"Set-Cookie: name=Gareen(cookie); Expires="); } @Test public void testgetCookie() throws IOException { String url = StrUtil.format("http://{}:{}{}", ip,port,"/javaweb/getCookie"); URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setRequestProperty("Cookie","name=Gareen(cookie)"); conn.connect(); InputStream is = conn.getInputStream(); String html = IoUtil.read(is, "utf-8"); containAssert(html,"name:Gareen(cookie)"); } @Test public void testSession() throws IOException { String jsessionid = getContentString("/javaweb/setSession"); if(null!=jsessionid) jsessionid = jsessionid.trim(); String url = StrUtil.format("http://{}:{}{}", ip,port,"/javaweb/getSession"); URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setRequestProperty("Cookie","JSESSIONID="+jsessionid); conn.connect(); InputStream is = conn.getInputStream(); String html = IoUtil.read(is, "utf-8"); containAssert(html,"Gareen(session)"); } @Test public void testGzip() { byte[] gzipContent = getContentBytes("/",true); byte[] unGzipContent = ZipUtil.unGzip(gzipContent); String html = new String(unGzipContent); Assert.assertEquals(html, "Hello DIY Tomcat from how2j.cn"); } @Test public void testJsp() { String html = getContentString("/javaweb/"); Assert.assertEquals(html, "hello jsp@javaweb"); } @Test public void testClientJump(){ String http_servlet = getHttpString("/javaweb/jump1"); containAssert(http_servlet,"HTTP/1.1 302 Found"); String http_jsp = getHttpString("/javaweb/jump1.jsp"); containAssert(http_jsp,"HTTP/1.1 302 Found"); } private byte[] getContentBytes(String uri) { return getContentBytes(uri,false); } private byte[] getContentBytes(String uri,boolean gzip) { String url = StrUtil.format("http://{}:{}{}", ip,port,uri); return MiniBrowser.getContentBytes(url,gzip); } private String getContentString(String uri) { String url = StrUtil.format("http://{}:{}{}", ip,port,uri); String content = MiniBrowser.getContentString(url); return content; } private String getHttpString(String uri) { String url = StrUtil.format("http://{}:{}{}", ip,port,uri); String http = MiniBrowser.getHttpString(url); return http; } private void containAssert(String html, String string) { boolean match = StrUtil.containsAny(html, string); Assert.assertTrue(match); } }
步骤 12 :

比较可运行项目,快速定位问题

edit
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢


HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。


问答区域    
2022-03-05 这段代码干嘛用的
前进的小胖子




看到它出现很多次了,好像也没用到
private static final long serialVersionUID = 1L;

							


1 个答案

how2j
答案时间:2022-03-13
这是 servlet 的规范,每个servlet类都要事先序列化接口,就必须提供这么一个属性。但是在业务上基本上用不到,可以不用管他。



回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2021-07-02 跳转路径不对
lzh123




问什么我的跳转地址栏会这样
加载中

							

							


1 个答案

how2j
答案时间:2021-07-08
怎么会是大写的H呢



回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2020-08-13 关于跳转的问题




提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
关于 实践项目-DiyTomcat-客户端跳转 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 578362961
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: https://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图