繁体   English   中英

在Spring MVC中,如何在使用@ResponseBody时设置mime类型头

[英]In Spring MVC, how can I set the mime type header when using @ResponseBody

我有一个Spring MVC Controller,它返回一个JSON String,我想将mimetype设置为application / json。 我怎样才能做到这一点?

@RequestMapping(method=RequestMethod.GET, value="foo/bar")
@ResponseBody
public String fooBar(){
    return myService.getJson();
}

业务对象已经可以作为JSON字符串使用,因此使用MappingJacksonJsonView不是我的解决方案。 @ResponseBody是完美的,但我怎样才能设置mimetype?

使用ResponseEntity而不是ResponseBody 这样您就可以访问响应标头,并可以设置适当的内容类型。 根据Spring文档

HttpEntity类似于@RequestBody@ResponseBody 除了访问请求和响应主体之外, HttpEntity (以及特定于响应的子类ResponseEntity )还允许访问请求和响应头

代码如下所示:

@RequestMapping(method=RequestMethod.GET, value="/fooBar")
public ResponseEntity<String> fooBar2() {
    String json = "jsonResponse";
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}

我会考虑重构服务以返回您的域对象而不是JSON字符串,并让Spring处理序列化(在编写时通过MappingJacksonHttpMessageConverter )。 从Spring 3.1开始,实现看起来非常简洁:

@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, 
    method = RequestMethod.GET
    value = "/foo/bar")
@ResponseBody
public Bar fooBar(){
    return myService.getBar();
}

评论:

首先,必须将<mvc:annotation-driven />@EnableWebMvc 添加到应用程序配置中。

接着,将产生的的属性@RequestMapping注释用于指定响应的内容类型。 因此,它应设置为MediaType.APPLICATION_JSON_VALUE (或"application/json" )。

最后,必须添加Jackson,以便Spring和Spring自动处理Java和JSON之间的任何序列化和反序列化(Spring将检测到Jackson依赖,并且MappingJacksonHttpMessageConverter将在引擎盖下)。

您可能无法使用@ResponseBody执行此操作,但这样的操作应该有效:

package xxx;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class FooBar {
  @RequestMapping(value="foo/bar", method = RequestMethod.GET)
  public void fooBar(HttpServletResponse response) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(myService.getJson().getBytes());
    response.setContentType("application/json");
    response.setContentLength(out.size());
    response.getOutputStream().write(out.toByteArray());
    response.getOutputStream().flush();
  }
}

我不认为这是可能的。 似乎有一个开放的Jira:

SPR-6702:在@ResponseBody中明确设置响应Content-Type

org.springframework.http.converter.json.MappingJacksonHttpMessageConverter注册为消息转换器并直接从方法返回对象。

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="webBindingInitializer">
    <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"/>
  </property>
  <property name="messageConverters">
    <list>
      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
    </list>
  </property>
</bean>

和控制器:

@RequestMapping(method=RequestMethod.GET, value="foo/bar")
public @ResponseBody Object fooBar(){
    return myService.getActualObject();
}

这需要依赖org.springframework:spring-webmvc

我不认为你可以,除了response.setContentType(..)

我的现实版本。 加载HTML文件并流式传输到浏览器。

@Controller
@RequestMapping("/")
public class UIController {

    @RequestMapping(value="index", method=RequestMethod.GET, produces = "text/html")
    public @ResponseBody String GetBootupFile() throws IOException  {
        Resource resource = new ClassPathResource("MainPage.html");
        String fileContents = FileUtils.readFileToString(resource.getFile());
        return fileContents;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM