步骤 1 : 拓扑图点亮 步骤 2 : 压缩 步骤 3 : 关于 gzip 步骤 4 : server.xml 步骤 5 : Connector 步骤 6 : ServerXMLUtil 步骤 7 : Constant 步骤 8 : Request 步骤 9 : HttpProcessor 步骤 10 : MiniBrowser 步骤 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个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
<?xml version="1.0" encoding="UTF-8"?>
<Server>
<Service name="Catalina">
<Connector port="18080"
compression="on"
compressionMinSize="20"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml,text/javascript,application/javascript,text/css,text/plain,text/json"
/>
<Connector port="18081"/>
<Connector port="18082"/>
<Engine defaultHost="localhost">
<Host name = "localhost">
<Context path="/b" docBase="d:/project/diytomcat/b" />
<Context path="/javaweb" docBase="d:/project/javaweb/web" reloadable = "true" />
</Host>
</Engine>
</Service>
</Server>
<?xml version="1.0" encoding="UTF-8"?> <Server> <Service name="Catalina"> <Connector port="18080" compression="on" compressionMinSize="20" noCompressionUserAgents="gozilla, traviata" compressableMimeType="text/html,text/xml,text/javascript,application/javascript,text/css,text/plain,text/json" /> <Connector port="18081"/> <Connector port="18082"/> <Engine defaultHost="localhost"> <Host name = "localhost"> <Context path="/b" docBase="d:/project/diytomcat/b" /> <Context path="/javaweb" docBase="d:/project/javaweb/web" reloadable = "true" /> </Host> </Engine> </Service> </Server>
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.catalina;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import cn.how2j.diytomcat.http.Request;
import cn.how2j.diytomcat.http.Response;
import cn.how2j.diytomcat.util.ThreadPoolUtil;
import cn.hutool.log.LogFactory;
public class Connector implements Runnable {
int port;
private Service service;
private String compression;
private int compressionMinSize;
private String noCompressionUserAgents;
private String compressableMimeType;
public String getCompression() {
return compression;
}
public void setCompression(String compression) {
this.compression = compression;
}
public int getCompressionMinSize() {
return compressionMinSize;
}
public void setCompressionMinSize(int compressionMinSize) {
this.compressionMinSize = compressionMinSize;
}
public String getNoCompressionUserAgents() {
return noCompressionUserAgents;
}
public void setNoCompressionUserAgents(String noCompressionUserAgents) {
this.noCompressionUserAgents = noCompressionUserAgents;
}
public String getCompressableMimeType() {
return compressableMimeType;
}
public void setCompressableMimeType(String compressableMimeType) {
this.compressableMimeType = compressableMimeType;
}
public Connector(Service service) {
this.service = service;
}
public Service getService() {
return service;
}
public void setPort(int port) {
this.port = port;
}
@Override
public void run() {
try {
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, Connector.this);
Response response = new Response();
HttpProcessor processor = new HttpProcessor();
processor.execute(s,request, response);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (!s.isClosed())
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
ThreadPoolUtil.run(r);
}
} catch (IOException e) {
LogFactory.get().error(e);
e.printStackTrace();
}
}
public void init() {
LogFactory.get().info("Initializing ProtocolHandler [http-bio-{}]",port);
}
public void start() {
LogFactory.get().info("Starting ProtocolHandler [http-bio-{}]",port);
new Thread(this).start();
}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.util;
import cn.how2j.diytomcat.catalina.*;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
public class ServerXMLUtil {
public static List<Connector> getConnectors(Service service) {
List<Connector> result = new ArrayList<>();
String xml = FileUtil.readUtf8String(Constant.serverXmlFile);
Document d = Jsoup.parse(xml);
Elements es = d.select("Connector");
for (Element e : es) {
int port = Convert.toInt(e.attr("port"));
String compression = e.attr("compression");
int compressionMinSize = Convert.toInt(e.attr("compressionMinSize"), 0);
String noCompressionUserAgents = e.attr("noCompressionUserAgents");
String compressableMimeType = e.attr("compressableMimeType");
Connector c = new Connector(service);
c.setPort(port);
c.setCompression(compression);
c.setCompressableMimeType(compressableMimeType);
c.setNoCompressionUserAgents(noCompressionUserAgents);
c.setCompressableMimeType(compressableMimeType);
c.setCompressionMinSize(compressionMinSize);
result.add(c);
}
return result;
}
public static List<Context> getContexts(Host host) {
List<Context> result = new ArrayList<>();
String xml = FileUtil.readUtf8String(Constant.serverXmlFile);
Document d = Jsoup.parse(xml);
Elements es = d.select("Context");
for (Element e : es) {
String path = e.attr("path");
String docBase = e.attr("docBase");
boolean reloadable = Convert.toBool(e.attr("reloadable"), true);
Context context = new Context(path, docBase, host, reloadable);
result.add(context);
}
return result;
}
public static String getEngineDefaultHost() {
String xml = FileUtil.readUtf8String(Constant.serverXmlFile);
Document d = Jsoup.parse(xml);
Element host = d.select("Engine").first();
return host.attr("defaultHost");
}
public static String getServiceName() {
String xml = FileUtil.readUtf8String(Constant.serverXmlFile);
Document d = Jsoup.parse(xml);
Element host = d.select("Service").first();
return host.attr("name");
}
public static List<Host> getHosts(Engine engine) {
List<Host> result = new ArrayList<>();
String xml = FileUtil.readUtf8String(Constant.serverXmlFile);
Document d = Jsoup.parse(xml);
Elements es = d.select("Host");
for (Element e : es) {
String name = e.attr("name");
Host host = new Host(name,engine);
result.add(host);
}
return result;
}
}
增值内容,请先登录
自己写一个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_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");
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.http;
import cn.how2j.diytomcat.catalina.Connector;
import cn.how2j.diytomcat.catalina.Context;
import cn.how2j.diytomcat.catalina.Engine;
import cn.how2j.diytomcat.catalina.Service;
import cn.how2j.diytomcat.util.MiniBrowser;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.Converter;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.*;
public class Request extends BaseRequest{
private String requestString;
private String uri;
private Socket socket;
private Context context;
private String method;
private String queryString;
private Map<String, String[]> parameterMap;
private Map<String, String> headerMap;
private Cookie[] cookies;
private HttpSession session;
private Connector connector;
public Request(Socket socket, Connector connector) throws IOException {
this.parameterMap = new HashMap();
this.headerMap = new HashMap<>();
this.socket = socket;
this.connector = connector;
parseHttpRequest();
if(StrUtil.isEmpty(requestString))
return;
parseUri();
parseContext();
parseMethod();
if(!"/".equals(context.getPath())){
uri = StrUtil.removePrefix(uri, context.getPath());
if(StrUtil.isEmpty(uri))
uri = "/";
}
parseParameters();
parseHeaders();
parseCookies();
}
private void parseMethod() {
method = StrUtil.subBefore(requestString, " ", false);
}
private void parseContext() {
Service service = connector.getService();
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 parseCookies() {
List<Cookie> cookieList = new ArrayList<>();
String cookies = headerMap.get("cookie");
if (null != cookies) {
String[] pairs = StrUtil.split(cookies, ";");
for (String pair : pairs) {
if (StrUtil.isBlank(pair))
continue;
// System.out.println(pair.length());
// System.out.println("pair:"+pair);
String[] segs = StrUtil.split(pair, "=");
String name = segs[0].trim();
String value = segs[1].trim();
Cookie cookie = new Cookie(name, value);
cookieList.add(cookie);
}
}
this.cookies = ArrayUtil.toArray(cookieList, Cookie.class);
}
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 getMethod() {
return method;
}
public ServletContext getServletContext() {
return context.getServletContext();
}
public String getRealPath(String path) {
return getServletContext().getRealPath(path);
}
private void parseParameters() {
if ("GET".equals(this.getMethod())) {
String url = StrUtil.subBetween(requestString, " ", " ");
if (StrUtil.contains(url, '?')) {
queryString = StrUtil.subAfter(url, '?', false);
}
}
if ("POST".equals(this.getMethod())) {
queryString = StrUtil.subAfter(requestString, "\r\n\r\n", false);
}
if (null == queryString || 0==queryString.length())
return;
queryString = URLUtil.decode(queryString);
String[] parameterValues = queryString.split("&");
if (null != parameterValues) {
for (String parameterValue : parameterValues) {
String[] nameValues = parameterValue.split("=");
String name = nameValues[0];
String value = nameValues[1];
String values[] = parameterMap.get(name);
if (null == values) {
values = new String[] { value };
parameterMap.put(name, values);
} else {
values = ArrayUtil.append(values, value);
parameterMap.put(name, values);
}
}
}
}
public String getParameter(String name) {
String values[] = parameterMap.get(name);
if (null != values && 0 != values.length)
return values[0];
return null;
}
public Map getParameterMap() {
return parameterMap;
}
public Enumeration getParameterNames() {
return Collections.enumeration(parameterMap.keySet());
}
public String[] getParameterValues(String name) {
return parameterMap.get(name);
}
public String getHeader(String name) {
if(null==name)
return null;
name = name.toLowerCase();
return headerMap.get(name);
}
public Enumeration getHeaderNames() {
Set keys = headerMap.keySet();
return Collections.enumeration(keys);
}
public int getIntHeader(String name) {
String value = headerMap.get(name);
return Convert.toInt(value, 0);
}
public void parseHeaders() {
StringReader stringReader = new StringReader(requestString);
List<String> lines = new ArrayList<>();
IoUtil.readLines(stringReader, lines);
for (int i = 1; i < lines.size(); i++) {
String line = lines.get(i);
if (0 == line.length())
break;
String[] segs = line.split(":");
String headerName = segs[0].toLowerCase();
String headerValue = segs[1];
headerMap.put(headerName, headerValue);
}
}
public String getLocalAddr() {
return socket.getLocalAddress().getHostAddress();
}
public String getLocalName() {
return socket.getLocalAddress().getHostName();
}
public int getLocalPort() {
return socket.getLocalPort();
}
public String getProtocol() {
return "HTTP:/1.1";
}
public String getRemoteAddr() {
InetSocketAddress isa = (InetSocketAddress) socket.getRemoteSocketAddress();
String temp = isa.getAddress().toString();
return StrUtil.subAfter(temp, "/", false);
}
public String getRemoteHost() {
InetSocketAddress isa = (InetSocketAddress) socket.getRemoteSocketAddress();
return isa.getHostName();
}
public int getRemotePort() {
return socket.getPort();
}
public String getScheme() {
return "http";
}
public String getServerName() {
return getHeader("host").trim();
}
public int getServerPort() {
return getLocalPort();
}
public String getContextPath() {
String result = this.context.getPath();
if ("/".equals(result))
return "";
return result;
}
public String getRequestURI() {
return uri;
}
public StringBuffer getRequestURL() {
StringBuffer url = new StringBuffer();
String scheme = getScheme();
int port = getServerPort();
if (port < 0) {
port = 80; // Work around java.net.URL bug
}
url.append(scheme);
url.append("://");
url.append(getServerName());
if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) {
url.append(':');
url.append(port);
}
url.append(getRequestURI());
return url;
}
public String getServletPath() {
return uri;
}
public Cookie[] getCookies() {
return cookies;
}
public String getJSessionIdFromCookie() {
if (null == cookies)
return null;
for (Cookie cookie : cookies) {
if ("JSESSIONID".equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
public HttpSession getSession() {
return session;
}
public void setSession(HttpSession session) {
this.session = session;
}
public Connector getConnector() {
return connector;
}
}
增值内容,请先登录
自己写一个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.util.Constant;
import cn.how2j.diytomcat.util.SessionManager;
import cn.hutool.core.util.*;
import cn.hutool.log.LogFactory;
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
DefaultServlet.getInstance().service(request,response);
if(Constant.CODE_200 == response.getStatus()){
handle200(s, request, 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 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;
}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.util;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpUtil;
public class MiniBrowser {
public static void main(String[] args) throws Exception {
String url = "http://static.how2j.cn/diytomcat.html";
String contentString= getContentString(url,false);
System.out.println(contentString);
String httpString= getHttpString(url,false);
System.out.println(httpString);
}
public static byte[] getContentBytes(String url, Map<String,Object> params, boolean isGet) {
return getContentBytes(url, false,params,isGet);
}
public static byte[] getContentBytes(String url, boolean gzip) {
return getContentBytes(url, gzip,null,true);
}
public static byte[] getContentBytes(String url) {
return getContentBytes(url, false,null,true);
}
public static String getContentString(String url, Map<String,Object> params, boolean isGet) {
return getContentString(url,false,params,isGet);
}
public static String getContentString(String url, boolean gzip) {
return getContentString(url, gzip, null, true);
}
public static String getContentString(String url) {
return getContentString(url, false, null, true);
}
public static String getContentString(String url, boolean gzip, Map<String,Object> params, boolean isGet) {
byte[] result = getContentBytes(url, gzip,params,isGet);
if(null==result)
return null;
try {
return new String(result,"utf-8").trim();
} catch (UnsupportedEncodingException e) {
return null;
}
}
public static byte[] getContentBytes(String url, boolean gzip, Map<String,Object> params, boolean isGet) {
byte[] response = getHttpBytes(url,gzip,params,isGet);
byte[] doubleReturn = "\r\n\r\n".getBytes();
int pos = -1;
for (int i = 0; i < response.length-doubleReturn.length; i++) {
byte[] temp = Arrays.copyOfRange(response, i, i + doubleReturn.length);
if(Arrays.equals(temp, doubleReturn)) {
pos = i;
break;
}
}
if(-1==pos)
return null;
pos += doubleReturn.length;
byte[] result = Arrays.copyOfRange(response, pos, response.length);
return result;
}
public static String getHttpString(String url,boolean gzip) {
return getHttpString(url, gzip, null, true);
}
public static String getHttpString(String url) {
return getHttpString(url, false, null, true);
}
public static String getHttpString(String url,boolean gzip, Map<String,Object> params, boolean isGet) {
byte[] bytes=getHttpBytes(url,gzip,params,isGet);
return new String(bytes).trim();
}
public static String getHttpString(String url, Map<String,Object> params, boolean isGet) {
return getHttpString(url,false,params,isGet);
}
public static byte[] getHttpBytes(String url,boolean gzip, Map<String,Object> params, boolean isGet) {
String method = isGet?"GET":"POST";
byte[] result = null;
try {
URL u = new URL(url);
Socket client = new Socket();
int port = u.getPort();
if(-1==port)
port = 80;
InetSocketAddress inetSocketAddress = new InetSocketAddress(u.getHost(), port);
client.connect(inetSocketAddress, 1000);
Map<String,String> requestHeaders = new HashMap<>();
requestHeaders.put("Host", u.getHost()+":"+port);
requestHeaders.put("Accept", "text/html");
requestHeaders.put("Connection", "close");
requestHeaders.put("User-Agent", "how2j mini brower / java1.8");
if(gzip)
requestHeaders.put("Accept-Encoding", "gzip");
String path = u.getPath();
if(path.length()==0)
path = "/";
if(null!=params && isGet){
String paramsString = HttpUtil.toParams(params);
path = path + "?" + paramsString;
}
String firstLine = method + " " + path + " HTTP/1.1\r\n";
StringBuffer httpRequestString = new StringBuffer();
httpRequestString.append(firstLine);
Set<String> headers = requestHeaders.keySet();
for (String header : headers) {
String headerLine = header + ":" + requestHeaders.get(header)+"\r\n";
httpRequestString.append(headerLine);
}
if(null!=params && !isGet){
String paramsString = HttpUtil.toParams(params);
httpRequestString.append("\r\n");
httpRequestString.append(paramsString);
}
PrintWriter pWriter = new PrintWriter(client.getOutputStream(), true);
pWriter.println(httpRequestString);
InputStream is = client.getInputStream();
result = readBytes(is,true);
client.close();
} catch (Exception e) {
e.printStackTrace();
try {
result = e.toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
return result;
}
public static byte[] readBytes(InputStream is, boolean fully) throws IOException {
int buffer_size = 1024;
byte buffer[] = new byte[buffer_size];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while(true) {
int length = is.read(buffer);
if(-1==length)
break;
baos.write(buffer, 0, length);
if(!fully && length!=buffer_size)
break;
}
byte[] result =baos.toByteArray();
return result;
}
}
增值内容,请先登录
自己写一个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");
}
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);
}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
问答区域
2021-03-08
这里的testGzip()有问题
9 个答案
999918cjs 跳转到问题位置 答案时间:2022-06-04 我也是因为没改测试类中的这块代码出现的这个问题
private byte[] getContentBytes(String uri,boolean gzip) { String url = StrUtil.format("http://{}:{}{}", ip,port,uri); return MiniBrowser.getContentBytes(url,gzip); } zy080080 跳转到问题位置 答案时间:2021-11-10 我是在读取server.xml的时候把compressionMinSize写成了conpressionMinSize才出现这个问题int compressionMinSize = Convert.toInt(e.attr("compressionMinSize"), 0);。。。大家注意拼写
int compressionMinSize = Convert.toInt(e.attr("compressionMinSize"), 0); 星归 跳转到问题位置 答案时间:2021-07-23 是站长前面的那个响应头信息写错了,再MiniBrowser的getHttpBytes,是Accept-Encoding,而不是Accept_Encoding
huanghf 跳转到问题位置 答案时间:2021-07-18 private byte[] getContentBytes(String uri,boolean gzip) {
String url = StrUtil.format("http://{}:{}{}", ip,port,uri);
return MiniBrowser.getContentBytes(url,gzip);
}
我是因为没改测试类中的这块代码出现的这个问题 打工人 跳转到问题位置 答案时间:2021-05-22 @chuancey 我这里不是这个问题,我一直用的都是开启了压缩的端口,检查过了。
chuancey 跳转到问题位置 答案时间:2021-05-09 我也出现了这个问题,后来才发现是testTomcat里使用的端口号(我的是10882)和我设置的Connector端口号(10880)不一致导致的。
打工人 跳转到问题位置 答案时间:2021-04-23 @devilllll 还没解决
devilllll 跳转到问题位置 答案时间:2021-04-12 老铁你的问题解决了吗?我也出现了这个异常。
how2j 跳转到问题位置 答案时间:2021-03-12 我跑了下没问题呀。。。。/扣脑壳
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
2020-06-18
站长,这里是修改TestTomcat里面的代码吧,MiniBrowser好像不用改
2 个答案
BeachFish 跳转到问题位置 答案时间:2020-06-23 老铁你说的对,站长大大写错了
how2j 跳转到问题位置 答案时间:2020-06-19 这里是个bug:
return MiniBrowser.getContentBytes(url,false);
以前这里是固定传 false,现在修改这个bug
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|