返回的内容会变成地址,但如果想返回字符串,就用@ResponseBody

package cn.java.controller.front;

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

@Controller
public class TestController {

    //正常xml中是有前缀后缀的,返回为/pages/front/hello springMVC.jsp,那么想只返回字符串,那就加@ResponseBody
    @RequestMapping("test1")
    @ResponseBody
    public String test1() {
        return "hello springMVC"; 
    }
}

使用@ResponseBody注解,访问的时候后缀不能以.html或者.htm最为结尾。可以.shtml或者.do

 

 

@ResponseBody可以返回任意类型。boolean类型、自己创建的类型等。。。

但要先导入jar包到lib:复制粘贴就行

然后就可以返回所有类型:

    @RequestMapping("beanToJson")
    @ResponseBody
    public User beanToJson() {
        User user = new User();
        user.setUsername("james");
        user.setPassword("123");
        user.setAge(10);
        return user;
    }

http://localhost:8080/springMVC/beanToJson.shtml中显示的是{"username":"james","password":"123","age":10}

 

返回Map类型

    @RequestMapping("mapToJson")
    @ResponseBody
    public Map<String,Object> mapToJson() {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("数学", "80分");
        map.put("语文", "50分");
        return map;
    }

http://localhost:8080/springMVC/mapToJson.shtml中显示的是:{"数学":"80分","语文":"50分"}

 

返回List<Map<String,Object>>

    @RequestMapping("listToJson")
    @ResponseBody
    public List<Map<String,Object>> listToJson() {
        Map<String,Object> map1 = new HashMap<String,Object>();
        map1.put("数学", "80分");
        map1.put("语文", "50分");
        
        Map<String,Object> map2 = new HashMap<String,Object>();
        map2.put("物理", "70分");
        map2.put("化学", "10分");
        
        List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
        mapList.add(map1);
        mapList.add(map2);
        return mapList;
    }

结果:[{"数学":"80分","语文":"50分"},{"物理":"70分","化学":"10分"}]

 

posted on 2018-06-04 16:04  lonske  阅读(171)  评论(0编辑  收藏  举报