[에러노트] [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported]

hyewon jeong·2024년 6월 26일
0

에러노트

목록 보기
42/46

1 발생

전자정부프레임워크 구현 중 , ajax를 통해 서버 요청 시 이러한 에러가 발생했다.


2 코드

ajax:function(url,ajaxParam,fn_success,fn_complete){

  //            var header = $("meta[name='_csrf_header']").attr("content");
  //            var token = $("meta[name = '_csrf']").attr.("content");/// 

  $.ajax({
    url : url,
    type : 'POST',
    contentType : "application/json",
    data : JSON.stringify(ajaxParam),
    dataType : "json",
    //                beforeSend:function(xhr){
    //                xhr.setRequestHeader(header,token);
    //                    if(isLoadingBool){
    //                        loader.isLoading();
    //                    }
    //                },
    success : function(data){
      if(fn_success != null || fn_success != undefined){
        fn_success(data);
      }
    },
    error: function(request,status, error){
      alert("code:"+request.status+ "\n"+"message:"+request.responseText+"\n"+"error:"+error);
    },
    complete: function(){

      if(fn_complete != null || fn_complete != undefined){
        fn_complete(xhr);
      }
    }
  });
},

3 원인

json 바인딩 해주는 라이브러리가 없어서 json에 대한 데이터 처리를 하지 못했다.


4 해결

  1. 의존성 추가
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version> <!-- 적절한 버전으로 변경 -->
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.3</version> <!-- 적절한 버전으로 변경 -->
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.12.3</version> <!-- 적절한 버전으로 변경 -->
        </dependency>
  1. dispatcher-servlet.xml

    <bean id="htmlEscapeTag"
          class="kr.or.woniProject.cmmn.sys.service.HtmlEscapingObjectMapperFactory" />
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
                <property name="objectMapper" ref="htmlEscapeTag"></property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
  1. HtmlEscapingObjectMapperFactory

public class HtmlEscapingObjectMapperFactory implements FactoryBean<ObjectMapper> {

    private final ObjectMapper objectMapper;


    public HtmlEscapingObjectMapperFactory() {
        objectMapper = new ObjectMapper();
        objectMapper.getFactory().setCharacterEscapes(new HTMLCharacterEscapes());
//        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public ObjectMapper getObject()  {
        return objectMapper;
    }

    @Override
    public Class<?> getObjectType() {
        return ObjectMapper.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    public static class HTMLCharacterEscapes extends CharacterEscapes {

        private final int[] asciiEscapes;

        private final CharSequenceTranslator charSequenceTranslator;

        public HTMLCharacterEscapes() {
            asciiEscapes = CharacterEscapes.standardAsciiEscapesForJSON();

            asciiEscapes['<'] = CharacterEscapes.ESCAPE_CUSTOM;
            asciiEscapes['>'] = CharacterEscapes.ESCAPE_CUSTOM;
//            asciiEscapes['&'] = CharacterEscapes.ESCAPE_CUSTOM;
//            asciiEscapes['"'] = CharacterEscapes.ESCAPE_CUSTOM;
//            asciiEscapes['\''] = CharacterEscapes.ESCAPE_CUSTOM;


            charSequenceTranslator = new AggregateTranslator(new LookupTranslator(EntityArrays.BASIC_ESCAPE()), new LookupTranslator((EntityArrays.ISO8859_1_ESCAPE())), new LookupTranslator(EntityArrays.HTML40_EXTENDED_ESCAPE()), new LookupTranslator(new String[][]{{"(", "&#40;"}, {")", "&#41;"}, {"#", "&#35;"}, {"\'", "&#39;"}}));

        }

        @Override
        public int[] getEscapeCodesForAscii() {
            int[] lAsciiEscapes =  asciiEscapes;
            return lAsciiEscapes;
        }

        @Override
        public SerializableString getEscapeSequence(int i) {
            return new SerializedString(StringEscapeUtils.escapeHtml4(Character.toString((char) i)));
        }
    }
}

profile
개발자꿈나무

0개의 댓글