zoukankan      html  css  js  c++  java
  • SpringMVC参数绑定(二)

    在springMVC中,提交请求的数据是通过方法形参来接收的,从客户端请求的key/value数据,经过参数绑定,将key/value数据绑定到controller形参上,然后再controller就可以直接使用该形参。

    默认支持的类型

      springMVC有支持的默认参数类型,我们直接在形参上给出这些默认类型的生命,就可以直接使用了。其中httpservletRequest对象需要导入tomcat-servlet包。

        1.HttpServletRequest对象

        2.HttpSerletResponse对象

        3.HttpSession对象

        4.Model/ModelMap对象

        @RequestMapping("/edit")
        public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model, ModelMap modelMap) throws IOException {
            String id = request.getParameter("id");
            request.setAttribute("request",id);
    
            response.getWriter().write("response");
    
            session.setAttribute("session",id);
    
            model.addAttribute("model",id);
    
            modelMap.addAttribute("modelMap",id);
    
            ModelAndView mav = new ModelAndView();
            mav.setViewName("edit");
            return mav;
        }

    jsp页面

    <html>
    <head>
        <title>edit</title>
    </head>
    <body>
    ${request}
    
    ${session}
    
    ${model}
    
    ${modelMap}
    </body>
    </html>

    测试地址:/product/eidt?id=112

    Model/ModelMap,ModelMap是Model借口的一个实现类,作用是将Model数据填充到request域,即使使用Model接口,其内部还是由ModelMap来实现。

    基本数据类型的绑定

      byte、short、int、long、float、double、char、boolean

        @RequestMapping("/query")
        public ModelAndView Query(Integer id){
            System.out.print(id);
            return new ModelAndView("edit");
        }

    输入路径测试http://localhost:9999/product/query?id=123 

    这里输入的参数值和controller的参数变量名保持一致,就能完成数据绑定,如果不一致可以使用@RequestParam注解来完成

        @RequestMapping("/query")
        public ModelAndView Query(@RequestParam("username")int id){
            System.out.print(id);
            return new ModelAndView("edit");
        }

    因为是基本数据类型,所以如果前台传递的值是?id=null的话就会数据转换异常,所以这里最好将参数类型定义成包装类。

    包装类数据类型的绑定

      Integer、Long、Byte、Double、Float、Short、String

    public ModelAndView Query(@RequestParam("username")Integer id){

    虽然可以?id=null  但是不写?id=又会报错 ,可以设定默认值以及是否必传

    @RequestMapping(value="/say",method=RequestMethod.GET)
    public String say(@RequestParam(value="id",required=false,defaultValue="0") Integer myId)

    POJO(实体类)类型的绑定

    Product.java

    package com.david.pojo;
    
    import java.util.Date;
    
    public class Product {
        private Integer id;
        private String name;
        private String price;private Integer categoryId;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPrice() {
            return price;
        }
    
        public void setPrice(String price) {
            this.price = price;
        }public Integer getCategoryId() {
            return categoryId;
        }
    
        public void setCategoryId(Integer categoryId) {
            this.categoryId = categoryId;
        }
    }

    参数要与pojo实体类的属性保持一致即可映射成功

        @RequestMapping(value = "/add",method = RequestMethod.POST)
        public ModelAndView add(Product product){
            ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            ProductMapper mapper = ac.getBean(ProductMapper.class);
            mapper.addProduct(product);
            return new ModelAndView("edit");
        }

    jsp

    <form action="/product/add" method="post">
        <input name="id">
        name:<input name="name">
        price:<input name="price">
        <button type="submit">提交</button>
    </form>

    post数据乱码解决

    web.xml

        <!--post乱码 -->
        <filter>
            <filter-name>characterEncodingFilter</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>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>characterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

    绑定包装pojo类

    新建一个包装类 QueryVo 包含Product属性

    public class QueryVo {
        private Product product;
        private String name;
        private String img;
    }

    编辑controller

    <form action="/product/query" method="post">
        img:<input name="img">
        name:<input name="name">
        proname:<input name="product.name">
        proprice:<input name="product.price">
        <button type="submit">提交</button>
    </form>

    在表单中使用该对象属性名.属性来命名如 product.name

    自定义参数类型绑定

      由于日期有很多种,springmvc没办法把字符串转换为日期类型,所以需要自定义参数绑定。

    1.定义String类型到Date类型的转换器

    package com.david.utils;
    
    import org.springframework.core.convert.converter.Converter;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class DateConverter implements Converter<String, Date> {
        @Override
        public Date convert(String s) {
            //实现将字符串转成日期类型(格式是yyyy-MM-dd HH:mm:ss)
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                return dateFormat.parse(s);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //如果参数绑定失败返回null
            return null;
        }
    }

    2.在springmvc.xml文件中配置转换器

    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="converters">
                <!-- 自定义转换器的类名 -->
                <bean class="com.david.utils.DateConverter"></bean>
            </property>
        </bean>

    3.修改queryVo

    public class QueryVo {
        private Product product;
        private String name;
        private String img;
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private Date createTime;
        。。。

    4.jsp

    <form action="/product/query" method="post">
        createTime:<input name="createTime">
        <button type="submit">提交</button>
    </form>

    数组类型的绑定

        @RequestMapping("/query")
        public ModelAndView Query(Integer[] nums){
            for(int i : nums){
                System.out.println(i);
            }
            return new ModelAndView("edit");
        }
    <form action="/product/query" method="post">
        createTime:<input name="nums"><input name="nums"><input name="nums"><input name="nums">
        <button type="submit">提交</button>
    </form>

    List类型的绑定

    需要定义包装类 实现List绑定-不能直接形参List

    package com.david.pojo;
    
    import java.util.List;
    
    public class QueryVo {
        private List<Product> products;
    
        public List<Product> getProducts() {
            return products;
        }
    
        public void setProducts(List<Product> products) {
            this.products = products;
        }
    }
        @RequestMapping("/query")
        public ModelAndView Query(QueryVo vo){
            for(Product p : vo.getProducts()){
                System.out.println(p);
            }
            return new ModelAndView("edit");
        }
    <form action="/product/query" method="post">
        createTime:<input name="products[0].name"><input name="products[0].price">
    
        <input name="products[1].name">
        <button type="submit">提交</button>
    </form>

    springMVC和struts2的区别

    1.springmvc的入口是一个servlet前端控制器,而struts2入口是一个filter过滤器

    2.springmvc是基于方法开发,请求参数传递到方法的形参,可以设计为单例或多例,struts2是基于类开发啊传递参数是通过类的属性,只能设计为多例。

    3.struts2采用值栈请求和相应数据,通过ognl存取数据,springmvc通过参数解析器将request请求内容解析,并给方法形参赋值,将数据和视图凤凰族昂成ModelAndView对象,最后又将ModelAndView中的模型数据通过request域传输到页面。

  • 相关阅读:
    How to install php 7.x on CentOS 7
    Azure新建的CentOS设置root账户的密码
    远程激活.NET REFLECTOR(不能断网)
    C# WebApi 配置复杂路由不生效的问题
    在Mac上激活Adobe产品
    WIN10更新后出现无法联网的问题
    Mac安装SSHFS挂载远程服务器上的文件夹到本地
    输入三个数值,输出其中的最大值和最小值
    登录接口,只为自己能尽快吐槽一下这段代码
    随手记
  • 原文地址:https://www.cnblogs.com/baidawei/p/9095956.html
Copyright © 2011-2022 走看看