首页 > 代码库 > SpringMVC_3_实操Binding

SpringMVC_3_实操Binding

previous:SpringMVC_2_实操Controller  next:SpringMVC_4_实操FileUpload

Binding:将请求中的字段按照名字匹配的原则填入模型对象。

1)@ModelAttribute on Method

2)redirect/forward

------------------------------------------------------

CourseController.java

 @RequestMapping(value="http://www.mamicode.com/admin", method = RequestMethod.GET, params = "add")//拦截URL对象/admin 2)请求参数add
 public String createCourse(){
  return "course_admin/edit";
 }

 @RequestMapping(value="http://www.mamicode.com/save", method = RequestMethod.POST)

// public String  doSave(Course course){  原始方法

//@ModelAttribute方法参数级别的annotation,来完成绑定参数的过程
 public String  doSave(@ModelAttribute Course course){  
   //日志信息,用来确认动作
  log.debug("Info of Course:");
  log.debug(ReflectionToStringBuilder.toString(course));
  
  //在此进行业务操作,比如数据库持久化
  course.setCourseId(123);

  //请求重定向
  return "redirect:view2/"+course.getCourseId();
 }
 

-------------------------------------------------------------------

edit.jsp

页面空间名称和模型的属性名称一致。注意casesensitive。

<%@ page language="java" 
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>我不是真正的慕课网</title>

<link rel="stylesheet"
    href="<%=request.getContextPath()%>/resources/css/main.css"
    type="text/css" />
</head>
<body>
    <div id="main">
        <div class="newcontainer" id="course_intro">
          <form name="mainForm" action="<%= request.getContextPath()%>/courses/save" method="post">
            <div>
               <span>课程名称:</span><input type="text" id="title" name="title">
            </div>
            <div>
               <span>课程时长:</span><input type="text" id="duration" name="duration"></div> 
            <div>
               <span>课程难度:</span>
               <select id="level" name="level">
                  <option value="0">初级</option>
                  <option value="1" selected="selected">中级</option>
                  <option value="2">高级</option>
                </select>
            </div> 
            <div>
               <span>课程介绍:</span>
               <textarea id="descr" name="descr" rows="5" style="width:480px"></textarea>
            </div> 
            <div>
               <input type="submit" id="btnPass" value="提交" />
            </div> 
          </form>
        </div>
    </div>
</body>
</html>

验证修改:

//maven操作

1)cmd:ctrl +c 停止jetty 

  cls

2)然后重新启动mvn jetty:run

查看cmd的log

 

SpringMVC_3_实操Binding