how2j.cn

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

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

点击下载 winrar5.21

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

步骤 1 : 拓扑图点亮   
步骤 2 : servlet   
步骤 3 : HelloServlet   
步骤 4 : Request   
步骤 5 : Response   
步骤 6 : HttpProcessor   
步骤 7 : stringWriter   
步骤 8 : TestTomcat   
步骤 9 : 比较可运行项目,快速定位问题   

增值内容,请先登录
自己写一个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.webappservlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try { response.getWriter().println("Hello DIY Tomcat from HelloServlet"); } catch (IOException e) { e.printStackTrace(); } } }
package cn.how2j.diytomcat.webappservlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        try {
            response.getWriter().println("Hello DIY Tomcat from HelloServlet");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.http; import cn.how2j.diytomcat.Bootstrap; import cn.how2j.diytomcat.catalina.Context; import cn.how2j.diytomcat.catalina.Engine; import cn.how2j.diytomcat.catalina.Host; import cn.how2j.diytomcat.catalina.Service; import cn.how2j.diytomcat.util.MiniBrowser; import cn.hutool.core.util.StrUtil; import javax.servlet.*; import javax.servlet.http.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.security.Principal; import java.util.Collection; import java.util.Enumeration; import java.util.Locale; import java.util.Map; public class Request implements HttpServletRequest{ private String requestString; private String uri; private Socket socket; private Context context; private Service service; public Request(Socket socket, Service service) throws IOException { this.socket = socket; this.service = service; parseHttpRequest(); if(StrUtil.isEmpty(requestString)) return; parseUri(); parseContext(); if(!"/".equals(context.getPath())){ uri = StrUtil.removePrefix(uri, context.getPath()); if(StrUtil.isEmpty(uri)) uri = "/"; } } private void parseContext() { Engine engine = service.getEngine(); context = engine.getDefaultHost().getContext(uri); if(null!=context) return; String path = StrUtil.subBetween(uri, "/", "/"); if (null == path) path = "/"; else path = "/" + path; context = engine.getDefaultHost().getContext(path); if (null == context) context = engine.getDefaultHost().getContext("/"); } private void parseHttpRequest() throws IOException { InputStream is = this.socket.getInputStream(); byte[] bytes = MiniBrowser.readBytes(is,false); requestString = new String(bytes, "utf-8"); } private void parseUri() { String temp; temp = StrUtil.subBetween(requestString, " ", " "); if (!StrUtil.contains(temp, '?')) { uri = temp; return; } temp = StrUtil.subBefore(temp, '?', false); uri = temp; } public Context getContext() { return context; } public String getUri() { return uri; } public String getRequestString(){ return requestString; } @Override public String getAuthType() { return null; } @Override public Cookie[] getCookies() { return new Cookie[0]; } @Override public long getDateHeader(String s) { return 0; } @Override public String getHeader(String s) { return null; } @Override public Enumeration<String> getHeaders(String s) { return null; } @Override public Enumeration<String> getHeaderNames() { return null; } @Override public int getIntHeader(String s) { return 0; } @Override public String getMethod() { return null; } @Override public String getPathInfo() { return null; } @Override public String getPathTranslated() { return null; } @Override public String getContextPath() { return null; } @Override public String getQueryString() { return null; } @Override public String getRemoteUser() { return null; } @Override public boolean isUserInRole(String s) { return false; } @Override public Principal getUserPrincipal() { return null; } @Override public String getRequestedSessionId() { return null; } @Override public String getRequestURI() { return null; } @Override public StringBuffer getRequestURL() { return null; } @Override public String getServletPath() { return null; } @Override public HttpSession getSession(boolean b) { return null; } @Override public HttpSession getSession() { return null; } @Override public boolean isRequestedSessionIdValid() { return false; } @Override public boolean isRequestedSessionIdFromCookie() { return false; } @Override public boolean isRequestedSessionIdFromURL() { return false; } @Override public boolean isRequestedSessionIdFromUrl() { return false; } @Override public boolean authenticate(HttpServletResponse httpServletResponse) throws IOException, ServletException { return false; } @Override public void login(String s, String s1) throws ServletException { } @Override public void logout() throws ServletException { } @Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { return null; } @Override public Part getPart(String s) throws IOException, IllegalStateException, ServletException { return null; } @Override public Object getAttribute(String s) { return null; } @Override public Enumeration<String> getAttributeNames() { return null; } @Override public String getCharacterEncoding() { return null; } @Override public void setCharacterEncoding(String s) throws UnsupportedEncodingException { } @Override public int getContentLength() { return 0; } @Override public String getContentType() { return null; } @Override public ServletInputStream getInputStream() throws IOException { return null; } @Override public String getParameter(String s) { return null; } @Override public Enumeration<String> getParameterNames() { return null; } @Override public String[] getParameterValues(String s) { return new String[0]; } @Override public Map<String, String[]> getParameterMap() { return null; } @Override public String getProtocol() { return null; } @Override public String getScheme() { return null; } @Override public String getServerName() { return null; } @Override public int getServerPort() { return 0; } @Override public BufferedReader getReader() throws IOException { return null; } @Override public String getRemoteAddr() { return null; } @Override public String getRemoteHost() { return null; } @Override public void setAttribute(String s, Object o) { } @Override public void removeAttribute(String s) { } @Override public Locale getLocale() { return null; } @Override public Enumeration<Locale> getLocales() { return null; } @Override public boolean isSecure() { return false; } @Override public RequestDispatcher getRequestDispatcher(String s) { return null; } @Override public String getRealPath(String s) { return null; } @Override public int getRemotePort() { return 0; } @Override public String getLocalName() { return null; } @Override public String getLocalAddr() { return null; } @Override public int getLocalPort() { return 0; } @Override public ServletContext getServletContext() { return null; } @Override public AsyncContext startAsync() { return null; } @Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) { return null; } @Override public boolean isAsyncStarted() { return false; } @Override public boolean isAsyncSupported() { return false; } @Override public AsyncContext getAsyncContext() { return null; } @Override public DispatcherType getDispatcherType() { return null; } }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.http; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.Locale; public class Response implements HttpServletResponse { private StringWriter stringWriter; private PrintWriter writer; private String contentType; private byte[] body; public Response(){ this.stringWriter = new StringWriter(); this.writer = new PrintWriter(stringWriter); this.contentType = "text/html"; } @Override public String getCharacterEncoding() { return null; } public String getContentType() { return contentType; } @Override public ServletOutputStream getOutputStream() throws IOException { return null; } public void setContentType(String contentType) { this.contentType = contentType; } @Override public void setBufferSize(int i) { } @Override public int getBufferSize() { return 0; } @Override public void flushBuffer() throws IOException { } @Override public void resetBuffer() { } @Override public boolean isCommitted() { return false; } @Override public void reset() { } @Override public void setLocale(Locale locale) { } @Override public Locale getLocale() { return null; } public PrintWriter getWriter() { return writer; } @Override public void setCharacterEncoding(String s) { } @Override public void setContentLength(int i) { } 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 addCookie(Cookie cookie) { } @Override public boolean containsHeader(String s) { return false; } @Override public String encodeURL(String s) { return null; } @Override public String encodeRedirectURL(String s) { return null; } @Override public String encodeUrl(String s) { return null; } @Override public String encodeRedirectUrl(String s) { return null; } @Override public void sendError(int i, String s) throws IOException { } @Override public void sendError(int i) throws IOException { } @Override public void sendRedirect(String s) throws IOException { } @Override public void setDateHeader(String s, long l) { } @Override public void addDateHeader(String s, long l) { } @Override public void setHeader(String s, String s1) { } @Override public void addHeader(String s, String s1) { } @Override public void setIntHeader(String s, int i) { } @Override public void addIntHeader(String s, int i) { } @Override public void setStatus(int i) { } @Override public void setStatus(int i, String s) { } @Override public int getStatus() { return 0; } @Override public String getHeader(String s) { return null; } @Override public Collection<String> getHeaders(String s) { return null; } @Override public Collection<String> getHeaderNames() { return null; } }
增值内容,请先登录
自己写一个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.util.Constant; import cn.how2j.diytomcat.util.WebXMLUtil; import cn.how2j.diytomcat.webappservlet.HelloServlet; import cn.hutool.core.io.FileUtil; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.log.LogFactory; import javax.servlet.http.HttpServletRequest; import java.io.File; 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; Context context = request.getContext(); if("/500.html".equals(uri)){ throw new Exception("this is a deliberately created exception"); } if("/hello".equals(uri)){ HelloServlet helloServlet = new HelloServlet(); helloServlet.doGet(request,response); } else{ if("/".equals(uri)) uri = WebXMLUtil.getWelcomeFile(request.getContext()); String fileName = StrUtil.removePrefix(uri, "/"); File file = FileUtil.file(context.getDocBase(),fileName); if(file.exists()){ String extName = FileUtil.extName(file); String mimeType = WebXMLUtil.getMimeType(extName); response.setContentType(mimeType); byte body[] = FileUtil.readBytes(file); response.setBody(body); if(fileName.equals("timeConsume.html")) ThreadUtil.sleep(1000); } else{ handle404(s, uri); return; } } handle200(s, response); } catch (Exception e) { LogFactory.get().error(e); handle500(s,e); } finally{ try { if(!s.isClosed()) s.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void handle200(Socket s, Response response) throws IOException { String contentType = response.getContentType(); String headText = Constant.response_head_202; headText = StrUtil.format(headText, contentType); byte[] head = headText.getBytes(); byte[] body = response.getBody(); 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); OutputStream os = s.getOutputStream(); os.write(responseBytes); } 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 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(); } } }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
自己写一个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.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.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("/hello"); Assert.assertEquals(html,"Hello DIY Tomcat from HelloServlet"); } 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,false); } 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); } }
步骤 9 :

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

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


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


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

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

上传截图