문제

I have a REST endpoint which currently returns JSON output. I would like to modify the same endpoint to return plain text output, basically differentiate between generating application/json and text/plain Accept headers. Here's my current configuration -

servlet.xml:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="defaultContentType" value="application/json" />
    <property name="ignoreAcceptHeader" value="true" />
    <property name="order" value="0" />
    <property name="mediaTypes">
        <map>
            <entry key="text" value="text/plain" />
            <entry key="json" value="application/json" />
        </map>
    </property>

    <property name="defaultViews">
        <list>
            <ref bean="jsonView"/>
        </list>
    </property>
</bean>

<bean id="jsonView"
      class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="contentType" value="application/json;charset=UTF-8"/>
    <property name="disableCaching" value="false"/>
</bean>

REST endpoint:

@RequestMapping(value = "/emps", method = RequestMethod.GET, produces = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public @ResponseBody List<Employee> getEmpsList() throws VMException {
    final List<Employee> eList = getAllEmployees();
    return eList;
}

I tried modifying produces to {"application/json", "text/plain"}. T read through some online stuff, and since I am returning a bean, I need to use HttpMessageConverter to return text/plain output. I was able to get this work by writing two methods, one returning application/json output and other returning text/plain output. Is it even possible to combine this into single method implementation, or importantly, return result based on requested output format, i.e. json or text.

Thanks in advance for the help.

Update: Attaching image of the the postman client plugin.

Image 1: Image1 Image 2: Image2

도움이 되었습니까?

해결책

Currently you have this:

<property name="ignoreAcceptHeader" value="true" />

In fact, you don't want to ignore the Accept header. Remove that and see what happens.

Also, the mediaTypes are only relevant if you are seeking recources by extension/format, which doesn't seem to be the case here.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top