Skip to content

Commit

Permalink
[#3] feat: ☁️ ReturnValueHandler 를 통해서 view 를 Resolve 하거나 리다이렉션을 할 수 …
Browse files Browse the repository at this point in the history
…있도록 했습니다.
tmdgusya committed Mar 30, 2021
1 parent 25853e2 commit e368189
Showing 8 changed files with 287 additions and 127 deletions.
67 changes: 67 additions & 0 deletions src/main/java/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package controller;

import core.HttpRequest;
import core.HttpResponse;
import db.DataBase;
import handler.mapping.Controller;
import handler.mapping.GetMapping;
import handler.mapping.PostMapping;
import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.HttpRequestUtils;
import util.IOUtils;
import util.ResponseData;

import java.io.DataOutputStream;
import java.util.Map;

@Controller
public class UserController {

private final static Logger log = LoggerFactory.getLogger(UserController.class);

public UserController() {
}

@GetMapping(url = "/")
public String root(HttpRequest httpRequest, HttpResponse httpResponse) {
return "index.html";
}

@PostMapping(url = "/users")
public String createUser(HttpRequest httpRequest, HttpResponse httpResponse) {

final Map<String, String> parameters = httpRequest.getRequestBody();

User user = new User(parameters.get("userId"), parameters.get("password"), parameters.get("name"), parameters.get("email"));
log.debug("User : {}" , user);

DataBase.addUser(user);

DataOutputStream dos = new DataOutputStream(httpResponse.getOut());
return "redirect:/";
}

@GetMapping(url = "/users")
public String getUsers(HttpRequest httpRequest, HttpResponse httpResponse) {
log.info("12312312312");
return "index.html";
}

@GetMapping(url = "/users/form")
public String createUserForm(HttpRequest httpRequest, HttpResponse httpResponse) {
return "user/form.html";
}

@GetMapping(url = "/users/login")
public String login(HttpRequest httpRequest, HttpResponse httpResponse) {
return "user/login.html";
}

@GetMapping(url = "/users/profile")
public String profile(HttpRequest httpRequest, HttpResponse httpResponse) {
return "user/profile.html";
}

}
14 changes: 14 additions & 0 deletions src/main/java/handler/mapping/PostMapping.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package handler.mapping;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PostMapping {

String url() default "";

}
88 changes: 88 additions & 0 deletions src/main/java/handler/returnValueHandle/ReturnValueHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package handler.returnValueHandle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ReturnValueHandler {

private static final Logger log = LoggerFactory.getLogger(ReturnValueHandler.class);

private final String returnValue;
private final DataOutputStream dos;

private static final String PREFIX = "./webapp/";

public ReturnValueHandler(Object returnValue, DataOutputStream dos) {
this.returnValue = (String) returnValue;
this.dos = dos;
}

public void handle() throws IOException {
if(returnValue.startsWith("redirect")) {
String url = returnValue.split(":")[1];
response302Header(dos, url);
}else {
byte[] body = Files.readAllBytes(new File(PREFIX + returnValue).toPath());
response200Header(dos, body.length);
responseBody(dos, body);
}
}

private void response302HeaderWithCookies(DataOutputStream dos, String location, String cookie) {
try {
dos.writeBytes("HTTP/1.1 302 \r\n");
dos.writeBytes(String.format("Location: %s \r\n", location));
dos.writeBytes(String.format("Set-Cookie: %s \r\n", cookie));
dos.writeBytes("\r\n");
} catch (IOException e) {
log.error(e.getMessage());
}
}

private void response200HeaderWithCss(DataOutputStream dos, int length) {
try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/css;charset=utf-8 \r\n");
dos.writeBytes(String.format("Content-Length: %d \r\n", length));
dos.writeBytes("\r\n");
} catch (IOException e) {
log.error(e.getMessage());
}
}

private void response302Header(DataOutputStream dos, String location) {
try {
dos.writeBytes("HTTP/1.1 302 \r\n");
dos.writeBytes(String.format("Location: %s \r\n", location));
dos.writeBytes("\r\n");
} catch (IOException e) {
log.error(e.getMessage());
}
}

private void response200Header(DataOutputStream dos, int lengthOfBodyContent) {
try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n");
dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
dos.writeBytes("\r\n");
} catch (IOException e) {
log.error(e.getMessage());
}
}

private void responseBody(DataOutputStream dos, byte[] body) {
try {
dos.write(body, 0, body.length);
dos.flush();
} catch (IOException e) {
log.error(e.getMessage());
}
}

}
67 changes: 67 additions & 0 deletions src/main/java/util/ResponseData.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.DataOutputStream;
import java.io.IOException;

public class ResponseData {

private static final Logger log = LoggerFactory.getLogger(ResponseData.class);

public static void response200Header(DataOutputStream dos, int lengthOfBodyContent) {
try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n");
dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
dos.writeBytes("\r\n");
} catch (IOException e) {
log.error(e.getMessage());
}
}

public static void response200HeaderWithCss(DataOutputStream dos, int lengthOfBodyContent) {
try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/css;charset=utf-8\r\n");
dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
dos.writeBytes("\r\n");
} catch (IOException e) {
log.error(e.getMessage());
}
}

public static void response302Header(DataOutputStream dos, String location) {
log.debug("location : {}", location);
try {
dos.writeBytes("HTTP/1.1 302 Found \r\n"); // 원래는 200
dos.writeBytes("Location: " + location+"\r\n");
dos.writeBytes("\r\n");
} catch (IOException e) {
log.error(e.getMessage());
}
}

public static void response302HeaderWithCookie(DataOutputStream dos, String location, String cookie) {
log.debug("location : {}", location);
try {
dos.writeBytes("HTTP/1.1 302 Found \r\n"); // 원래는 200
dos.writeBytes("Location: " + location+"\r\n");
dos.writeBytes("Set-Cookie: " + cookie + "\r\n");
dos.writeBytes("\r\n");
} catch (IOException e) {
log.error(e.getMessage());
}
}

public static void responseBody(DataOutputStream dos, byte[] body) {
try {
dos.write(body, 0, body.length);
dos.flush();
} catch (IOException e) {
log.error(e.getMessage());
}
}

}
114 changes: 0 additions & 114 deletions src/main/java/webserver/RequestHandler.java

This file was deleted.

11 changes: 0 additions & 11 deletions src/main/java/webserver/RequestMethod.java

This file was deleted.

49 changes: 49 additions & 0 deletions src/main/java/webserver/WebCat.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package webserver;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

import core.HttpRequest;
import core.HttpResponse;
import handler.mapping.MappingUrlHandler;
import handler.returnValueHandle.ReturnValueHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebCat extends Thread {

private static final Logger log = LoggerFactory.getLogger(WebCat.class);

private Socket connection;

public WebCat(Socket connectionSocket) {
this.connection = connectionSocket;
}

public void run() {
log.debug("New Client Connect! Connected IP : {}, Port : {}", connection.getInetAddress(), connection.getPort());

try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {
HttpRequest httpRequest = new HttpRequest(in);
httpRequest.run();
HttpResponse httpResponse = new HttpResponse(out);
MappingUrlHandler mappingUrlHandler = new MappingUrlHandler(httpRequest.getMethod(), httpRequest.getUrl());
DataOutputStream dos = new DataOutputStream(out);
try {
Object returnValue = mappingUrlHandler.invokeMethod(httpRequest, httpResponse);
//TODO 여기서 returnValue 를 resolve 하는 방식을 찾아야 한다.
ReturnValueHandler returnValueHandler = new ReturnValueHandler(returnValue, dos);
returnValueHandler.handle();
} catch (IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException | InstantiationException e) {
e.printStackTrace();
}
log.info(httpRequest.toString());
log.info(httpResponse.toString());
} catch (IOException e) {
e.printStackTrace();
}

}

}
4 changes: 2 additions & 2 deletions src/main/java/webserver/WebServer.java
Original file line number Diff line number Diff line change
@@ -26,8 +26,8 @@ public static void main(String args[]) throws Exception {
// 클라이언트가 연결될때까지 대기한다.
Socket connection;
while ((connection = listenSocket.accept()) != null) {
RequestHandler requestHandler = new RequestHandler(connection);
requestHandler.start();
WebCat webCat = new WebCat(connection);
webCat.start();
}
}
}

0 comments on commit e368189

Please sign in to comment.