步骤 1 : 拓扑图点亮 步骤 2 : 500错误 步骤 3 : Constant 步骤 4 : Server 步骤 5 : TestTomcat 步骤 6 : 比较可运行项目,快速定位问题
增值内容,请先登录
自己写一个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");
}
增值内容,请先登录
自己写一个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.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)){
String html = "Hello DIY Tomcat from how2j.cn";
response.getWriter().println(html);
}
else{
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个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
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/index.html");
Assert.assertEquals(html,"Hello DIY Tomcat from index.html@a");
}
@Test
public void testbIndex() {
String html = getContentString("/b/index.html");
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);
}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|