Spring MVC数据绑定

2018-07-01  本文已影响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>
上一篇 下一篇

猜你喜欢

热点阅读