1. web.xml 에서 다음과 같이 처리합니다.

흔히 사용하던 jsp 경로 대신 REST uri경로를 그대로 사용합니다.

<error-page>

    <error-code>404</error-code>

    <location>/errors/404</location>

  </error-page>

  

  <error-page>

    <error-code>405</error-code>

    <location>/errors/405</location>

  </error-page>


2. ErrorController를 작성합니다.

package common.error


import java.util.HashMap;

import java.util.Map;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.springframework.http.HttpStatus;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;


@Controller

public class ErrorController {

private String RESULT_CODE = "result_code";

private String RESULT_MESSAGE = "result_message";

private String HEAD = "head";


@RequestMapping(value = "/errors/{errorCode}", method = RequestMethod.GET)

public ModelAndView error405(@PathVariable("errorCode") int errorCode, HttpServletRequest request, HttpServletResponse response) {

Map<String, Object> responseMap = new HashMap<String, Object>();

Map<String, Object> responseHeadMap = new HashMap<String, Object>();

                //넘겨받은 errorCode에 해당하는 HttpStatus Object를 가져옵니다.

HttpStatus httpStatus = HttpStatus.valueOf(errorCode); 

responseHeadMap.put(RESULT_CODE, httpStatus.value());

responseHeadMap.put(RESULT_MESSAGE, httpStatus.getReasonPhrase());

responseMap.put(HEAD, responseHeadMap);

/*

for (HttpStatus status :HttpStatus.values()) {

System.out.println(status.value() +"," + status.name()+"::" + status.getReasonPhrase());

}

*/

return new ModelAndView("jsonView", responseMap);

}

}


3. 결과는 다음과 같이 리턴합니다. (404/405, 500 등 각각의 error코드에 맞게 error메시지가 리턴됩니다.)

{

    "head": {

        "result_message": "Method Not Allowed",

        "result_code": 405

    }

}


P.S. 위의 리턴타입은 org.springframework.web.servlet.view.BeanNameViewResolver 를 이용하여 MappingJacksonJsonView를 선언하여 처리한 것입니다.

<bean id="beanNameViewResolver" class="org.springframework.web.servlet.view. BeanNameViewResolver" />

<bean id="jsonView" class="org.springframework.web.servlet.view.json. MappingJacksonJsonView">