how2j.cn

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

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

步骤 1 : 拓扑图点亮   
步骤 2 : 欢迎文件   
步骤 3 : Constant   
步骤 4 : web.xml   
步骤 5 : WebXMLUtil   
步骤 6 : Request   
步骤 7 : Server   
步骤 8 : index.html   
步骤 9 : TestTomcat   
步骤 10 : 比较可运行项目,快速定位问题   

增值内容,请先登录
自己写一个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.util; import cn.hutool.system.SystemUtil; import java.io.File; public class Constant { public final static String response_head_202 = "HTTP/1.1 200 OK\r\n" + "Content-Type: {}\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"); }
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
<?xml version="1.0" encoding="UTF-8"?> <web-app> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.util; import static cn.how2j.diytomcat.util.Constant.webXmlFile; import java.io.File; import java.util.HashMap; import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import cn.how2j.diytomcat.catalina.Context; import cn.hutool.core.io.FileUtil; public class WebXMLUtil { public static String getWelcomeFile(Context context) { String xml = FileUtil.readUtf8String(webXmlFile); Document d = Jsoup.parse(xml); Elements es = d.select("welcome-file"); for (Element e : es) { String welcomeFileName = e.text(); File f = new File(context.getDocBase(), welcomeFileName); if (f.exists()) return f.getName(); } return "index.html"; } }
增值内容,请先登录
自己写一个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 java.io.IOException; import java.io.InputStream; import java.net.Socket; public class Request { 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); 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; } }
增值内容,请先登录
自己写一个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.ThreadPoolUtil; import cn.how2j.diytomcat.util.WebXMLUtil; 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 cn.hutool.system.SystemUtil; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; public class Server { private Service service; public Server(){ this.service = new Service(this); } public void start(){ logJVM(); init(); } private void init() { try { int port = 18080; ServerSocket ss = new ServerSocket(port); while(true) { Socket s = ss.accept(); Runnable r = new Runnable(){ @Override public void run() { try { Request request = new Request(s,service); Response response = new Response(); String uri = request.getUri(); if(null==uri) return; System.out.println("uri:"+uri); Context context = request.getContext(); if("/500.html".equals(uri)){ throw new Exception("this is a deliberately created exception"); } if("/".equals(uri)) uri = WebXMLUtil.getWelcomeFile(request.getContext()); String fileName = StrUtil.removePrefix(uri, "/"); File file = FileUtil.file(context.getDocBase(),fileName); if(file.exists()){ String fileContent = FileUtil.readUtf8String(file); response.getWriter().println(fileContent); 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(); } } } }; ThreadPoolUtil.run(r); } } catch (IOException e) { LogFactory.get().error(e); e.printStackTrace(); } } private static void logJVM() { Map<String,String> infos = new LinkedHashMap<>(); infos.put("Server version", "How2J DiyTomcat/1.0.1"); infos.put("Server built", "2020-04-08 10:20:22"); infos.put("Server number", "1.0.1"); infos.put("OS Name\t", SystemUtil.get("os.name")); infos.put("OS Version", SystemUtil.get("os.version")); infos.put("Architecture", SystemUtil.get("os.arch")); infos.put("Java Home", SystemUtil.get("java.home")); infos.put("JVM Version", SystemUtil.get("java.runtime.version")); infos.put("JVM Vendor", SystemUtil.get("java.vm.specification.vendor")); Set<String> keys = infos.keySet(); for (String key : keys) { LogFactory.get().info(key+":\t\t" + infos.get(key)); } } 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); } protected 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); } protected 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个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
Hello DIY Tomcat from how2j.cn
Hello DIY Tomcat from how2j.cn
增值内容,请先登录
自己写一个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 org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; 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"); } 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); } }
步骤 10 :

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

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


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


问答区域    
2021-02-25 改进一下,能自动访问二级以上目录的index
打工人




站长的代码到这里的时候是不能自动映射类似/a/b或/a/b/c这样的有二三级目录以上的index文件,我测试过tomcat,tomcat是会这样做的,所以我在Server里改进了一下,做到和tomcat一样。
                            if("/".equals(uri)){
                                uri= WebXMLUtil.getWelcomeFile(request.getContext());
                            }
                            String fileName = StrUtil.removePrefix(uri, "/");
                            File file=new File(context.getDocBase(),fileName);
                            //改动在这里
                            if (!file.isFile()){//因为只有目录没有文件,所有判断不是文件就行了
                                uri=uri+"/"+WebXMLUtil.getWelcomeFile(request.getContext());
                                fileName = StrUtil.removePrefix(uri, "/");
                                file=new File(context.getDocBase(),fileName);
                            }

							


1 个答案

how2j
答案时间:2021-03-01
很好,good!



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





2020-07-27 步骤6理解
Tyx

1、如果传进来的uri是“/a/index”,那么path为“/a”,Request构造方法中会把uri剔除path前缀,得到“/index”,即a目录下的index文件 2、如果传进来的uri是“/a”,那么context = engine.getDefaultHost().getContext(uri) 非空,直接可以获取到path为“/a“的context,直接可以return,即uri为”/a”,path也是"/a",构造方法 把uri剔除path前缀变为空,最后设uri=“/”,即可使得 “/a"的uri转换为a目录下的”/",即欢迎目录 是否是这么理解?




3 个答案

LittleCatXianYu
答案时间:2022-01-21
输入“/a”是被识别为了a应用,docBase = project\DIYtomcat\webapps\a,获得的index.html也是 Hello DIY Tomcat from index.html@a

chuancey
答案时间:2021-04-17
" /a 会被认为是 ROOT应用。" 这句是不是有点问题呢?"/a"应该要被识别为a应用,因为a应用这里已经存在了,为啥要被识别为ROOT应用,如果是ROOT下的a.html,那是Root应用,但是如果在浏览器中输入“http://localhost:18080/a”这种,肯定就是a应用了。

how2j
答案时间:2020-07-28
是的, /a/index就会被认识为 a应用,但是 /a 会被认为是 ROOT应用。



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








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

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

上传截图