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

[MVC 구현하기 - 3단계] 에코(조은찬) 미션 제출합니다. #626

Merged
merged 8 commits into from
Sep 28, 2023
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
feat: JSON View render 구현
  • Loading branch information
echo724 committed Sep 25, 2023
commit 0c7d549c45d966d77d21b919e79e9256b967593d
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@
@Controller
public class RegisterViewController {

@RequestMapping(value = "/register/view", method = RequestMethod.GET)
@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView execute(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
return ModelAndView.fromJspViewName("/register.jsp");
}
32 changes: 32 additions & 0 deletions app/src/main/java/com/techcourse/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.techcourse.controller;

import com.techcourse.domain.User;
import com.techcourse.repository.InMemoryUserRepository;
import context.org.springframework.stereotype.Controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.org.springframework.web.bind.annotation.RequestMapping;
import web.org.springframework.web.bind.annotation.RequestMethod;
import webmvc.org.springframework.web.servlet.ModelAndView;
import webmvc.org.springframework.web.servlet.view.JsonView;

@Controller
public class UserController {

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

@RequestMapping(value = "/api/user", method = RequestMethod.GET)
public ModelAndView show(HttpServletRequest request, HttpServletResponse response) {
final String account = request.getParameter("account");
log.debug("user id : {}", account);

final ModelAndView modelAndView = new ModelAndView(new JsonView());
final User user = InMemoryUserRepository.findByAccount(account)
.orElseThrow();

modelAndView.addObject("user", user);
return modelAndView;
}
}
wugawuga marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -42,11 +42,10 @@ public void initialize() {
private void addHandlerExecutions(Map<Class<?>, Object> controllerMapper, final Method method, final RequestMapping requestMapping) {
final String requestURI = requestMapping.value();
List<HandlerKey> handlerKeys = mapHandlerKeys(requestURI, requestMapping.method());
handlerKeys.stream()
.forEach(handlerKey -> {
final Object instance = controllerMapper.get(method.getDeclaringClass());
handlerExecutions.put(handlerKey, new HandlerExecution(instance, method));
});
handlerKeys.forEach(handlerKey -> {
final Object instance = controllerMapper.get(method.getDeclaringClass());
handlerExecutions.put(handlerKey, new HandlerExecution(instance, method));
});
}

private List<HandlerKey> mapHandlerKeys(final String requestURI, final RequestMethod[] methods) {
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package webmvc.org.springframework.web.servlet.view;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import webmvc.org.springframework.web.servlet.View;
@@ -10,6 +11,16 @@ public class JsonView implements View {

@Override
public void render(final Map<String, ?> model, final HttpServletRequest request, HttpServletResponse response) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
String json = "";
if (model.size() == 1) {
json = objectMapper.writeValueAsString(model.get(model.keySet().iterator().next()));
} else {
json = objectMapper.writeValueAsString(model);
}
Comment on lines +23 to +28
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분 분리를 한다면 getModelMessage() 라던가?

더 가독성이 높아질 것 같은데 에코 의견이 궁금합니다.

render 안에서 response 세팅과 model json 을 만드는 과정이 어색하지는 않지만, 에코의 의견이 궁금해요!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

음 아무래도 render라는 메서드에 json body 생성, Response header 설정, Response에 body 작성 등 여러 작업을 하더라구요! 그래서 우가 얘기해주신대로 분리가 가능할 것 같았고, 해당 부분은 아래와 같이 createJsonBody 메서드로 분리했습니다! 확실히 가독성이 좋아졌네요 ㅎㅎ

private String createJsonBody(final Map<String, ?> model) throws JsonProcessingException {
        final ObjectMapper objectMapper = new ObjectMapper();
        String json = "";
        if (model.size() == 1) {
            json = objectMapper.writeValueAsString(model.get(model.keySet().iterator().next()));
        } else {
            json = objectMapper.writeValueAsString(model);
        }
        return json;
    }

response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(json);
}

@Override