栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaWeb学习笔记(十一):SpringMVC数据响应

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaWeb学习笔记(十一):SpringMVC数据响应

  • 前面学习了SpringMvc项目的简单搭建
  • 今天天学springmvc的数据响应
    - 代码地址
直接返回
//直接返回jsp页面方式
    @RequestMapping("/s1")
    public String show() {

        return "hello";
    }
模型和视图返回
//模型和视图返回
    @RequestMapping("/s2")
    public ModelAndView show2(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");
        modelAndView.addObject("username","xiaoming");
        return  modelAndView;
    }
模型和视图注入返回
//模型和视图注入返回
    @RequestMapping("/s3")
    public ModelAndView show3(ModelAndView modelAndView){
        modelAndView.setViewName("hello");
        modelAndView.addObject("username","xiaogang");
        return  modelAndView;
    }
模型返回
 //模型返回
    @RequestMapping("/s4")
    public String show4(Model model){
        model.addAttribute("username","xiaohong");
        return  "hello";
    }
request方式返回
 //request 方式返回
    @RequestMapping("/s5")
    public String show5(HttpServletRequest request){
        request.setAttribute("username","xiaoxu");
        return "hello";
    }
response返回数据
//response返回数据
    @RequestMapping("/s6")
    public void show6(HttpServletResponse response) throws IOException {
        response.getWriter().print("Hello World");
    }
直接返回字符串非模板
 //直接返回字符串非模板
    @RequestMapping("/s7")
    @ResponseBody
    public String show7(){
        return  "xiaoming";
    }
返回json数据
//直接json数据
    @RequestMapping("/s8")
    @ResponseBody
    public String show8(){
        return "{"username":"zhangsan","age":18}";
    }
使用json包对象转json
  • 在pom.xml导入json包坐标

            com.fasterxml.jackson.core
            jackson-core
            2.9.0
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.9.0
        
        
            com.fasterxml.jackson.core
            jackson-annotations
            2.9.0
        
 //使用json包对象转json
    @RequestMapping("/s9")
    @ResponseBody
    public String show9() throws JsonProcessingException {
        User user = new User();
        user.setUsername("xiaoming");
        user.setAge(23);

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writevalueAsString(user);
        return json;
    }
使用spring容器方式进行返回json
  • 在spring-mvc.xml中配置处理器映射器
 
        
            
                
            
        
    
//spring容器返回对象集合
    @RequestMapping("/s10")
    @ResponseBody
    public User show10() {
        User user = new User();
        user.setUsername("xiaohong");
        user.setAge(23);
        return user;
    }
  • 在xml文件我们可以配置mvc注解驱动,可以默认去使用json包,不再去配置
  
    
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/658279.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号