복붙노트

[SPRING] 스프링 부트로 JSON 및 HTML 용 컨트롤러

SPRING

스프링 부트로 JSON 및 HTML 용 컨트롤러

나는 다른 것들 중에서 특정 객체에 대해 CRUD 작업을 수행해야하는 응용 프로그램을 작성하고 있습니다. 인간 사용자를 위해 HTML 페이지를 제공하고 다른 애플리케이션을 위해 JSON을 제공 할 수 있어야합니다. 지금 내 URL은 "읽기"와 같습니다.

GET  /foo/{id}      -> Serves HTML
GET  /rest/foo/{id} -> Serves JSON
etc.

이것은 조금 중복 된 것 같습니다. 차라리 이런 식으로하고 싶습니다.

GET /foo/{id}.html OR /foo/{id} -> Serves HTML
GET /foo/{id}.json              -> Serves JSON

스프링 부트로 이것을 할 수 있습니까? 그렇다면 어떻게?

JSON을 반환하는 방법을 알고 있습니다.

@RequestMapping(value = "/foo/{id}", method = RequestMethod.GET, produces = "application/json")
public Object fetch(@PathVariable Long id) {
    return ...;
}

HTML을 반환하는 방법도 알고 있습니다.

@RequestMapping("/app/{page}.html")
String index(@PathVariable String page) {
    if(page == null || page.equals(""))
        page = "index";
    return page;
}

하지만 컨트롤러에 요청에 따라 컨트롤러를 설정하는 방법을 모르겠습니다.

해결법

  1. ==============================

    1.스프링 부트의 기본 동작입니다. 유일한 것은 JSON을 생성하기 위해 @RequestMapping 중 하나를 표시해야한다는 것입니다. 예:

    스프링 부트의 기본 동작입니다. 유일한 것은 JSON을 생성하기 위해 @RequestMapping 중 하나를 표시해야한다는 것입니다. 예:

    @Controller
    class HelloController {
    
        // call http://<host>/hello.json
        @RequestMapping(value = "/hello", method = RequestMethod.GET, produces = "application/json")
        @ResponseBody
        public MyObject helloRest() {
            return new MyObject("hello world");
        }
    
        // call http://<host>/hello.html or just http://<host>/hello 
        @RequestMapping(value = "/hello", method = RequestMethod.GET)
        public String helloHtml(Model model) {
            model.addAttribute("myObject", new MyObject("helloWorld"));
            return "myView";
        }
    }
    

    자세한 내용은 http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc 및 http://spring.io/blog/2013/06/03/content-negotiation- 사용보기

  2. ==============================

    2.사실, 나머지 웹 서비스를 html 페이지와 혼합하는 것은 나쁜 습관입니다. 정말 훌륭한 것을 만들고 싶다면 여기 내 충고가있다. 컨트롤러에 CRUD 작업 만 작성하고 모든 HTML / CSS / js는 정적 폴더에 보관하고 UI 파트를 보려면 정적 index.html 파일을 호출하십시오. 여기에 대한 자세한 내용은 http://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot를 참조하십시오.

    사실, 나머지 웹 서비스를 html 페이지와 혼합하는 것은 나쁜 습관입니다. 정말 훌륭한 것을 만들고 싶다면 여기 내 충고가있다. 컨트롤러에 CRUD 작업 만 작성하고 모든 HTML / CSS / js는 정적 폴더에 보관하고 UI 파트를 보려면 정적 index.html 파일을 호출하십시오. 여기에 대한 자세한 내용은 http://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot를 참조하십시오.

    그러나 만약 당신이 정말로 지금하고있는 일을하고 싶다면, 해결책이 있습니다 :

    @RequestMapping(value = "/foo/{id}", method = RequestMethod.GET)
    public Object serve(final HttpServletRequest req, final HttpServletResponse resp, @PathVariable final Long id) {
        String header = req.getHeader("Accept");
    
        // If Accept header will be text/html - then we are forwarding to jsp page.
        if(header.equals("text/html")) {
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    
        // In other cases we are returning json and setting appropriate headers.
        resp.setHeader("Content-Type", "application/json");
        Object object = "Some string";
    
        return object;
    }
    
  3. from https://stackoverflow.com/questions/27278791/controller-for-json-and-html-with-spring-boot by cc-by-sa and MIT license