步骤 1 : 拓扑图点亮 步骤 2 : 服务端跳转 步骤 3 : ApplicationRequestDispatcher 步骤 4 : Request 步骤 5 : HttpProcessor 步骤 6 : ServerJumpServlet 步骤 7 : web.xml 步骤 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.http;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import cn.how2j.diytomcat.catalina.HttpProcessor;
public class ApplicationRequestDispatcher implements RequestDispatcher {
private String uri;
public ApplicationRequestDispatcher(String uri) {
if(!uri.startsWith("/"))
uri = "/" + uri;
this.uri = uri;
}
@Override
public void forward(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
Request request = (Request) servletRequest;
Response response = (Response) servletResponse;
request.setUri(uri);
HttpProcessor processor = new HttpProcessor();
processor.execute(request.getSocket(), request,response);
request.setForwarded(true);
}
@Override
public void include(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
增值内容,请先登录
自己写一个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.RequestDispatcher;
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;
private boolean forwarded;
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;
}
public void setUri(String uri) {
this.uri = uri;
}
public Socket getSocket() {
return socket;
}
public boolean isForwarded() {
return forwarded;
}
public void setForwarded(boolean forwarded) {
this.forwarded = forwarded;
}
public RequestDispatcher getRequestDispatcher(String uri) {
return new ApplicationRequestDispatcher(uri);
}
}
增值内容,请先登录
自己写一个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(request.isForwarded())
return;
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;
}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.javaweb;
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 ServerJumpServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
request.getRequestDispatcher("hello").forward(request,response);
} catch (ServletException e) {
e.printStackTrace();
}
}
}
package cn.how2j.javaweb; 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 ServerJumpServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { request.getRequestDispatcher("hello").forward(request,response); } catch (ServletException e) { e.printStackTrace(); } } }
增值内容,请先登录
自己写一个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>
<servlet>
<servlet-name>ServerJumpServlet</servlet-name>
<servlet-class>cn.how2j.javaweb.ServerJumpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServerJumpServlet</servlet-name>
<url-pattern>/jump2</url-pattern>
</servlet-mapping>
</web-app>
增值内容,请先登录
自己写一个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");
}
@Test
public void testServerJump(){
String http_servlet = getHttpString("/javaweb/jump2");
containAssert(http_servlet,"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,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-02-10
request在这里不设置forwarded为true看起来也没有啥问题呀?
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
2020-10-21
关于上一页面reponse的body,影响下一页面的body
2 个答案
wuchangkun 跳转到问题位置 答案时间:2022-10-30 同理由于两次调用HttpProcess,prepareSession(request, response)这段代码导致两次设置Session,那我们保留那段Session呢
prepareSession(request, response); how2j 跳转到问题位置 答案时间:2020-10-21 哇, 你说的很有道理呢,被你发现一个bug, 赞!
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
2020-08-21
能再解释一下如果是forwarded就不做后续处理的原因吗
2020-06-26
无论是客户端还是服务端,跳转的业务意义什么呢
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|