【问题标题】:Spring @RestController Get Request Content-Type to response json or htmlSpring @RestController 获取请求内容类型以响应 json 或 html
【发布时间】:2015-07-27 07:45:17
【问题描述】:

如何获取请求的 Content-Type 值?我们需要它来打印 json 响应或 Html 响应。我的代码是这样的:

 @RestController
public class GestorController {
    @RequestMapping(value="/gestores", method = RequestMethod.GET)  
    public Object gestoresHtml(@RequestParam(value="name", required=false, defaultValue="sh14") String name) throws Exception {
        String json = "prueba json";

        String contentType = ?????

        if(contentType.equals("application/json")){
            return json;
        }else{
            ModelAndView mav = new ModelAndView();
            mav.setViewName("gestores");
            mav.addObject("name", name);
            return mav;
        }
    }
}

谢谢大家。

【问题讨论】:

    标签: spring-mvc spring-restcontroller


    【解决方案1】:

    Content-Type是一个请求头,你可以通过以下代码获取:

        @RequestMapping("/display")
        public void display(@RequestHeader("Content-Type") String contentType)  {}
    

    见春天的@RequestHeaderdocs

    您无需手动执行此操作。你需要的是Content negotiation。它返回适合您需求的响应类型。看到这个post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多