spring mvc怎么处理返回值

2025-05-08 13:01:05
推荐回答(2个)
回答1:

  以下是SpringMvc原生支持的返回类型,如果返回Json,可以用Json String或者Map,

  ModelAndView

  Model

  ModelMap

  Map

  View

  String

  Void

  还可以返回类,操作步骤见下面介绍。

  

  需要注意的是,SpringMvc与Jackson结合使用时,如果返回的是一个
Object、或者返回的Map中是Object型的,就需要对Object中的成员变量加注解,否则会报
错:org.springframework.web.HttpMediaTypeNotAcceptableException: Could not
find acceptable representation,500 code error。

  原因是 Jackson 默认情况下不知道怎么去序列化,方法有:

  1.为成员变量增加getter、setter方法

  2. 或者也可以给field加上 @JsonProperty 注解,(也可在getter上加)  , 还能用它指定序列化时的属性名

  

  @JsonProperty可以标注在field或者getter上,

  Defines name of the logical property, i.e.
Json object field name to use for the
property(i.e. @JsonProperty("GID") ): if empty String (which is the
default), will use name of the field that is annotated.

  

  代码示例:

 

 class ItemContent {
  private int gid;
  private int sid;
  private Date createTime;
  private String gname;
  private String name;
  private String nologinUrl;
  
  @JsonProperty
  int getGid() {
  return gid;
  }
  
  void setGid(int gid) {
  this.gid = gid;
  }
  
  @JsonProperty
  int getSid() {
  return sid;
  }
  .............................
  
  @RequestMapping(value = "/dissert/getServerList.do")
  @ResponseBody
  public Object getServerList(HttpServletRequest request) {
  Map resultMap = new HashMap();
  ..................................
  List tempList = new ArrayList();
  for (GameServer gameServer : listServers) {
  ......................
  ItemContent item = new ItemContent();
  item.setGid(gameServer.getGid());
  item.setGname(gameServer.getGname());
  item.setSid(gameServer.getSid());
  item.setName(gameServer.getName());
  item.setCreateTime(gameServer.getCreateTime());
  
  }
  tempList.add(item);
  }
  }
  resultMap.put("open", tempList);
  return resultMap;
  }
  

回答2:

对于springMVC处理方法支持支持一系列的返回方式:
ModelAndView
Model
ModelMap
Map
View
String
Void

具体内容可以参考:https://my.oschina.net/bosscheng/blog/126941