首页 > 编程语言 > 详细

Springmvc:(五)数据处理

时间:2020-03-13 13:35:22      阅读:88      评论:0      收藏:0      [点我收藏+]

一、处理提交数据

  1. 提交的域名称和处理方法的参数名一致

    url : http://localhost:8080/hello?name=zho
    
    @RequestMapping("/hello")
    public String hello(String name){
        System.out.println(name);
        return "hello";
    }
    
    输出:zho
  2. 提交的域名称和处理方法的参数名不一致

    url:http://localhost:8080/hello?username=kuangshen
    
    //@RequestParam("username") : username提交的域的名称 .
    @RequestMapping("/hello")
    public String hello(@RequestParam("username") String name){
        System.out.println(name);
        return "hello";
    }
  3. 提交的是一个对象

    要求提交的表单域和对象的属性名一致 , 参数使用对象即可

    //实体类
    public class User {
        private int id;
        private String name;
        private int age; 
    }
    
    url:http://localhost:8080/mvc04/user?name=zho&id=1&age=15  
    
    输出 : User { id=1, name='zho', age=15 }
    

二、数据显示到前端

  1. 通过ModelAndView

  2. 通过ModelMap

    @RequestMapping("/hello")
    public String hello(@RequestParam("username") String name, ModelMap model){
        //封装要显示到视图中的数据
        //相当于req.setAttribute("name",name);
        model.addAttribute("name",name);
        System.out.println(name);
        return "hello";
    }
  3. 通过Model

    @RequestMapping("/ct2/hello")
    public String hello(@RequestParam("username") String name, Model model){
        //封装要显示到视图中的数据
        //相当于req.setAttribute("name",name);
        model.addAttribute("msg",name);
        System.out.println(name);
        return "test";
    }
Model 只有寥寥几个方法只适合用于储存数据,简化了新手对于Model对象的操作和理解;

ModelMap 继承了 LinkedMap ,除了实现了自身的一些方法,同样的继承 LinkedMap 的方法和特性;

ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。

三、解决乱码问题

<filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/</url-pattern>
</filter-mapping>

Springmvc:(五)数据处理

原文:https://www.cnblogs.com/dreamzone/p/12485658.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!