SpringMVC框架數據綁定和表單標籤庫

數據綁定是將用戶參數輸入值綁定到領域模型(實體類)的一種特性,在SpringMVC的Controller和View參數數據傳遞中,在所有HTTP請求參數的類型均爲字符串。如果模型需要綁定的類型爲Double或Int,則需要手動進行類型轉換,而有了數據綁定後,就不在需要手動將HTTP請求中的String類型轉換爲模型需要的類型,另一個好處是,當輸入驗證失敗時(數據自動回填),會重新生成一個HTTP表單,無需重新填寫輸入字段。

  1. 數據綁定
    數據綁定的含義:綁定請求參數輸入值到領域模型,模型數據到視圖的綁定(輸入驗證失敗時),模型數據(實體類數據成員的具體值)到表單元素的綁定(如下列列表選項值有控制器初始化)

  2. 數據綁定應用
    必須在web.xml文件中增加編碼過濾器
    form表單的提交方式必須爲post
    domain函數

public class User {
private String[] userName;
 private String[] hobby;
 private String[] friends;
 private String carrer;
 private String houseRegister;
 private String remark;
 public String[] getUserName() {
  return userName;
 }
 public void setUserName(String[] userName) {
  this.userName = userName;
 }
 public String[] getFriends() {
  return friends;
 }
 public void setFriends(String[] friends) {
  this.friends = friends;
 }
 public String getCarrer() {
  return carrer;
 }
 public void setCarrer(String carrer) {
  this.carrer = carrer;
 }
 public String getHouseRegister() {
  return houseRegister;
 }
 public void setHouseRegister(String houseRegister) {
  this.houseRegister = houseRegister;
 }
 public String getRemark() {
  return remark;
 }
 public void setRemark(String remark) {
  this.remark = remark;
 }
 public String[] getHobby() {
  return hobby;
 }
 public void setHobby(String[] hobby) {
  this.hobby = hobby;
 }
 
}

Service層,包括添加用戶和查詢用戶

public interface UserService {
 boolean addUser(User u);
 ArrayList<User> getUsers();
 
}

@Service
public class UserServicelmpl implements UserService{
  private  final ArrayList<User> users =  new ArrayList<User>();
  
 @Override
 public boolean addUser(User u) {
  // TODO Auto-generated method stub
  if(!"IT民工".equals(u.getCarrer())) {
   users.add(u);
   return true;
  }
  return false;
 }
 
 @Override
 public ArrayList<User> getUsers() {
  // TODO Auto-generated method stub
  return users;
 }
 }

Controller層
在UserController類中,通過**@Autowired註解在UserController對象中主動注入UserService對象**,實現對user對象的添加和查詢等操作:通過model的addAttribute方法將User類對象,HashMap類型的hobbys對象,String[ ]類型的carrers對象以及String[]類型的houseRegisters對象傳遞給View

@Controller
@RequestMapping("/user")
public class UserController {
private static final Log logger = LogFactory.getLog(UserController.class);
 @Autowired
 private UserService userService;
 @RequestMapping (value = "/input")
 public String inputUser(Model model) {
  HashMap<String,String> hobbys = new HashMap<String , String>();
  hobbys.put("籃球","籃球");
  hobbys.put("乒乓球","乒乓球");
  hobbys.put("電玩","電玩");
  hobbys.put("游泳","游泳");
  model.addAttribute("user", new User());
  model.addAttribute("hobbys", hobbys);
  model.addAttribute("carrers", new String[] {"教師","學生","coding搬運工","IT民工","其他"});
  model.addAttribute("houseRegisters", new String[] {"北京","上海","廣州","深圳","其他"});
  return "userAdd";
 }
 @RequestMapping(value = "/save")
 public String addUser(@ModelAttribute  User user,Model model) {
  if(userService.addUser(user)) {
   logger.info("成功 ");
   return "redirect:/user/list";
  }else {
   logger.info("失敗");
   HashMap<String,String> hobbys = new HashMap<String,String>();
   hobbys.put("籃球","籃球");
   hobbys.put("乒乓球","乒乓球");
   hobbys.put("電玩","電玩");
   hobbys.put("游泳","游泳");
   model.addAttribute("hobbys", hobbys);
   model.addAttribute("carrers", new String[] {"教師","學生","coding搬運工","IT民工","其他"});
   model.addAttribute("houseRegisters", new String[] {"北京","上海","廣州","深圳","其他"});
   return "userAdd";
  }
 }
 @RequestMapping(value = "/list")
 public String listUsers(Model model) {
  List<User> users = userService.getUsers();
  model.addAttribute("users", users);
  return "userList";
  }`在這裏插入代碼片`
 }

View層
userAdd.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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>Insert title here</title>
</head>
<body>
 <form:form modelAttribute="user" method="post" action="user/save">
  <fieldset>
   <legend>添加一個用戶</legend>
   <p>
    <label>用戶名:</label>
    <form:input path="userName"/>
   </p>
   <p>
    <label>用戶名:</label>
    <form:checkboxes items="${hobbys }" path="hobby"/>
   </p>
   <p>
    <label>朋友:</label>
    <form:checkbox path="friends" value="張三"/>張三
    <form:checkbox path="friends" value="李四"/>李四
    <form:checkbox path="friends" value="王五"/>王五
    <form:checkbox path="friends" value="週六"/>週六
   </p>
   <p>
    <label>職業:</label>
    <form:select path="carrer">
    <option/>請選擇職業
    <form:options items="${carrers}"></form:options>
    </form:select>
   </p>
    <p>
    <label>戶籍:</label>
    <form:select path="houseRegister">
    <option/>請選擇戶籍
    <form:options items="${houseRegisters }"></form:options>
    </form:select>
   </p>
   <p>
    <label>個人描述:</label>
    <form:textarea path="remark" rows="5"/>
   </p>
   <p id="buttons">
    <input id="reset" type="reset">
    <input id="submit" type="submit" value="添加">
   </p>
  </fieldset>
 
 </form:form>
</body>
</html>

userLiset.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>用戶列表</h1>
    <a href="<c:url value="user/input"/>">繼續添加</a>
    <table>
        <tr>
            <th>用戶名</th>
            <th>興趣愛好</th>
            <th>朋友</th>
            <th>職業</th>
            <th>戶籍</th>
            <th>個人描述</th>
        </tr>
        <!-- JSTL標籤,請參考本書的相關內容 -->
        <c:forEach items="${users}" var="user">
            <tr>
                <td>${user.userName }</td>
                <td>
                 <c:forEach items="${user.hobby }" var="hobby">
                  ${hobby }&nbsp;
                 </c:forEach>
                </td>
                <td>
                 <c:forEach items="${user.friends }" var="friend">
                  ${friend }&nbsp;
                 </c:forEach>
                </td>
                <td>${user.carrer }</td>
                <td>${user.houseRegister }</td>
                <td>${user.remark }</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

應用通過地址http://localhost:8080/ch5/user/input 進行測試,添加用戶信息頁面
在這裏插入圖片描述

  1. 表單標籤庫

表單標籤庫中有form、input、password、hidden、textarea、checkbox、checkboxes
radiobutton、radiobuttons、select、option、options、errors。
form:渲染表單元素。
input:渲染元素。
password:渲染元素。
hidden:渲染元素。
textarea:渲染textarea元素。
checkbox:渲染一個元素。wajegi單:意出
checkboxes:渲染多個元素。
radiobutton:渲染一個元素。
radiobuttons:渲染多個元素。
select:渲染一個選擇元素。
option:渲染一個選項元素。
options:渲染多個選項元素。
errers,在span元素中渲染字段錯誤

-表單標籤

表單標籤,語法格式如下:
<form:form modelAttribute=“xxx” method="post”action=“xxx”>
</form:form>
除了具有HTML表單元素屬性外,表單標籤還具有acceptCharset、commandName、
cssClass、cssStyle、htmlEscape和 modelAtribute等屬性。各屬性含義如下所示。
acceptCharset:定義服務器接受的字符編碼列表。
commandName:暴露表單對象的模型屬性名稱,默認爲command。
cssClass:定義應用到form元素的CSS類。
cssStyle:定義應用到form元素的CSS樣式。
htmlEscape:true 或false,表示是否進行HTML轉義。
modelAttribute:暴露form backing object的模型屬性名稱,默認爲command。
其中,commandName和modelAtribute屬性功能基本一致,屬性值綁定一個JavaBean對象。

  • input標籤,password標籤,hidden標籤,textarea標籤,checkbox標籤,checkboxes標籤等
    在這裏插入圖片描述

在這裏插入圖片描述

  1. 總結
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章