美文网首页
Spring MVC数据绑定

Spring MVC数据绑定

作者: 沧海一粟谦 | 来源:发表于2018-07-01 19:32 被阅读16次

数据绑定:是指将http请求中的参数绑定到Handler业务方法的形参

我们在使用servlet的时候,通过doGet和doPost方法中的HttpServletRequest对象获取参数,但是通过request对象获取的参数都是String类型的,如果前端传一个int类型的id,我们在后台使用request对象取出后要进行数据转换;如果要添加一个课程的话,在前端输入相关属性后,通过form表单传给后台,后台处理业务方法的时候,通过request获取参数,然后要封装成一个课程对象。使用SpringMVC框架之后,就不需要再进行数据的转换、封装等操作,只需要在形参列表定义类型就可以了。SpringMVC框架会自动将http请求中的参数取出来绑定到形参当中。

Spring MVC数据绑定原理

Spring MVC数据绑定的使用

绑定基本数据类型
@Controller
public class DataController {
    @RequestMapping(value = "/baseType")
    @ResponseBody
    public String baseType(@RequestParam(value = "id") int id){
        return "id:"+id;
    }
}
绑定包装类型
@RequestMapping(value = "/packageType")
    @ResponseBody
    public String packageType(@RequestParam(value = "id",required = false) Integer id){
        return "id:"+id;
    }
绑定数组
@RequestMapping(value = "/arrayType")
    @ResponseBody
    public String arrayType(String[] name){
        StringBuffer stringBuffer = new StringBuffer();
        for (String item:name){
            stringBuffer.append(item).append("  ");
        }
        return stringBuffer.toString();
    }
绑定POJO数据类型
public class Course {
    private int id;
    private String name;
    private double price;
    private Author author;
    ......
}
public class Author {
    private int id;
    private String name;
    ......
}
@Repository
public class CourseDAO {

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

    public void add(Course course){
        courses.put(course.getId(),course);
    }

    public Collection<Course> getAll(){
        return courses.values();
    }
}
@Controller
public class DataBindController {

    @Autowired
    private CourseDAO courseDAO;

    @RequestMapping(value = "/pojoType")
    public ModelAndView pojoType(Course course){
        courseDAO.add(course);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("courses",courseDAO.getAll());
        return modelAndView;
    }
}
绑定list
public class CourseList {
    private List<Course> courses;

    public List<Course> getCourses() {
        return courses;
    }

    public void setCourses(List<Course> courses) {
        this.courses = courses;
    }
}
@RequestMapping(value = "/listType")
    public ModelAndView listType(CourseList courseList){
        for(Course course:courseList.getCourses()){
            courseDAO.add(course);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("courses",courseDAO.getAll());
        return modelAndView;
    }
绑定map
public class CourseMap {
    private Map<String,Course> courses;

    public void setCourses(Map<String, Course> courses) {
        this.courses = courses;
    }

    public Map<String, Course> getCourses() {
        return courses;
    }
}
@RequestMapping(value = "/mapType")
    public ModelAndView mapType(CourseMap courseMap){
        for(String key:courseMap.getCourses().keySet()){
            Course course = courseMap.getCourses().get(key);
            courseDAO.add(course);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("courses",courseDAO.getAll());
        return modelAndView;
    }
绑定set
public class CourseSet {
    private Set<Course> courses = new HashSet<Course>();

    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }

    public Set<Course> getCourses() {
        return courses;
    }

    public  CourseSet(){
        courses.add(new Course());
        courses.add(new Course());
    }
}
@RequestMapping(value = "/setType")
    public ModelAndView setType(CourseSet courseSet){
        for (Course course:courseSet.getCourses()){
            courseDAO.add(course);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("courses",courseDAO.getAll());
        return modelAndView;
    }
绑定json
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
    $(function(){
        var course = {
            "id":"8",
            "name":"SSM框架整合",
            "price":"200"
        };
        $.ajax({
            url:"jsonType",
            data:JSON.stringify(course),
            type:"post",
            contentType:"application/json;charse=UTF-8",
            dataType:"json",
            success:function(data){
                alert(data.name+"---"+data.price);
            }
        })
    })
</script>
<body></body>
</html>
 @RequestMapping(value = "/jsonType")
    @ResponseBody
    public  Course jsonType(@RequestBody  Course course){
        course.setPrice(course.getPrice()+100);
        return course;
    }

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>
    <link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">

    <!-- 标题 -->
    <div class="row">
        <div class="col-md-12">
            <h1>imooc-课程管理</h1>
        </div>
    </div>
    <!-- 显示表格数据 -->
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="check_all"/>
                    </th>
                    <th>编号</th>
                    <th>课程名</th>
                    <th>价格</th>
                    <th>讲师</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach items="${courses}" var="course">
                    <tr>
                        <td><input type='checkbox' class='check_item'/></td>
                        <td>${course.id}</td>
                        <td>${course.name}</td>
                        <td>${course.price}</td>
                        <td>${course.author.name}</td>
                        <td>
                            <button class="btn btn-primary btn-sm edit_btn">
                                <span class="glyphicon glyphicon-pencil">编辑</span>
                            </button>&nbsp;&nbsp;
                            <button class="btn btn-danger btn-sm delete_btn">
                                <span class="glyphicon glyphicon-trash">删除</span>
                            </button>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

addCourse.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>add</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        body{
            overflow-x:hidden;
        }
        #main{
            width:1200px;
            height:600px;
            margin-left:500px;
        }
    </style>
</head>
<body>

<div id="main">
    <!-- 标题 -->
    <div class="row">
        <div class="col-md-12">
            <h1>imooc-添加课程</h1>
        </div>
    </div>

    <form class="form-horizontal" role="form" action="pojoType" method="post">
        <div class="form-group">
            <label class="col-sm-1 control-label">课程编号</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="id" placeholder="请输入课程编号">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">课程名称</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="name" placeholder="请输入课程名称">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">课程价格</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="price" placeholder="请输入课程价格">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">讲师编号</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="author.id" placeholder="请输入讲师编号">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">讲师姓名</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="author.name" placeholder="请输入讲师姓名">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <button type="submit" class="btn btn-default">提交</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

addList.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>add</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        body{
            overflow-x:hidden;
        }
        #main{
            width:1200px;
            height:600px;
            margin-left:500px;
        }
    </style>
</head>
<body>

<div id="main">
    <!-- 标题 -->
    <div class="row">
        <div class="col-md-12">
            <h1>imooc-添加课程</h1>
        </div>
    </div>

    <form class="form-horizontal" role="form" action="listType" method="post">
        <div class="form-group">
            <label class="col-sm-1 control-label">课程1编号</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[0].id" placeholder="请输入课程编号">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">课程1名称</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[0].name" placeholder="请输入课程名称">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">课程1价格</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[0].price" placeholder="请输入课程价格">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">讲师编号</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[0].author.id" placeholder="请输入讲师编号">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">讲师姓名</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[0].author.name" placeholder="请输入讲师姓名">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">课程2编号</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[1].id" placeholder="请输入课程编号">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">课程2名称</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[1].name" placeholder="请输入课程名称">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">课程2价格</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[1].price" placeholder="请输入课程价格">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">讲师编号</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[1].author.id" placeholder="请输入讲师编号">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">讲师姓名</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="courses[1].author.name" placeholder="请输入讲师姓名">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <button type="submit" class="btn btn-default">提交</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

相关文章

  • 第十三章 数据绑定

    数据绑定介绍 Spring MVC是怎样完成的数据绑定 在数据绑定过程中,Spring MVC框架会通过数据绑定组...

  • Spring MVC 数据绑定(二)

    上篇:Spring MVC 数据绑定(一)Spring MVC通过反射机制对目标处理方法的签名进行分析,将请求信息...

  • 2019-07-18 SpringMVC 数据绑定

    1.Spring MVC数据绑定基本概念 在为发明Spring MVC之前,我们一般使用的方法是,利用doPost...

  • Spring MVC 数据绑定

    数据绑定 将HTTP请求中的参数绑定到Handler业务方法的形参。(传统request方式只能传String类型...

  • Spring MVC数据绑定

    数据绑定:是指将http请求中的参数绑定到Handler业务方法的形参 我们在使用servlet的时候,通过doG...

  • Spring MVC 数据绑定(一)

    写在最前 本文主要了解请求参数解析的过程,源码参考为4.2.5,为了便于理解,部分代码我进行了简化。如果需要了解整...

  • SpringMVC(八)数据转换 & 数据格式化 &am

    一、数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标方法的入参实例传递...

  • spring mvc出现 Failed to convert p

    在使用spring mvc中,绑定页面传递时间字符串数据给Date类型是出错: Failed to convert...

  • Spring MVC的数据转换及数据格式化

    Spring MVC会根据请求方法签名不同,将请求消息中信息以一定方式转换并绑定到请求方法的参数中。 1.数据绑定...

  • spring mvc

    spring mvc 参数绑定 默认支持的类型①、HttpServletRequest 对象②、HttpServl...

网友评论

      本文标题:Spring MVC数据绑定

      本文链接:https://www.haomeiwen.com/subject/pslhuftx.html