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. python连接 elasticsearch 查询数据,支持分页

    使用python连接es并执行最基本的查询 from elasticsearch import Elasticsearch es = Elasticsearch(["localhost:92 ...

  2. HTTP 学习笔记02

    请求行 格式:请求方式  资源路径  HTTP版本号 HTTP1.1 还需要 [host] 例:GET   /test.html   HTTP/1.0 GET   /test.html   HTTP/ ...

  3. 【POJ - 2386】Lake Counting (dfs+染色)

    -->Lake Counting 直接上中文了 Descriptions: 由于近日阴雨连天,约翰的农场中中积水汇聚成一个个不同的池塘,农场可以用 N x M (1 <= N <= ...

  4. Codeforces Gym101246J:Buoys(三分搜索)

    http://codeforces.com/gym/101246/problem/J 题意:给出n个点坐标,要使这些点间距相同的话,就要移动这些点,问最少的需要的移动距离是多少,并输出移动后的坐标. ...

  5. scrapy基础知识之 CrawlSpiders爬取lagou招聘保存在mysql(分布式):

    items.py import scrapy class LagouItem(scrapy.Item): # define the fields for your item here like: # ...

  6. ETL-kettle 核心执行逻辑

    一.大数据下的ETL工具是否还使用Kettle kettle 作为通用的ETL工具,非常成熟,应用也很广泛,这里主要讲一下 目前我们如何使用kettle的? 在进行大数据处理时,ETL也是大数据处理的 ...

  7. SpringCloud解析之Ribbon

    Ribbon是分布式微服务架构中负载均衡的一个解决方案,我们只需要引入ribbon依赖,然后初始化一个RestTemplate对象,在其上添加@LoadBalanced注解,就可以实现请求的负载均衡, ...

  8. jdk源码--LinkedList

    本文基于jdk1.8_171 LinkedList介绍 之前看了ArrayList,内部是一个数组.这次看了LinkedList,作用和ArrayList一样,但是内部是链表形式.链表结构如下图: 数 ...

  9. android_activity_研究(二)

    这次开始玩玩活动的生命周期.废话不说,先搞个小应用,大体思路是:主界面有两个按钮,一个按钮按下后,出现第二个界面:另一个按钮按下后,出现第三个界面,真他妈简单. 一.主界面: 1. 主界面布局xml文 ...

  10. mongo去重统计

    表名:parkUserCost id: patkId: userId: phone: costVal: 适合特定条件下,对某些字段进行去重筛选.(比如限定抢购) 第一种,使用\(first操作符.\) ...