Skip to content

Commit aa12b81

Browse files
Oraindropjavajigi
authored andcommitted
Step1 (#41)
* first requirement show index.html page * requirement2 implement get method join * requirement3 implement post mapping * implement httpstatus 302 header * requirement4 and refactoring implement redirect 302 header extract method and class * change a package from ResponsMessage * incomplete login function * implement login response header set cookie * requirement6 로그인 시 user/list 조회 가능 * requirement7, apply css
1 parent 793027d commit aa12b81

File tree

11 files changed

+349
-30
lines changed

11 files changed

+349
-30
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package controller;
2+
3+
import dto.ResponseMessage;
4+
import util.HttpResponseHeaderUtils;
5+
6+
import java.io.File;
7+
import java.io.IOException;
8+
import java.nio.file.Files;
9+
10+
public class MainController {
11+
12+
public static ResponseMessage showHtml(String path) throws IOException {
13+
return ResponseMessage.ofBody(Files.readAllBytes(new File("./webapp" + path).toPath()));
14+
}
15+
16+
public static ResponseMessage showDefaultMessage() {
17+
return ResponseMessage.ofDefault();
18+
}
19+
20+
public static ResponseMessage showCss(String path) throws IOException {
21+
byte[] body = Files.readAllBytes(new File("./webapp" + path).toPath());
22+
return ResponseMessage.ofMessage(HttpResponseHeaderUtils.generate200CssHeader(body.length), body);
23+
}
24+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package controller;
2+
3+
import db.DataBase;
4+
import dto.ResponseMessage;
5+
import model.User;
6+
import org.slf4j.Logger;
7+
import util.HttpRequestUtils;
8+
import util.HttpResponseHeaderUtils;
9+
import util.HttpResponseHtmlUtils;
10+
11+
import java.io.BufferedReader;
12+
import java.io.IOException;
13+
import java.util.Map;
14+
15+
import static org.slf4j.LoggerFactory.getLogger;
16+
17+
public class UserController {
18+
private static final Logger log = getLogger(UserController.class);
19+
20+
public static ResponseMessage create(BufferedReader br, String headerFirstLine) throws IOException {
21+
Map<String, String> header = HttpRequestUtils.readHeader(br, headerFirstLine);
22+
Map<String, String> body = HttpRequestUtils.readRequestBody(br, Integer.parseInt(header.get("Content-Length")));
23+
User newUser =
24+
User.of(body.get("userId"), body.get("password"), body.get("name"), body.get("email"));
25+
DataBase.addUser(newUser);
26+
return ResponseMessage.ofMessage(HttpResponseHeaderUtils.generate302Header("/index.html"), "".getBytes());
27+
}
28+
29+
public static ResponseMessage login(BufferedReader br, String headerFirstLine) throws IOException {
30+
Map<String, String> header = HttpRequestUtils.readHeader(br, headerFirstLine);
31+
Map<String, String> parseValues = HttpRequestUtils.readRequestBody(br, Integer.parseInt(header.get("Content-Length")));
32+
User maybeUser = DataBase.findUserById(parseValues.get("userId"));
33+
if(maybeUser.isEmpty()) return ResponseMessage.ofMessage(HttpResponseHeaderUtils.generate302CookieHeader("/user/login_failed.html", false), "".getBytes());
34+
if(maybeUser.isCorrect(parseValues.get("password"))){
35+
return ResponseMessage.ofMessage(HttpResponseHeaderUtils.generate302CookieHeader("/index.html", true), "".getBytes());
36+
}
37+
return ResponseMessage.ofMessage(HttpResponseHeaderUtils.generate302CookieHeader("/user/login_failed.html", false), "".getBytes());
38+
}
39+
40+
public static ResponseMessage list(BufferedReader br, String headerFirstLine) throws IOException {
41+
Map<String, String> header = HttpRequestUtils.readHeader(br, headerFirstLine);
42+
if(isLogin(header)) {
43+
return ResponseMessage.ofBody(HttpResponseHtmlUtils.generate(DataBase.findAll()).getBytes());
44+
}
45+
return ResponseMessage.ofMessage(HttpResponseHeaderUtils.generate302Header("/user/login.html"), "".getBytes());
46+
}
47+
48+
private static boolean isLogin(Map<String, String> header) {
49+
if(header.get("Cookie") != null){
50+
String[] cookie = header.get("Cookie").split("=");
51+
if(cookie.length == 2) {
52+
return Boolean.parseBoolean(cookie[1]);
53+
}
54+
}
55+
return false;
56+
}
57+
}

src/main/java/db/DataBase.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.Collection;
44
import java.util.Map;
5+
import java.util.Optional;
56

67
import com.google.common.collect.Maps;
78

@@ -15,7 +16,7 @@ public static void addUser(User user) {
1516
}
1617

1718
public static User findUserById(String userId) {
18-
return users.get(userId);
19+
return users.getOrDefault(userId, User.ofEmpty());
1920
}
2021

2122
public static Collection<User> findAll() {
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package dto;
2+
3+
import org.slf4j.Logger;
4+
import util.HttpResponseHeaderUtils;
5+
6+
import java.io.DataOutputStream;
7+
import java.io.IOException;
8+
9+
import static org.slf4j.LoggerFactory.getLogger;
10+
11+
public class ResponseMessage {
12+
private static final Logger log = getLogger(ResponseMessage.class);
13+
14+
private String header;
15+
private byte[] body;
16+
17+
private ResponseMessage(String header, byte[] body) {
18+
this.header = header;
19+
this.body = body;
20+
}
21+
22+
public static ResponseMessage ofDefault() {
23+
return ResponseMessage.ofBody("Hello World".getBytes());
24+
}
25+
26+
public static ResponseMessage ofBody(byte[] body) {
27+
return new ResponseMessage(HttpResponseHeaderUtils.generate200Header(body.length), body);
28+
}
29+
30+
public static ResponseMessage ofMessage(String header, byte[] body) {
31+
return new ResponseMessage(header, body);
32+
}
33+
34+
public void response(DataOutputStream dos) {
35+
try {
36+
log.debug("responseHeader : {}", header);
37+
dos.writeBytes(header);
38+
dos.write(body, 0, body.length);
39+
dos.flush();
40+
} catch (IOException e) {
41+
log.error(e.getMessage());
42+
}
43+
}
44+
45+
}

src/main/java/model/User.java

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,19 @@ public class User {
66
private String name;
77
private String email;
88

9-
public User(String userId, String password, String name, String email) {
9+
public static User of(String userId, String password, String name, String email) {
10+
return new User(userId, password, name, email);
11+
}
12+
13+
public static User ofEmpty() {
14+
return new User();
15+
}
16+
17+
private User() {
18+
19+
}
20+
21+
private User(String userId, String password, String name, String email) {
1022
this.userId = userId;
1123
this.password = password;
1224
this.name = name;
@@ -29,8 +41,16 @@ public String getEmail() {
2941
return email;
3042
}
3143

44+
public boolean isCorrect(String password) {
45+
return this.password.equals(password);
46+
}
47+
48+
public boolean isEmpty() {
49+
return this.userId == null;
50+
}
51+
3252
@Override
3353
public String toString() {
34-
return "User [userId=" + userId + ", password=" + password + ", name=" + name + ", email=" + email + "]";
54+
return "User [userId=" + userId + ", name=" + name + ", email=" + email + "]";
3555
}
3656
}

src/main/java/util/HttpRequestUtils.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
11
package util;
22

3+
import java.io.BufferedReader;
4+
import java.io.IOException;
35
import java.util.Arrays;
6+
import java.util.HashMap;
47
import java.util.Map;
58
import java.util.stream.Collectors;
69

710
import com.google.common.base.Strings;
811
import com.google.common.collect.Maps;
12+
import org.slf4j.Logger;
13+
14+
import static org.slf4j.LoggerFactory.getLogger;
915

1016
public class HttpRequestUtils {
17+
private static final Logger log = getLogger(HttpRequestUtils.class);
18+
1119
/**
1220
* @param queryString은
1321
* URL에서 ? 이후에 전달되는 field1=value1&field2=value2 형식임
@@ -53,6 +61,24 @@ public static Pair parseHeader(String header) {
5361
return getKeyValue(header, ": ");
5462
}
5563

64+
public static Map<String, String> readHeader(BufferedReader br, String headerFirstLine) throws IOException {
65+
Map<String, String> header = new HashMap<>();
66+
while(!headerFirstLine.equals("") && headerFirstLine != null) {
67+
headerFirstLine = br.readLine();
68+
String[] tokens = headerFirstLine.split(": ");
69+
if(tokens.length == 2) {
70+
header.put(tokens[0], tokens[1]);
71+
}
72+
}
73+
log.debug("header map : {}", header);
74+
return header;
75+
}
76+
77+
public static Map<String, String> readRequestBody(BufferedReader br, int contentLength) throws IOException {
78+
String requestBody = IOUtils.readData(br, contentLength);
79+
return parseQueryString(requestBody);
80+
}
81+
5682
public static class Pair {
5783
String key;
5884
String value;
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package util;
2+
3+
public class HttpResponseHeaderUtils {
4+
public static final String NEW_LINE = System.lineSeparator();
5+
6+
public static String generate200Header(int lengthOfBodyContent) {
7+
StringBuilder sb = new StringBuilder()
8+
.append("HTTP/1.1 200 OK")
9+
.append(NEW_LINE)
10+
.append(generateHtmlContentType())
11+
.append(generateContentLength(lengthOfBodyContent))
12+
.append(NEW_LINE);
13+
return sb.toString();
14+
}
15+
16+
public static String generate302Header(String path) {
17+
StringBuilder sb = new StringBuilder()
18+
.append("HTTP/1.1 302 Found")
19+
.append(NEW_LINE)
20+
.append("Location: ")
21+
.append(path)
22+
.append(NEW_LINE)
23+
.append(generateHtmlContentType())
24+
.append(NEW_LINE);
25+
return sb.toString();
26+
}
27+
28+
public static String generate200CssHeader(int lengthOfBodyContent) {
29+
StringBuilder sb = new StringBuilder()
30+
.append("HTTP/1.1 200 OK")
31+
.append(NEW_LINE)
32+
.append(generateCssContentType())
33+
.append(generateContentLength(lengthOfBodyContent))
34+
.append(NEW_LINE);
35+
return sb.toString();
36+
}
37+
38+
public static String generate302CookieHeader(String path, boolean bool) {
39+
StringBuilder sb = new StringBuilder()
40+
.append("HTTP/1.1 302 Found")
41+
.append(NEW_LINE)
42+
.append("Location: ")
43+
.append(path)
44+
.append(NEW_LINE)
45+
.append(generateHtmlContentType())
46+
.append(generateCookie(bool))
47+
.append(NEW_LINE);
48+
return sb.toString();
49+
}
50+
51+
private static String generateHtmlContentType() {
52+
StringBuilder sb = new StringBuilder()
53+
.append("Content-Type: text/html;charset=utf-8")
54+
.append(NEW_LINE);
55+
return sb.toString();
56+
}
57+
58+
private static String generateCssContentType() {
59+
StringBuilder sb = new StringBuilder()
60+
.append("Content-Type: text/css;charset=utf-8")
61+
.append(NEW_LINE);
62+
return sb.toString();
63+
}
64+
65+
private static String generateContentLength(int lengthOfBodyContent) {
66+
StringBuilder sb = new StringBuilder()
67+
.append("Content-Length: ")
68+
.append(lengthOfBodyContent)
69+
.append(NEW_LINE);
70+
return sb.toString();
71+
}
72+
73+
private static String generateCookie(boolean bool) {
74+
StringBuilder sb = new StringBuilder()
75+
.append("Set-Cookie: logined=")
76+
.append(bool)
77+
.append("; Path=/")
78+
.append(NEW_LINE);
79+
return sb.toString();
80+
}
81+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package util;
2+
3+
import model.User;
4+
5+
import java.util.Collection;
6+
7+
public class HttpResponseHtmlUtils {
8+
public static String generate(Collection<User> users) {
9+
StringBuilder sb = new StringBuilder()
10+
.append("<html>").append(System.lineSeparator())
11+
.append("<body>").append(System.lineSeparator());
12+
for (User user : users) {
13+
sb.append("<p>")
14+
.append(user.toString())
15+
.append("</p>")
16+
.append(System.lineSeparator());
17+
}
18+
sb.append("</body>").append(System.lineSeparator())
19+
.append("</html>");
20+
return sb.toString();
21+
}
22+
}

0 commit comments

Comments
 (0)