Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

안녕하세요 #29

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* 각 요구사항을 구현하는 것이 중요한 것이 아니라 구현 과정을 통해 학습한 내용을 인식하는 것이 배움에 중요하다.

### 요구사항 1 - http://localhost:8080/index.html로 접속시 응답
*
*

### 요구사항 2 - get 방식으로 회원가입
*
Expand All @@ -24,13 +24,13 @@
*

### 요구사항 4 - redirect 방식으로 이동
*
* http 상태코드에대해 알게되었다. 302 코드를 이용하여 실무에서 사용했던 불필요한 요청로직을 지울수있을것같다.

### 요구사항 5 - cookie
*
* 개발하면서 헤더에 쿠키를 담아서 보내는데 생각보다 오래걸렷다. 문자열을 자르는것 부터 많은 리팩토링이 필요하다.

### 요구사항 6 - stylesheet 적용
*
* css의 타입이 text/css 인지 여태 신경도 안쓰고 개발했던것같다. 프레임워크에서 자동으로 해주다보니 잘 적용되던것들을 가볍게 넘긴거같다.

### heroku 서버에 배포 후
*
*
61 changes: 61 additions & 0 deletions src/main/java/util/HeaderUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package util;


import java.util.HashMap;
import java.util.Map;

public class HeaderUtil {

public static String getUriInHeader(String header) {
String[] headerArr = header.split(" ");
return headerArr[1];
}

public static String getRealUrl(String url) {
int index = url.indexOf("?");

if (index == -1) {
return url;
}
return url.substring(0, index);
}

public static String getParamInUrl(String url) {
int index = url.indexOf("?");

if (index == -1) {
return "";
}

return url.substring(index+1);
}

public static Map<String, String> paramToMap(String paramText) {
int length = paramText.length();
String[] paramArr = paramText.split("&");
Map<String, String> paramMap = new HashMap<>();

if (length == 0) {
return paramMap;
}

for (String param : paramArr) {
mapInputParam(param, paramMap);
}

System.out.println(paramMap);

return paramMap;
}

private static void mapInputParam (String param, Map<String, String> paramMap) {
int index = param.indexOf("=");
if(index > -1) {
String key = param.substring(0, index);
String value = param.substring(index + 1, param.length());

paramMap.put(key, value);
}
}

}
1 change: 1 addition & 0 deletions src/main/java/util/HttpRequestUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.google.common.base.Strings;
Expand Down
42 changes: 32 additions & 10 deletions src/main/java/webserver/RequestHandler.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package webserver;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.util.Map;

import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.HeaderUtil;
import util.HttpRequestUtils;

public class RequestHandler extends Thread {
private static final Logger log = LoggerFactory.getLogger(RequestHandler.class);
Expand All @@ -24,11 +26,31 @@ public void run() {

try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {
// TODO 사용자 요청에 대한 처리는 이 곳에 구현하면 된다.
DataOutputStream dos = new DataOutputStream(out);
byte[] body = "Hello World".getBytes();
response200Header(dos, body.length);
responseBody(dos, body);
} catch (IOException e) {

final String line = br.readLine();
final String url = HeaderUtil.getUriInHeader(line);
final String realUrl = HeaderUtil.getRealUrl(url);

//리팩토링 힌트

// param = HeaderUtil.getParamInUrl(url);
// Map<String, String> map =HeaderUtil.paramToMap(param);

if (url.startsWith("/user/create")) {
final int index = url.indexOf("?");
final String queryString = url.substring(index + 1);

final Map<String, String> params = HttpRequestUtils.parseQueryString(queryString);

final User user = new User(params.get("userId"), params.get("password"), params.get("name"), params.get("email"));
} else {
final DataOutputStream dos = new DataOutputStream(out);
// byte[] body = "Hello World22".getBytes();
final byte[] body = Files.readAllBytes(new File("./webapp" + realUrl).toPath());
response200Header(dos, body.length);
responseBody(dos, body);
}
} catch (final IOException e) {
log.error(e.getMessage());
}
}
Expand All @@ -52,4 +74,4 @@ private void responseBody(DataOutputStream dos, byte[] body) {
log.error(e.getMessage());
}
}
}
}
1 change: 0 additions & 1 deletion src/main/java/webserver/WebServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ public static void main(String args[]) throws Exception {
}

// 서버소켓을 생성한다. 웹서버는 기본적으로 8080번 포트를 사용한다.

try (ServerSocket listenSocket = new ServerSocket(port)) {
log.info("Web Application Server started {} port.", port);

Expand Down
64 changes: 64 additions & 0 deletions src/test/java/util/HeaderUtilTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package util;

import org.junit.Test;

import java.util.Map;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

public class HeaderUtilTest {

@Test
public void url_분리() {

String header = "GET /index.html HTTP/1.1";

String url = HeaderUtil.getUriInHeader(header);

assertThat("/index.html", is(url));
}



@Test
public void url_파라메터_제거버전() {

String pullUrl = "/index.html?name=123&password=1234";

String url = HeaderUtil.getRealUrl(pullUrl);

assertThat("/index.html", is(url));
}

@Test
public void url_제거버전() {

String pullUrl = "/index.html?name=123&password=1234";

String url = HeaderUtil.getParamInUrl(pullUrl);

assertThat("name=123&password=1234", is(url));
}

@Test
public void url_제거버전2() {

String pullUrl = "/index.html";

String url = HeaderUtil.getParamInUrl(pullUrl);

assertThat("", is(url));
}

@Test
public void paramToMap() {

String pullUrl = "name=123&password=1234";

Map<String,String> map = HeaderUtil.paramToMap(pullUrl);

assertThat("123", is(map.get("name")));
assertThat("1234", is(map.get("password")));
}
}
2 changes: 1 addition & 1 deletion webapp/user/form.html
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
<div class="container" id="main">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default content-main">
<form name="question" method="get" action="/user/create">
<form name="question" method="post" action="/user/create">
<div class="form-group">
<label for="userId">사용자 아이디</label>
<input class="form-control" id="userId" name="userId" placeholder="User ID">
Expand Down