Jon*_*eto 2 spring-mvc spring-restcontroller
如何获取请求 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢大家。
Content-Type 是一个请求头,您可以使用以下代码获取:
@RequestMapping("/display")
public void display(@RequestHeader("Content-Type") String contentType) {}
Run Code Online (Sandbox Code Playgroud)
查看 spring 的@RequestHeader 文档
您无需手动执行此操作。你需要的是Content negotiation。这将返回适合您需求的响应类型。看到这个帖子
| 归档时间: |
|
| 查看次数: |
9970 次 |
| 最近记录: |