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

HTTP 요청을 허용하는 서버 구현 #3

Open
5 tasks done
mjj111 opened this issue May 14, 2024 · 0 comments
Open
5 tasks done

HTTP 요청을 허용하는 서버 구현 #3

mjj111 opened this issue May 14, 2024 · 0 comments
Assignees
Labels

Comments

@mjj111
Copy link
Owner

mjj111 commented May 14, 2024

📄 구현 포인트

  • HTTP 요청에 대한 Enum 추가
  • 쿼리스트링 값을 Map으로 반환하는 메서드를 가진 클래스 구현
  • 받은 Json 값을 QueryString으로 변환하는 클래스 구현
  • POST와 GET 요청에 대해 동적으로 응답할 수 있도록 핸들러 구현
  • 회원 객체 구현

✅ 간략한 코드 설명

1.HTTP 요청에 대한 Enum 추가합니다.
String 값으로 값을 계속해서 비교하기 보다는 미리 Enum으로 선언하여 활용하도록 합니다.

POST("POST"), GET("GET"), PATCH("PATCH"), DELETE("DELETE");

2.요청으로부터 받은 URL에서 쿼리값을 추출합니다.
추출한 값은 = 와 &에 맞춰 key값과 value로 분류하여 Map에 저장하도록 합니다.

    public static Map<String, String> parseQueryString(final String queryString) {
        Map<String, String> result = new HashMap<>();
        String[] splintedQuery = queryString.split("&");

        for(String sentence : splintedQuery) {
            String[] query = sentence.split("=");

            String key = query[0];
            String value = query[1];

            result.put(key, value);
        }

        return result;
    }
  1. requsetBody에 값이 들어올 경우, 값을 파싱해줘야하므로
    받은 Json 값을 QueryString으로 변환하도록 합니다.
public static String readData(final BufferedReader br, final int contentLength) throws IOException {
        char[] body = new char[contentLength];
        br.read(body, 0, contentLength);
        return convertJsonToUrl(String.copyValueOf(body));
    }

    public static String convertJsonToUrl(final String json) {
        StringBuffer sb = new StringBuffer();
        String[] keyValuePairs = json.replaceAll("[{}\"]", "").split(",");

        for (String pair : keyValuePairs) {
            String[] keyValue = pair.split(":");
            String key = keyValue[0].trim();
            String value = keyValue[1].trim();
            sb.append(key).append("=").append(value).append("&");
        }

        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
  1. POST와 GET 요청에 대해 값을 파싱할 수 있도록 분기를 나눠서 적용해줍니다.
 //POST
 if(HttpRequestMethod.POST.equals(method) && url.equals("/users/create")) {

//GET
else if(HttpRequestMethod.GET.equals(method) && url.startsWith("/users")) {
  1. 회원 생성 요청시 파싱하여 받은 값을 기반으로 만들 User 객체를 생성합니다.
public class User {
    private final String userId;
    private final String password;
    private final String name;
    private final String email;
@mjj111 mjj111 added the Feat label May 14, 2024
@mjj111 mjj111 self-assigned this May 14, 2024
mjj111 added a commit that referenced this issue May 14, 2024
@mjj111 mjj111 changed the title 서블릿 컨테이너를 가진 HTTP 기반의 웹서버 구현 HTTP 요청을 허용하는 서버 구현 May 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant