代码结构
RequestMapping
package com.commons.study.webserver.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* RequestMapping 注解
*
* <p>Copyright: Copyright (c) 2019</p>
* <p>succez</p>
*
* @author kejint
* @createdate 2019/11/26
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
String value() default "";
}
HttpRequest
package com.commons.study.webserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
/**
* 请求类 解析Http请求中的请求头,请求体,请求方法,请求路径
*
* <p>Copyright: Copyright (c) 2019</p>
* <p>succez</p>
*
* @author kejint
* @createdate 2019/11/15
*/
public class HttpRequest {
private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class);
private String url = "";
private String requestPath = "";
private String requestMethod = "";
private String requestBody = "";
private HashMap<String, String> requestParams = new HashMap<>();
private InputStream inputStream;
HttpRequest(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getRequestMethod() {
return requestMethod;
}
public void setRequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
}
public String getRequestBody() {
return requestBody;
}
public void setRequestBody(String requestBody) {
this.requestBody = requestBody;
}
public HashMap<String, String> getRequestParams() {
return requestParams;
}
public String getRequestPath() {
return requestPath;
}
public void setRequestPath(String requestPath) {
this.requestPath = requestPath;
}
/**
* 获取输入流,返回请求内容,用于解析request请求
*
* @return 请求内容字符串
*/
public String parse() throws IOException {
int count = 0;
String requestStr;
while (count == 0) {
count = inputStream.available();
}
int readCount = 0;
byte[] bytes = new byte[count];
while (readCount < count) {
readCount += inputStream.read(bytes, readCount, count - readCount);
}
requestStr = new String(bytes, StandardCharsets.UTF_8);
logger.trace("request请求内容为 [{}]", requestStr);
return requestStr;
}
/**
* 解析request请求,获取请求参数,URl,请求体,请求方法
*/
public void parseRequestStr() throws IOException {
String requestStr = parse();
String[] lines = requestStr.split("\r\n");
if (lines.length <= 0) {
throw new RuntimeException("空请求,无法解析!");
}
String line1 = lines[0];
int index1 = line1.indexOf(' ');
if (index1 != -1) {
int index2 = line1.indexOf(' ', index1 + 1);
if (index2 &g