步骤 1 : 拓扑图点亮 步骤 2 : 获取参数 步骤 3 : ParamServlet 步骤 4 : web.xml 步骤 5 : Request 步骤 6 : MiniBrowser 步骤 7 : TestTomcat 步骤 8 : 比较可运行项目,快速定位问题
增值内容,请先登录
自己写一个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.javaweb;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ParamServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try {
String name = request.getParameter("name");
response.getWriter().println("get name:" + name);
} catch (Exception e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response){
try {
String name = request.getParameter("name");
response.getWriter().println("post name:" + name);
} catch (Exception 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>
</web-app>
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.http;
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.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class Request extends BaseRequest{
private String requestString;
private String uri;
private Socket socket;
private Context context;
private Service service;
private String method;
private String queryString;
private Map<String, String[]> parameterMap;
public Request(Socket socket, Service service) throws IOException {
this.parameterMap = new HashMap();
this.socket = socket;
this.service = service;
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();
}
private void parseMethod() {
method = StrUtil.subBefore(requestString, " ", false);
}
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 getMethod() {
return method;
}
public ServletContext getServletContext() {
return context.getServletContext();
}
public String getRealPath(String path) {
return getServletContext().getRealPath(path);
}
private void parseParameters() {
System.out.println(requestString);
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);
}
}
增值内容,请先登录
自己写一个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.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.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");
}
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);
}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
问答区域
2020-06-26
请求参数的值为啥是String[]格式呢?一个name不是对应一个value吗?
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|