IT박스

Spring MVC에서 응답 컨텐츠 유형을 설정하는 사람 (@ResponseBody)

itboxs 2020. 7. 13. 21:42
반응형

Spring MVC에서 응답 컨텐츠 유형을 설정하는 사람 (@ResponseBody)


Annotation 기반의 Spring MVC Java 웹 응용 프로그램을 부두 웹 서버 (현재 maven jetty plugin)에서 실행하고 있습니다.

String 도움말 텍스트 만 반환하는 하나의 컨트롤러 메소드로 AJAX 지원을하려고합니다. 리소스는 UTF-8 인코딩이며 문자열도 있지만 서버의 응답은 다음과 같습니다.

content-encoding: text/plain;charset=ISO-8859-1 

브라우저가 전송하더라도

Accept-Charset  windows-1250,utf-8;q=0.7,*;q=0.7

어떻게 든 스프링의 기본 구성을 사용하고 있습니다.

이 Bean을 구성에 추가하는 힌트를 찾았지만 인코딩을 지원하지 않고 대신 기본 Bean이 사용되기 때문에 사용되지 않았다고 생각합니다.

<bean class="org.springframework.http.converter.StringHttpMessageConverter">
    <property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>

내 컨트롤러 코드는 다음과 같습니다 (이 응답 유형 변경은 저에게 효과적이지 않습니다).

@RequestMapping(value = "ajax/gethelp")
public @ResponseBody String handleGetHelp(Locale loc, String code, HttpServletResponse response) {
    log.debug("Getting help for code: " + code);
    response.setContentType("text/plain;charset=UTF-8");
    String help = messageSource.getMessage(code, null, loc);
    log.debug("Help is: " + help);
    return help;
}

StringHttpMessageConverterBean 의 간단한 선언으로는 충분하지 않으므로 다음에 삽입해야합니다 AnnotationMethodHandlerAdapter.

<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
            </bean>
        </array>
    </property>
</bean>

그러나이 방법을 사용하면 모든을 재정의해야하며 HttpMessageConverter작동하지 않습니다 <mvc:annotation-driven />.

따라서 가장 편리하지만 못생긴 방법은 AnnotationMethodHandlerAdapterwith의 인스턴스를 가로채는 것 입니다 BeanPostProcessor.

public class EncodingPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String name)
            throws BeansException {
        if (bean instanceof AnnotationMethodHandlerAdapter) {
            HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
            for (HttpMessageConverter<?> conv: convs) {
                if (conv instanceof StringHttpMessageConverter) {
                    ((StringHttpMessageConverter) conv).setSupportedMediaTypes(
                        Arrays.asList(new MediaType("text", "html", 
                            Charset.forName("UTF-8"))));
                }
            }
        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String name)
            throws BeansException {
        return bean;
    }
}

-

<bean class = "EncodingPostProcessor " />

Spring 3.1에 대한 솔루션을 찾았습니다. @ResponseBody 주석을 사용하여. 다음은 Json 출력을 사용하는 컨트롤러의 예입니다.

@RequestMapping(value = "/getDealers", method = RequestMethod.GET, 
produces = "application/json; charset=utf-8")
@ResponseBody
public String sendMobileData() {

}

Spring MVC 3.1에서는 MVC 네임 스페이스를 사용하여 메시지 변환기를 구성 할 수 있습니다.

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

또는 코드 기반 구성 :

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  private static final Charset UTF8 = Charset.forName("UTF-8");

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
    stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
    converters.add(stringConverter);

    // Add other converters ...
  }
}

다음과 같은 방법으로 인코딩을 설정할 수도 있습니다.

@RequestMapping(value = "ajax/gethelp")
public ResponseEntity<String> handleGetHelp(Locale loc, String code, HttpServletResponse response) {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "text/html; charset=utf-8");

    log.debug("Getting help for code: " + code);
    String help = messageSource.getMessage(code, null, loc);
    log.debug("Help is: " + help);

    return new ResponseEntity<String>("returning: " + help, responseHeaders, HttpStatus.CREATED);
}

StringHttpMessageConverter를 사용하는 것이 이것보다 낫다고 생각합니다.


RequestMapping에 produce = "text / plain; charset = UTF-8"을 추가 할 수 있습니다

@RequestMapping(value = "/rest/create/document", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String create(Document document, HttpServletRespone respone) throws UnsupportedEncodingException {

    Document newDocument = DocumentService.create(Document);

    return jsonSerializer.serialize(newDocument);
}

자세한 내용은이 블로그를 참조하십시오


나는 최근 에이 문제와 싸우고 있었고 Spring 3.1에서 훨씬 더 나은 대답을 찾았습니다.

@RequestMapping(value = "ajax/gethelp", produces = "text/plain")

따라서 모든 의견과 마찬가지로 JAX-RS만큼 쉽게 할 수 있습니다.


감사합니다 digz6666, 귀하의 솔루션은 json을 사용하고 있기 때문에 약간의 변경 사항이 있습니다.

responseHeaders.add ( "Content-Type", "application / json; charset = utf-8");

axtavt의 답변 (권장)은 저에게 효과적이지 않습니다. 올바른 매체 유형을 추가 한 경우에도 :

if (conv instanceof StringHttpMessageConverter) {                   
                    ((StringHttpMessageConverter) 전환) .setSupportedMediaTypes (
                        Arrays.asList (
                                새로운 MediaType ( "text", "html", Charset.forName ( "UTF-8")),
                                새로운 MediaType ( "application", "json", Charset.forName ( "UTF-8"))));
                }

ContentNegotiatingViewResolver Bean 의 MarshallingView에서 컨텐츠 유형을 설정했습니다 . 쉽고 깨끗하고 부드럽게 작동합니다.

<property name="defaultViews">
  <list>
    <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
      <constructor-arg>
        <bean class="org.springframework.oxm.xstream.XStreamMarshaller" />     
      </constructor-arg>
      <property name="contentType" value="application/xml;charset=UTF-8" />
    </bean>
  </list>
</property>

농작물을 사용하여 컨트롤러에서 보내는 응답의 유형을 나타낼 수 있습니다. 이 "produces"키워드는 아약스 요청에서 가장 유용하며 내 프로젝트에서 매우 유용했습니다.

@RequestMapping(value = "/aURLMapping.htm", method = RequestMethod.GET, produces = "text/html; charset=utf-8") 

public @ResponseBody String getMobileData() {

}

web.xml에 구성된 CharacterEncodingFilter를 사용하고 있습니다. 아마 도움이 될 것입니다.

    <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

위의 어느 것도 효과가 없다면 "GET"이 아닌 "POST"에 대한 아약스 요청을 시도하면 나에게 잘 작동했습니다 ... 위의 어느 것도하지 않았습니다. characterEncodingFilter도 있습니다.


package com.your.package.spring.fix;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author Szilard_Jakab (JaKi)
 * Workaround for Spring 3 @ResponseBody issue - get incorrectly 
   encoded parameters     from the URL (in example @ JSON response)
 * Tested @ Spring 3.0.4
 */
public class RepairWrongUrlParamEncoding {
    private static String restoredParamToOriginal;

    /**
    * @param wrongUrlParam
    * @return Repaired url param (UTF-8 encoded)
    * @throws UnsupportedEncodingException
    */
    public static String repair(String wrongUrlParam) throws 
                                            UnsupportedEncodingException {
    /* First step: encode the incorrectly converted UTF-8 strings back to 
                  the original URL format
    */
    restoredParamToOriginal = URLEncoder.encode(wrongUrlParam, "ISO-8859-1");

    /* Second step: decode to UTF-8 again from the original one
    */
    return URLDecoder.decode(restoredParamToOriginal, "UTF-8");
    }
}

이 문제에 대한 많은 해결 방법을 시도한 후이 문제를 해결하고 제대로 작동했습니다.


Spring 3.1.1에서이 문제를 해결하는 간단한 방법은 다음과 같습니다. servlet-context.xml

    <annotation-driven>
    <message-converters register-defaults="true">
    <beans:bean class="org.springframework.http.converter.StringHttpMessageConverter">
    <beans:property name="supportedMediaTypes">    
    <beans:value>text/plain;charset=UTF-8</beans:value>
    </beans:property>
    </beans:bean>
    </message-converters>
    </annotation-driven>

Don't need to override or implement anything.


if you decide to fix this problem through the following configuration:

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

you should confirm that there should only one mvc:annotation-driven tag in all your *.xml file. otherwise, the configuration may not be effective.


According to the link " If a character encoding is not specified, the Servlet specification requires that an encoding of ISO-8859-1 is used ".If you are using spring 3.1 or later use the fallowing configuration to set charset=UTF-8 to response body
@RequestMapping(value = "your mapping url", produces = "text/plain;charset=UTF-8")


public final class ConfigurableStringHttpMessageConverter extends AbstractHttpMessageConverter<String> {

    private Charset defaultCharset;

    public Charset getDefaultCharset() {
        return defaultCharset;
    }

    private final List<Charset> availableCharsets;

    private boolean writeAcceptCharset = true;

    public ConfigurableStringHttpMessageConverter() {
        super(new MediaType("text", "plain", StringHttpMessageConverter.DEFAULT_CHARSET), MediaType.ALL);
        defaultCharset = StringHttpMessageConverter.DEFAULT_CHARSET;
        this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
    }

    public ConfigurableStringHttpMessageConverter(String charsetName) {
        super(new MediaType("text", "plain", Charset.forName(charsetName)), MediaType.ALL);
        defaultCharset = Charset.forName(charsetName);
        this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
    }

    /**
     * Indicates whether the {@code Accept-Charset} should be written to any outgoing request.
     * <p>Default is {@code true}.
     */
    public void setWriteAcceptCharset(boolean writeAcceptCharset) {
        this.writeAcceptCharset = writeAcceptCharset;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return String.class.equals(clazz);
    }

    @Override
    protected String readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException {
        Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
        return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
    }

    @Override
    protected Long getContentLength(String s, MediaType contentType) {
        Charset charset = getContentTypeCharset(contentType);
        try {
            return (long) s.getBytes(charset.name()).length;
        }
        catch (UnsupportedEncodingException ex) {
            // should not occur
            throw new InternalError(ex.getMessage());
        }
    }

    @Override
    protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException {
        if (writeAcceptCharset) {
            outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
        }
        Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
        FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), charset));
    }

    /**
     * Return the list of supported {@link Charset}.
     *
     * <p>By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses.
     *
     * @return the list of accepted charsets
     */
    protected List<Charset> getAcceptedCharsets() {
        return this.availableCharsets;
    }

    private Charset getContentTypeCharset(MediaType contentType) {
        if (contentType != null && contentType.getCharSet() != null) {
            return contentType.getCharSet();
        }
        else {
            return defaultCharset;
        }
    }
}

Sample configuration :

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <util:list>
                <bean class="ru.dz.mvk.util.ConfigurableStringHttpMessageConverter">
                    <constructor-arg index="0" value="UTF-8"/>
                </bean>
            </util:list>
        </property>
    </bean>

참고URL : https://stackoverflow.com/questions/3616359/who-sets-response-content-type-in-spring-mvc-responsebody

반응형