Spring MVC(@Response Body)에서 응답 콘텐츠 유형을 설정하는 사용자
주석 기반 Spring MVC Java 웹 응용 프로그램을 jetty 웹 서버에서 실행하고 있습니다(현재 maven jetty 플러그인).
String 도움말 텍스트만 반환하는 하나의 컨트롤러 메서드로 AJAX를 지원하려고 합니다.리소스는 UTF-8 인코딩이며 문자열도 UTF-8 인코딩이지만 서버로부터의 응답은 다음과 같습니다.
content-encoding: text/plain;charset=ISO-8859-1 
브라우저가 전송해도
Accept-Charset  windows-1250,utf-8;q=0.7,*;q=0.7
스프링의 디폴트 설정을 사용하고 있습니다.
설정에 이 콩을 추가할 힌트를 찾았습니다만, 인코딩을 지원하지 않고 대신 기본 콩이 사용되고 있기 때문에 사용되지 않는 것 같습니다.
<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;
}
@ResponseBody 주석을 사용하여 Spring 3.1용 솔루션을 찾았습니다.다음으로 Json 출력을 사용하는 컨트롤러의 예를 나타냅니다.
@RequestMapping(value = "/getDealers", method = RequestMethod.GET, 
produces = "application/json; charset=utf-8")
@ResponseBody
public String sendMobileData() {
}
한 StringHttpMessageConverter.  한다. 콩을 넣어야 .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 s,아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아.<mvc:annotation-driven />.
가장 은 v-in-in-in-in-in-time의 입니다.AnnotationMethodHandlerAdapterBeanPostProcessor:
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 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를 사용하는 것이 이것보다 더 좋다고 생각합니다.
추가할 수 있는 결과 = "text/carset;charset=UTF-8"에서 RequestMapping으로
@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는 모든 코멘트가 나타내는 것처럼 매우 간단합니다.
products를 사용하여 컨트롤러에서 보내는 응답 유형을 나타낼 수 있습니다.이 "products" 키워드는 ajax 요청에서 가장 유용하고 내 프로젝트에 큰 도움이 되었습니다.
@RequestMapping(value = "/aURLMapping.htm", method = RequestMethod.GET, produces = "text/html; charset=utf-8") 
public @ResponseBody String getMobileData() {
}
digz666 감사합니다.저는 json을 사용하고 있기 때문에, 당신의 솔루션은 약간의 변경을 가하고 있습니다.
responseHeaders.add("Content-Type", "application/json; charset=utf-8"); 
당신이 추천한 axtavt의 답변은 나에게 효과가 없습니다.올바른 미디어 유형을 추가했더라도:
if(StringHttpMessageConverter의 conv 인스턴스) {((StringHttpMessageConverter) conv).set Supported Media Types()Arrays.asList(새로운 MediaType("text", "html", 문자 집합).이름()의 경우UTF-8")) )새로운 MediaType("어플리케이션", "json", Charset).이름()의 경우UTF-8");}Content Negotiating ViewResolver 빈의 Marshalling View에서 content-type을 설정합니다.쉽고 깔끔하며 원활하게 작동합니다.
<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>
web.xml로 설정된 Character Encoding Filter를 사용하고 있습니다.그게 도움이 될지도 몰라
    <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"에서 Ajax 요청을 하려고 하지 않았다면, 그것은 나에게 잘 먹혔을 것입니다.위의 어떤 것도 그렇지 않았다.character Encoding Filter도 가지고 있습니다.
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>
어떤 것도 덮어쓰거나 구현할 필요가 없습니다.
이 문제를 해결하려면 , 다음의 설정을 사용해 주세요.
<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>
모든 *.xml 파일에 mvc:drivation-driven 태그가 하나만 있는지 확인해야 합니다.그렇지 않으면 설정이 유효하지 않을 수 있습니다.
「문자 인코딩이 지정되어 있지 않은 경우, 서블릿 사양에서는 ISO-8859-1의 인코딩을 사용할 필요가 있습니다.」라고 하는 링크에 따라서,spring 3.1 이후를 사용하는 경우, 예비 구성을 사용하여 charset=을 설정합니다.응답 본체에 UTF-8 연결
 @RequestMapping(값 = "your mapping url"), = "text/mapping;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;
        }
    }
}
설정 예:
    <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
'programing' 카테고리의 다른 글
| v-model이 null인 경우 Vue.js에서 확인란 값을 false로 설정합니다. (0) | 2022.10.30 | 
|---|---|
| JPA 엔티티 메타모델 생성 방법 (0) | 2022.10.30 | 
| Python에서 변수와 문자열을 같은 줄에 인쇄하려면 어떻게 해야 하나요? (0) | 2022.10.30 | 
| Ajax 요청을 사용하여 파일 다운로드 (0) | 2022.10.30 | 
| 이 외부 키 제약 조건이 잘못 형성된 이유는 무엇입니까? (0) | 2022.10.30 |