SpringMVC数据绑定

一.基础配置

(1)pom.xml

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

(2)web.xml

<servlet>

  <servlet-name>SpringMVC</servlet-name>

  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  <init-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:springmvc.xml</param-value>

  </init-param>

</servlet>

<servlet-mapping>

  <servlet-name>SpringMVC</servlet-name>

  <url-pattern>/</url-pattern>

</servlet-mapping>

(3)springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"

       xmlns:mvc="http://www.springframework.org/schema/mvc"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--配置包扫描-->

    <context:component-scan base-package="controller,dao"></context:component-scan>

    <!--配置视图解析器-->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <!--配置前缀-->

        <property name="prefix" value="/"></property>

        <!--配置后缀-->

        <property name="suffix" value=".jsp"></property>

    </bean>

    <!--消息转换器-->

    <mvc:annotation-driven>

        <mvc:message-converters>

            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>

        </mvc:message-converters>

    </mvc:annotation-driven>

</beans>

(4)Course.java(实体类)

package entity;

public class Course {

    private int id;

    private String name;

    private double price;

    private Author author;

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public double getPrice() {

        return price;

    }

    public void setPrice(double price) {

        this.price = price;

    }

    public Author getAuthor() {

        return author;

    }

    public void setAuthor(Author author) {

        this.author = author;

    }

    @Override

    public String toString() {

        return "Course{" +

                "id=" + id +

                ", name='" + name + '\'' +

                ", price=" + price +

                ", author=" + author +

                '}';

    }

}

(5)Author.java(实体类)

package entity;

public class Author {

    private int id;

    private String name;

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

}

(6)SaveDao.java(用于保存的dao)

package dao;

import entity.Course;

import org.springframework.stereotype.Repository;

import java.util.Collection;

import java.util.HashMap;

import java.util.Map;

@Repository

public class SaveDao {

   private Map<Integer,Course> map=new HashMap<Integer, Course>();

   public void save(Course course){

       map.put(course.getId(),course);

   }

   public Collection<Course> getall(){

       return map.values();

   }

}

(7)index.jsp(用于遍历显示)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@page isELIgnored="false" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>

<head>

    <title>Title</title>

</head>

<body>

<table>

    <tr>

        <td>课程ID</td>

        <td>课程名</td>

        <td>课程价格</td>

        <td>讲师ID</td>

        <td>讲师名</td>

    </tr>

    <c:forEach items="${courses}" var="course">

        <tr>

            <td>${course.id}</td>

            <td>${course.name}</td>

            <td>${course.price}</td>

            <td>${course.author.id}</td>

            <td>${course.author.name}</td>

        </tr>

    </c:forEach>

</table>

</body>

</html>

二.数据绑定分类

(一)普通数据类型的数据绑定
(二)包装类的数据绑定
(三)数组类型的数据绑定
(四)对象类型的数据绑定
(五)List集合类型的数据绑定
(六)Map集合类型的数据绑定
(七)Set集合类型的数据绑定

DataController.java

package controller;

import dao.SaveDao;

import entity.*;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.servlet.ModelAndView;

@Controller

public class DataController {

    @Autowired

    private SaveDao saveDao;

    /**

     * 基本数据类型的数据绑定

     * @param id

     * @return

     */

    @RequestMapping("/one")

    @ResponseBody  //将返回值显示到页面

    public String one(@RequestParam(value="id") int id){

        return "id:"+id;

    }

    /**

     * 包装类的数据绑定

     * @param id

     * @return

     */

    @RequestMapping("/two")

    @ResponseBody

    public String two(@RequestParam(value="id")Integer id){

        return "id"+id;

    }

    /**

     * 数组类型的数据绑定

     * @param three

     * @return

     */

    @RequestMapping("/three")

    @ResponseBody

    public String three(String[] three){

       StringBuffer st=new StringBuffer();

       for(String s:three){

           st.append(s).append(" ");

       }

       return st.toString();

    }

    /**

     * 对象类型的数据绑定

     * 对象保存,在dao层进行

     * @param course

     * @return

     */

    @RequestMapping("/four")

    public ModelAndView four(Course course){

        saveDao.save(course);

        ModelAndView modelAndView=new ModelAndView();

        modelAndView.setViewName("index");

        modelAndView.addObject("courses",saveDao.getall());

        return modelAndView;

    }

    /**

     * List集合类型的数据绑定

     * 不能直接绑定集合,应该创建一个包装类

     * @param courceList

     * @return

     */

    @RequestMapping("/five")

    public ModelAndView five(CourceList courceList){

        for(Course course:courceList.getCourses()){

            saveDao.save(course);

        }

        ModelAndView modelAndView=new ModelAndView();

        modelAndView.setViewName("index");

        modelAndView.addObject("courses",saveDao.getall());

        return modelAndView;

    }

    /**

     * Map集合类型的数据绑定

     * @param courseMap

     * @return

     */

    @RequestMapping("/six")

    public ModelAndView six(CourseMap courseMap){

        for(Course course:courseMap.getMap().values()){

            System.out.println(course);

            saveDao.save(course);

        }

        ModelAndView modelAndView=new ModelAndView();

        modelAndView.setViewName("index");

        modelAndView.addObject("courses",saveDao.getall());

        return modelAndView;

    }

    /**

     * Set集合类型的数据绑定

     * @param courseSet

     * @return

     */

    @RequestMapping("/seven")

    public ModelAndView seven(CourseSet courseSet){

        for(Course course:courseSet.getSet()){

            saveDao.save(course);

        }

        ModelAndView modelAndView=new ModelAndView();

        modelAndView.setViewName("index");

        modelAndView.addObject("courses",saveDao.getall());

        return modelAndView;

    }

    @RequestMapping(value="/eight")

    @ResponseBody

    public String eight(@RequestBody User user){

        user.setName("成功");

        System.out.println("==========");

        return "aa";

    }

}

三.数据绑定所需的类和页面

(一)普通数据类型
(二)包装类
(三)数组类型
(四)对象类型

1.save.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

<form action="/four" method="post">

    课程ID:<input type="text" name="id">

    课程名:<input type="text" name="name">

    课程价格:<input type="text" name="12.5">

    讲师ID:<input type="text" name="author.id">

    讲师名:<input type="text" name="author.name">

    <input type="submit">

</form>

</body>

</html>
(五)List集合

1.CourseList.java

package entity;

import java.util.List;

public class CourceList {

    private List<Course> courses;

    public List<Course> getCourses() {

        return courses;

    }

    public void setCourses(List<Course> courses) {

        this.courses = courses;

    }

}

2.saveList.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

<form action="/five" method="post">

    课程1ID:<input type="text" name="courses[0].id">

    课程1名:<input type="text" name="courses[0].name">

    课程1价格:<input type="text" name="courses[0].price">

    讲师1ID:<input type="text" name="courses[0].author.id">

    讲师1名:<input type="text" name="courses[0].author.name">

    课程2ID:<input type="text" name="courses[1].id">

    课程2名:<input type="text" name="courses[1].name">

    课程2价格:<input type="text" name="courses[1].price">

    讲师2ID:<input type="text" name="courses[1].author.id">

    讲师2名:<input type="text" name="courses[1].author.name">

    <input type="submit">

</form>

</body>

</html>
(六)Map集合

1.CourseMap.java

package entity;

import java.util.Map;

public class CourseMap {

    private Map<String,Course> map;

    public Map<String, Course> getMap() {

        return map;

    }

    public void setMap(Map<String, Course> map) {

        this.map = map;

    }

    @Override

    public String toString() {

        return "CourseMap{" +

                "map=" + map +

                '}';

    }

}

2.saveMap.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

<form action="/six" method="post">

    课程1ID:<input type="text" name="map['one'].id">

    课程1名:<input type="text" name="map['one'].name">

    课程1价格:<input type="text" name="map['one'].price">

    讲师1ID:<input type="text" name="map['one'].author.id">

    讲师1名:<input type="text" name="map['one'].author.name">

    课程2ID:<input type="text" name="map['two'].id">

    课程2名:<input type="text" name="map['two'].name">

    课程2价格:<input type="text" name="map['two'].price">

    讲师2ID:<input type="text" name="map['two'].author.id">

    讲师2名:<input type="text" name="map['two'].author.name">

    <input type="submit">

</form>

</body>

</html>
(七)Set集合

1.CourseSet.java

package entity;

import java.util.HashSet;

import java.util.Set;

public class CourseSet {

    private Set<Course> set=new HashSet<Course>();

    public Set<Course> getSet() {

        return set;

    }

    public void setSet(Set<Course> set) {

        this.set = set;

    }

    public CourseSet(){

        set.add(new Course());

        set.add(new Course());

    }

}

2.saveSet.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

<form action="/seven" method="post">

    课程1ID:<input type="text" name="set[0].id">

    课程1名:<input type="text" name="set[0].name">

    课程1价格:<input type="text" name="set[0].price">

    讲师1ID:<input type="text" name="set[0].author.id">

    讲师1名:<input type="text" name="set[0].author.name">

    课程2ID:<input type="text" name="set[1].id">

    课程2名:<input type="text" name="set[1].name">

    课程2价格:<input type="text" name="set[1].price">

    讲师2ID:<input type="text" name="set[1].author.id">

    讲师2名:<input type="text" name="set[1].author.name">

    <input type="submit">

</form>

</body>

</html>

-----------------------------------demo12------------------------------------

SpringMVC学习笔记之---数据绑定的更多相关文章

  1. SpringMVC:学习笔记(5)——数据绑定及表单标签

    SpringMVC——数据绑定及表单标签 理解数据绑定 为什么要使用数据绑定 基于HTTP特性,所有的用户输入的请求参数类型都是String,比如下面表单: 按照我们以往所学,如果要获取请求的所有参数 ...

  2. 史上最全的SpringMVC学习笔记

    SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...

  3. springmvc学习笔记(常用注解)

    springmvc学习笔记(常用注解) 1. @Controller @Controller注解用于表示一个类的实例是页面控制器(后面都将称为控制器). 使用@Controller注解定义的控制器有如 ...

  4. SpringMVC学习笔记之二(SpringMVC高级参数绑定)

    一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...

  5. springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定

    springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定 标签: springmvc springmvc学习笔记13-springmvc注解开发之集合类型參数绑定 数组绑定 需 ...

  6. springmvc学习笔记--REST API的异常处理

    前言: 最近使用springmvc写了不少rest api, 觉得真是一个好框架. 之前描述的几篇关于rest api的文章, 其实还是不够完善. 比如当遇到参数缺失, 类型不匹配的情况时, 直接抛出 ...

  7. springmvc学习笔记---面向移动端支持REST API

    前言: springmvc对注解的支持非常灵活和飘逸, 也得web编程少了以往很大一坨配置项. 另一方面移动互联网的到来, 使得REST API变得流行, 甚至成为主流. 因此我们来关注下spring ...

  8. SpringMVC:学习笔记(8)——文件上传

    SpringMVC--文件上传 说明: 文件上传的途径 文件上传主要有两种方式: 1.使用Apache Commons FileUpload元件. 2.利用Servlet3.0及其更高版本的内置支持. ...

  9. springmvc学习笔记(简介及使用)

    springmvc学习笔记(简介及使用) 工作之余, 回顾了一下springmvc的相关内容, 这次也为后面复习什么的做个标记, 也希望能与大家交流学习, 通过回帖留言等方式表达自己的观点或学习心得. ...

随机推荐

  1. AntD使用timePiacker封装时间范围选择器(React hook版)

    .katex { display: block; text-align: center; white-space: nowrap; } .katex-display > .katex > ...

  2. 蓝桥杯:合并石子(区间DP+平行四边形优化)

    http://lx.lanqiao.cn/problem.page?gpid=T414 题意:…… 思路:很普通的区间DP,但是因为n<=1000,所以O(n^3)只能拿90分.上网查了下了解了 ...

  3. c#中bin,obj,properties文件夹的作用

    Bin 目录用来存放编译的结果,bin是二进制binrary的英文缩写,因为最初C编译的程序文件都是二进制文件,它有Debug和Release两个版本,分别对应的文件夹为bin/Debug和bin/R ...

  4. Spring的Ioc模拟实现

      关于IOC:我们讲个故事吧! 有一个厨师,他在做一道菜的时候需要某种调味料(bean),可是他正好没有那瓶调味料(bean),这个时候他就必须去制作一瓶调味料(bean)出来.(这就像我们平时需要 ...

  5. 基础篇-1.2Java世界的规章制度(上)

    1 Java标识符 在Java语言中,有类.对象.方法.变量.接口和自定义数据类型等等,他们的名字并不是确定的,需要我们自己命名.而Java标识符就是用来给类.对象.方法.变量.接口和自定义数据类型命 ...

  6. HBaseCon Asia2019 会议总结

    一.首先会议流程. 1. The current status of HBase 2.The advantage and technology trend of HBase on the cloud ...

  7. springboot启动代码(自用)

    1.springboot配置解释 @AutoConfigurationPackage //自动配置包 //@Import(AutoConfigurationPackages.Registrar.cla ...

  8. C# 针对特定的条件进行锁操作,不用lock,而是mutex

    背景:用户领取优惠券,同一个用户需要加锁验证是否已经领取,不同用户则可以同时领取. 上代码示例: 1.创建Person类 /// <summary> /// Person类 /// < ...

  9. hmm隐马尔可夫真的那么难吗?

    hmm隐马尔可夫真的那么难吗? 首先上代码 这里是github上的关于hmm的:链接 概率计算问题:前向-后向算法 学习问题:Baum-Welch算法(状态未知) 预测问题:Viterbi算法 htt ...

  10. python3.x 与 python2.x 差别记录

    从2.x过渡到3.x的时候,遇到了大大小小的坑,于是便记录下来- 1.print:  3.x 所有print都要加 "( )",print更像(就是)一个函数了. 2.x 可以加& ...