spring mvc 支援如下的返回方式:ModelAndView, Model, ModelMap, Map,View, String, void。
Map
@RequestMapping("/demo2/show")
public Map<String, String> getMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value-1");
map.put("key2", "value-2");
return map;
}
在jsp頁面中可直透過${key1}獲得到值, map.put()相當於request.setAttribute方法。
頁面上這麼寫:
<c:forEach items="${map}" var="entry">
<c:out value="${entry.key}" />
<c:out value="${entry.value}" />
</c:forEach>
返回json的例子(使用Jackson):
@RequestMapping("/load1")
@ResponseBody
public String load1(@RequestParam String name,@RequestParam String password) throws IOException{
System.out.println(name+" : "+password);
//return name+" : "+password;
MyDog dog=new MyDog();
dog.setName("小哈");dog.setAge("1歲");dog.setColor("深灰");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString=objectMapper.writeValueAsString(dog);
System.out.println(jsonString);
return jsonString;
spring mvc 支援如下的返回方式:ModelAndView, Model, ModelMap, Map,View, String, void。
Map
@RequestMapping("/demo2/show")
public Map<String, String> getMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value-1");
map.put("key2", "value-2");
return map;
}
在jsp頁面中可直透過${key1}獲得到值, map.put()相當於request.setAttribute方法。
頁面上這麼寫:
<c:forEach items="${map}" var="entry">
<c:out value="${entry.key}" />
<c:out value="${entry.value}" />
</c:forEach>
返回json的例子(使用Jackson):
@RequestMapping("/load1")
@ResponseBody
public String load1(@RequestParam String name,@RequestParam String password) throws IOException{
System.out.println(name+" : "+password);
//return name+" : "+password;
MyDog dog=new MyDog();
dog.setName("小哈");dog.setAge("1歲");dog.setColor("深灰");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString=objectMapper.writeValueAsString(dog);
System.out.println(jsonString);
return jsonString;
}