激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - SpringMVC實(shí)現(xiàn)表單驗(yàn)證功能詳解

SpringMVC實(shí)現(xiàn)表單驗(yàn)證功能詳解

2021-01-24 11:23ITDragon龍 Java教程

這篇文章主要為大家詳細(xì)介紹了SpringMVC 表單驗(yàn)證的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本章節(jié)內(nèi)容很豐富,主要有基本的表單操作,數(shù)據(jù)的格式化,數(shù)據(jù)的校驗(yàn),以及提示信息的國際化等實(shí)用技能。
首先看效果圖

SpringMVC實(shí)現(xiàn)表單驗(yàn)證功能詳解

項(xiàng)目結(jié)構(gòu)圖

SpringMVC實(shí)現(xiàn)表單驗(yàn)證功能詳解

接下來用代碼重點(diǎn)學(xué)習(xí)springmvc的表單操作,數(shù)據(jù)格式化,數(shù)據(jù)校驗(yàn)以及錯誤提示信息國際化。請讀者將重點(diǎn)放在usercontroller.java,user.java,input.jsp三個文件中。
maven 項(xiàng)目必不可少的pom.xml文件。里面有該功能需要的所有jar包。

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/pom/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
 xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelversion>4.0.0</modelversion>
 <groupid>com.springmvc</groupid>
 <artifactid>springmvc</artifactid>
 <version>0.0.1-snapshot</version>
 <packaging>war</packaging>
 
 <!-- 若不配置,打包時會提示錯誤信息
 failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project springmvc: compilation failure:
 提示 未結(jié)束的字符串文字 ,若字符串后面加上空格后可以打包成功,但會亂碼。
 原因是:maven使用的是默認(rèn)的compile插件來進(jìn)行編譯的。complier是maven的核心插件之一,然而complier插件默認(rèn)只支持編譯java 1.4
 -->
 <build>
 <plugins>
  <plugin>
   <artifactid>maven-compiler-plugin</artifactid>
   <configuration>
    <source>1.7</source>
    <target>1.7</target>
    <encoding>utf-8</encoding>
   </configuration>
  </plugin>
 </plugins>
 </build>
 
 <properties>
 <spring.version>4.1.3.release</spring.version>
 </properties>
 <dependencies>
 <!-- spring begin -->
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-webmvc</artifactid>
  <version>${spring.version}</version>
 </dependency>
 
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-context</artifactid>
  <version>${spring.version}</version>
 </dependency>
 
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-aop</artifactid>
  <version>${spring.version}</version>
 </dependency>
 
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-core</artifactid>
  <version>${spring.version}</version>
 </dependency>
  
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-web</artifactid>
  <version>${spring.version}</version>
 </dependency>
 
 <!-- spring end -->
 <dependency>
  <groupid>javax.servlet</groupid>
  <artifactid>javax.servlet-api</artifactid>
  <version>4.0.0</version>
  <scope>provided</scope>
 </dependency>
 <dependency>
  <groupid>javax.servlet</groupid>
  <artifactid>jstl</artifactid>
  <version>1.2</version>
 </dependency>
 <dependency>
  <groupid>taglibs</groupid>
  <artifactid>standard</artifactid>
  <version>1.1.2</version>
 </dependency>
 <!-- 缺少jsp-api 則提示 javax.servlet.jsp.jspexception cannot be resolved to a type -->
 <dependency>
  <groupid>javax.servlet.jsp</groupid>
  <artifactid>jsp-api</artifactid>
  <version>2.2</version>
  <scope>provided</scope>
 </dependency>
 <!-- jsr 303 start -->
 <dependency>
  <groupid>org.hibernate</groupid>
  <artifactid>hibernate-validator</artifactid>
  <version>5.4.1.final</version>
 </dependency>
 <dependency>
  <groupid>javax.validation</groupid>
  <artifactid>validation-api</artifactid>
  <version>1.1.0.final</version>
 </dependency>
 <!-- jsr 303 end -->
   
 </dependencies>
</project>

springmvc的核心配置文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?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-4.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
 
 <!-- 配置自定掃描的包 -->
 <context:component-scan base-package="com.itdragon.springmvc" />
 
 <!-- 配置視圖解析器 -->
 <bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
  <property name="prefix" value="/web-inf/views/"></property>
  <property name="suffix" value=".jsp"></property>
 </bean>
  
 <!-- 配置注解驅(qū)動 -->
 <mvc:annotation-driven />
 
 <!-- 配置視圖 beannameviewresolver 解析器
  使用視圖的名字來解析視圖
  通過 order 屬性來定義視圖解析器的優(yōu)先級, order 值越小優(yōu)先級越高
 -->
 <bean class="org.springframework.web.servlet.view.beannameviewresolver">
  <property name="order" value="100"></property>
 </bean>
  
 <!-- 配置直接跳轉(zhuǎn)的頁面,無需經(jīng)過controller層
  http://localhost:8080/springmvc/index
  然后會跳轉(zhuǎn)到 web-inf/views/index.jsp 頁面
 -->
 <mvc:view-controller path="/index" view-name="index"/>
  
 <mvc:default-servlet-handler/>
  
 <!-- 配置國際化資源文件 -->
 <bean id="messagesource"
  class="org.springframework.context.support.resourcebundlemessagesource">
  <property name="basename" value="i18n"></property>
 </bean>
  
</beans>

以上是準(zhǔn)備工作。下面開始核心代碼介紹。

數(shù)據(jù)的校驗(yàn)思路:

第一步,在實(shí)體類中指定屬性添加校驗(yàn)注解(如@notempty),
第二步,在控制層目標(biāo)方法實(shí)體類參數(shù)添加注解@valid,
第三步,在返回頁面加上顯示提示錯誤信息

數(shù)據(jù)格式化思路:只需要在實(shí)體類中加上注解即可。

信息國際化思路:

第一步,在springmvc配置文件中配置國際化資源文件
第二步,創(chuàng)建文件i18n_zh_cn.properties文件
第三步,在i18n_zh_cn.properties文件配置國際化信息(要嚴(yán)格按照springmvc的語法)

usercontroller.java,兩個重點(diǎn)知識。一個是springmvc的rest風(fēng)格的增刪改查。另一個是@valid注解用法。具體看代碼。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.map;
import javax.validation.valid;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.validation.errors;
import org.springframework.validation.fielderror;
import org.springframework.web.bind.annotation.modelattribute;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
 
import com.itdragon.springmvc.crud.dao.positiondao;
import com.itdragon.springmvc.crud.dao.userdao;
import com.itdragon.springmvc.crud.orm.user;
 
@controller
public class usercontroller {
 
 @autowired
 private userdao userdao;
  
 @autowired
 private positiondao positiondao;
  
 private static final string input = "input"; // 跳轉(zhuǎn)到編輯頁面
 
 private static final string list = "list"; // 跳轉(zhuǎn)到用戶列表頁面
 
 @modelattribute
 public void getuser(@requestparam(value="id",required=false) integer id,
   map<string, object> map){
  if(id != null){
   map.put("user", userdao.getuserbyid(id));
  }
 }
  
 // 更新用戶,用put請求方式區(qū)別get請求方式,屬于springmvc rest 風(fēng)格的crud
 @requestmapping(value="/user", method=requestmethod.put)
 public string updateuser(user user){
  userdao.save(user);
  return "redirect:/users";
 }
  
 // 點(diǎn)擊編輯跳轉(zhuǎn)編輯頁面
 @requestmapping(value="/user/{id}", method=requestmethod.get)
 public string input(@pathvariable("id") integer id, map<string, object> map){
  map.put("user", userdao.getuserbyid(id));
  map.put("positions", positiondao.queryallpositions());
  return input;
 }
  
 // 通過id刪除用戶
 @requestmapping(value="/delete/{id}", method=requestmethod.get)
 public string delete(@pathvariable("id") integer id){
  userdao.deleteuserbyid(id);
  return "redirect:/users";
 }
  
 /**
  * 新增用戶,若保存成功則跳轉(zhuǎn)到用戶列表頁面,若失敗則跳轉(zhuǎn)到編輯頁面
  * @param user 用 @valid 注解修飾后,可實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)的邏輯
  * @param result 數(shù)據(jù)校驗(yàn)結(jié)果
  * @param map 數(shù)據(jù)模型
  * @return
  */
 @requestmapping(value="/user", method=requestmethod.post)
 public string save(@valid user user, errors result, map<string, object> map){
  if(result.geterrorcount() > 0){
   for(fielderror error : result.getfielderrors()){
    system.out.println(error.getfield() + " : " + error.getdefaultmessage());
   }
   map.put("positions", positiondao.queryallpositions());
   return input;
  }
  userdao.save(user);
  return "redirect:/users";
 }
  
 @requestmapping(value="/user", method=requestmethod.get)
 public string input(map<string, object> map){
  map.put("positions", positiondao.queryallpositions());
  map.put("user", new user());
  return input;
 }
  
 // 跳轉(zhuǎn)用戶列表頁面
 @requestmapping("/users")
 public string list(map<string, object> map){
  map.put("users", userdao.queryallusers());
  return list;
 }
  
}

user.java,兩個重點(diǎn)知識。一個是數(shù)據(jù)的格式化(包括日期格式化和數(shù)值格式化)。另一個是使用 jsr 303 驗(yàn)證標(biāo)準(zhǔn)數(shù)據(jù)校驗(yàn)。

數(shù)據(jù)格式化,由于前端傳給后臺的是字符串,對于比較特殊的屬性,比如date,float類型就需要進(jìn)行數(shù)據(jù)格式化
** @numberformat 數(shù)值格式化 **
可以格式化/解析的數(shù)字類型:short、integer、long、float、double、bigdecimal、biginteger。
屬性參數(shù)有:pattern="###,###.##"(重點(diǎn))。
style= org.springframework.format.annotation.numberformat.style.number(currency / percent)。其中style.number(通用樣式,默認(rèn)值);style.currency(貨幣樣式);style.percent(百分?jǐn)?shù)樣式)

** @datetimeformat 日期格式化 **
可以格式化/解析的數(shù)字類型:java.util.date 、java.util.calendar 、java.long.long。
屬性參數(shù)有:pattern="yyyy-mm-dd hh:mm:ss"(重點(diǎn))。
iso=指定解析/格式化字段數(shù)據(jù)的iso模式,包括四種:iso.none(不使用iso模式,默認(rèn)值),iso.date(yyyy-mm-dd),iso.time(hh:mm:ss.sssz),iso.date_time(yyyy-mm-dd hh:mm:ss.sssz);style=指定用于格式化的樣式模式,默認(rèn)“ss”,優(yōu)先級: pattern 大于 iso 大于 style,后兩個很少用。

數(shù)據(jù)校驗(yàn)

空檢查
** @null ** 驗(yàn)證對象是否為null
** @notnull ** 驗(yàn)證對象是否不為null, 無法查檢長度為0的字符串
** @notblank ** 檢查約束字符串是不是null還有被trim的長度是否大于0,只對字符串,
且會去掉前后空格
** @notempty ** 檢查約束元素是否為null或者是empty
booelan檢查
** @asserttrue ** 驗(yàn)證 boolean 對象是否為 true
** @assertfalse ** 驗(yàn)證 boolean 對象是否為 false
長度檢查
** @size(min=, max=) ** 驗(yàn)證對象(array,collection,map,string)值是否在給定的范圍之內(nèi)
** @length(min=, max=) ** 驗(yàn)證對象(charsequence子類型)長度是否在給定的范圍之內(nèi)
日期檢查
** @past ** 驗(yàn)證 date 和 calendar 對象是否在當(dāng)前時間之前
** @future ** 驗(yàn)證 date 和 calendar 對象是否在當(dāng)前時間之后
** @pattern ** 驗(yàn)證 string 對象是否符合正則表達(dá)式的規(guī)則
數(shù)值檢查
** @min ** 驗(yàn)證 number 和 string 對象是否大等于指定的值
** @max ** 驗(yàn)證 number 和 string 對象是否小等于指定的值
** @decimalmax ** 被標(biāo)注的值必須不大于約束中指定的最大值. 這個約束的參數(shù)
是一個通過bigdecimal定義的最大值的字符串表示.小數(shù)存在精度
** @decimalmin ** 被標(biāo)注的值必須不小于約束中指定的最小值. 這個約束的參數(shù)
是一個通過bigdecimal定義的最小值的字符串表示.小數(shù)存在精度
** @digits ** 驗(yàn)證 number 和 string 的構(gòu)成是否合法
** @digits(integer=,fraction=) ** 驗(yàn)證字符串是否是符合指定格式的數(shù)字,interger指定整數(shù)精度,fraction指定小數(shù)精度
** @range(min=, max=) ** 檢查數(shù)字是否介于min和max之間
** @creditcardnumber ** 信用卡驗(yàn)證
** @email ** 驗(yàn)證是否是郵件地址,如果為null,不進(jìn)行驗(yàn)證,算通過驗(yàn)證
** @scriptassert(lang= ,script=, alias=) ** 通過腳本驗(yàn)證

其中有幾點(diǎn)需要注意:

空判斷注解

?
1
2
3
4
5
string name  @notnull @notempty @notblank
null       false    false    false
""       true    false    false
" "       true    true    false
"itdragon!"   true    true    true

數(shù)值檢查:建議使用在stirng,integer類型,不建議使用在int類型上,因?yàn)楸韱沃禐?ldquo;”時無法轉(zhuǎn)換為int,但可以轉(zhuǎn)換為stirng為"",integer為null

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.date;
import javax.validation.constraints.decimalmin;
import org.hibernate.validator.constraints.email;
import org.hibernate.validator.constraints.notempty;
import org.springframework.format.annotation.datetimeformat;
import org.springframework.format.annotation.numberformat;
 
public class user {
  
 private integer id;
 @notempty
 private string account;
 @email
 @notempty
 private string email;
 private integer sex;
 private position position;
 @datetimeformat(pattern="yyyy-mm-dd")
 private date createddate;
 @numberformat(pattern="###,###.#")
 @decimalmin("2000")
 private double salary;
  
 public user() {
 }
 public user(integer id, string account, string email, integer sex,
   position position, date createddate, double salary) {
  this.id = id;
  this.account = account;
  this.email = email;
  this.sex = sex;
  this.position = position;
  this.createddate = createddate;
  this.salary = salary;
 }
 public integer getid() {
  return id;
 }
 public void setid(integer id) {
  this.id = id;
 }
 public string getaccount() {
  return account;
 }
 public void setaccount(string account) {
  this.account = account;
 }
 public string getemail() {
  return email;
 }
 public void setemail(string email) {
  this.email = email;
 }
 public integer getsex() {
  return sex;
 }
 public void setsex(integer sex) {
  this.sex = sex;
 }
 public position getposition() {
  return position;
 }
 public void setposition(position position) {
  this.position = position;
 }
 public date getcreateddate() {
  return createddate;
 }
 public void setcreateddate(date createddate) {
  this.createddate = createddate;
 }
 public double getsalary() {
  return salary;
 }
 public void setsalary(double salary) {
  this.salary = salary;
 }
 @override
 public string tostring() {
  return "user [id=" + id + ", account=" + account + ", email=" + email
    + ", sex=" + sex + ", position=" + position + ", createddate="
    + createddate + ", salary=" + salary + "]";
 }
 
}

input.jsp,springmvc 表單標(biāo)簽知識點(diǎn)詳解

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%>
<%@page import="java.util.hashmap"%>
<%@page import="java.util.map"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
<!doctype html">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>springmvc 表單操作</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="stylesheet">
</head>
<body>
 
 <!--
 1. 使用 form 標(biāo)簽可以更快速的開發(fā)出表單頁面, 而且可以更方便的進(jìn)行表單值的回顯。
 step1 導(dǎo)入標(biāo)簽 taglib prefix="form" uri="http://www.springframework.org/tags/form"
 step2 和普通的form用法差不多。path 相當(dāng)于 普通的form的name,form:hidden 隱藏域,form:errors 提示錯誤信息。
 2. 使用form 標(biāo)簽需要注意:
 通過 modelattribute 屬性指定綁定的模型屬性, 該數(shù)據(jù)模型必須是實(shí)例化過的。
 若沒有 modelattribute 指定該屬性,則默認(rèn)從 request 域?qū)ο笾凶x取 command 的表單 bean (如果該屬性值也不存在,則會發(fā)生錯誤)。
 java.lang.illegalstateexception: neither bindingresult nor plain target object for bean name 'command' available as request attribute
 -->
 <div class="container">
 <div class="row">
  <div class="col-sm-6">
  <div class="panel panel-info" style="margin-top:10px;">
  <div class="panel-heading">
   <h3 class="panel-title">修改或創(chuàng)建用戶信息</h3>
  </div>
  <div class="panel-body">
   <form:form action="${pagecontext.request.contextpath }/user" method="post"
   modelattribute="user" class="form-horizontal" role="form">
   <c:if test="${user.id == null }">
    <!-- path 屬性對應(yīng) html 表單標(biāo)簽的 name 屬性值 -->
    <div class="form-group">
    <label class="col-sm-2 control-label">account</label>
    <div class="col-sm-10">
     <form:input class="form-control" path="account"/>
     <form:errors style="color:red" path="account"></form:errors>
    </div>
    </div>
   </c:if>
   <c:if test="${user.id != null }">
    <form:hidden path="id"/>
    <input type="hidden" name="_method" value="put"/>
    <%-- 對于 _method 不能使用 form:hidden 標(biāo)簽, 因?yàn)?modelattribute 對應(yīng)的 bean 中沒有 _method 這個屬性 --%>
    <%--
    <form:hidden path="_method" value="put"/>
    --%>
   </c:if>
   <div class="form-group">
    <label class="col-sm-2 control-label">email</label>
    <div class="col-sm-10">
    <form:input class="form-control" path="email"/>
    <form:errors style="color:red" path="email"></form:errors>
    </div>
   </div>
   <!-- 這是springmvc 不足之處 -->
   <%
    map<string, string> genders = new hashmap();
    genders.put("1", "male");
    genders.put("0", "female");
    request.setattribute("genders", genders);
   %>
   <div class="form-group">
    <label class="col-sm-2 control-label">sex</label>
    <div class="col-sm-10">
    <form:radiobuttons path="sex" items="${genders }" />
    </div>
   </div>
   <div class="form-group">
    <label class="col-sm-2 control-label">position</label>
    <div class="col-sm-10">
    <form:select class="form-control" path="position.id" items="${positions}" itemlabel="level" itemvalue="id">
    </form:select>
    </div>
   </div>
   <div class="form-group">
    <label class="col-sm-2 control-label">date</label>
    <div class="col-sm-10">
    <form:input class="form-control" path="createddate"/>
    <form:errors style="color:red" path="createddate"></form:errors>
    </div>
   </div>
   <div class="form-group">
    <label class="col-sm-2 control-label">salary</label>
    <div class="col-sm-10">
    <form:input class="form-control" path="salary"/>
    <form:errors style="color:red" path="salary"></form:errors>
    </div>
   </div>
   <input class="btn btn-success" type="submit" value="submit"/>
   </form:form>
  </div>
  </div>
  </div>
 </div>
 </div>
 
</body>
</html>

 i18n國際化文件

#語法:實(shí)體類上屬性的注解.驗(yàn)證目標(biāo)方法的modleattribute 屬性值(如果沒有默認(rèn)為實(shí)體類首字母小寫).注解修飾的屬性 
#以第一個為例:user實(shí)體類中 屬性account用了notempty注解修飾,表示不能為空。所以前綴是notempty 
#驗(yàn)證的目標(biāo)方法 public string save(@valid user user, ...) user被注解@valid 修飾,但沒有被modleattribute修飾。所以中間是user 
#后綴就是被注解修飾的屬性名 account 
notempty.user.account=用戶名不能為空 
email.user.email=email地址不合法 
 
#typemismatch 數(shù)據(jù)類型不匹配時提示 
typemismatch.user.createddate=不是一個日期 
#required 必要參數(shù)不存在時提示 
#methodinvocation 調(diào)用目標(biāo)方法出錯的時提示 

其他文件,position 實(shí)體類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class position {
 
 private integer id;
 private string level;
 
 public position() {
 }
 public position(integer id, string level) {
 this.id = id;
 this.level = level;
 }
 public integer getid() {
 return id;
 }
 public void setid(integer id) {
 this.id = id;
 }
 public string getlevel() {
 return level;
 }
 public void setlevel(string level) {
 this.level = level;
 }
 @override
 public string tostring() {
 return "position [id=" + id + ", level=" + level + "]";
 }
}

 模擬用戶操作的dao,userdao.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.collection;
import java.util.date;
import java.util.hashmap;
import java.util.map;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.repository;
import com.itdragon.springmvc.crud.orm.position;
import com.itdragon.springmvc.crud.orm.user;
 
@repository
public class userdao {
 
 private static map<integer, user> users = null;
 
 @autowired
 private positiondao positiondao;
 
 // 模擬數(shù)據(jù)庫查詢數(shù)據(jù)
 static{
 users = new hashmap<integer, user>();
 users.put(1, new user(1, "itdragon", "[email protected]", 1, new position(1, "架構(gòu)師"), new date(), 18888.88));
 users.put(2, new user(2, "blog", "[email protected]", 1, new position(2, "高級工程師"), new date(), 15555.55));
 users.put(3, new user(3, "welcome", "[email protected]", 0, new position(3, "中級工程師"), new date(), 8888.88));
 users.put(4, new user(4, "to", "[email protected]", 0, new position(4, "初級工程師"), new date(), 5555.55));
 users.put(5, new user(5, "you", "[email protected]", 1, new position(5, "java實(shí)習(xí)生"), new date(), 2222.22));
 }
 
 // 下一次存儲的下標(biāo)id
 private static integer initid = 6;
 
 public void save(user user){
 if(user.getid() == null){
  user.setid(initid++);
 }
  
 user.setposition(positiondao.getpositionbyid(user.getposition().getid()));
 users.put(user.getid(), user);
 }
 
 public collection<user> queryallusers(){
 return users.values();
 }
 
 public user getuserbyid(integer id){
 return users.get(id);
 }
 
 public void deleteuserbyid(integer id){
 users.remove(id);
 }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.collection;
import java.util.hashmap;
import java.util.map;
import org.springframework.stereotype.repository;
import com.itdragon.springmvc.crud.orm.position;
 
@repository
public class positiondao {
 
 private static map<integer, position> positions = null;
 
 static{
 positions = new hashmap<integer, position>();
  
 positions.put(1, new position(1, "架構(gòu)師"));
 positions.put(2, new position(2, "高級工程師"));
 positions.put(3, new position(3, "中級工程師"));
 positions.put(4, new position(4, "初級工程師"));
 positions.put(5, new position(5, "java實(shí)習(xí)生"));
 }
 
 // 模擬查詢所有數(shù)據(jù)
 public collection<position> queryallpositions(){
 return positions.values();
 }
 
 // 模擬通過id查詢數(shù)據(jù)
 public position getpositionbyid(integer id){
 return positions.get(id);
 }
 
}

用戶列表頁面的list.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
 
<!doctype html">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>springmvc 表單操作</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="stylesheet">
<script src="https://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
 $(function(){
 $(".delete").click(function(){
  var msg = confirm("確定要刪除這條數(shù)據(jù)?");
  if (true == msg) {
  $(this).onclick();
  } else {
  return false;
  }
 });
 })
</script>
</head>
<body>
 
 
 <!-- 用于刪除的form -->
 <form action="" method="post" id="deleteform">
 <input type="hidden" name="_method" value="delete"/>
 </form>
 
 <div class="container">
 <div class="row">
  <div class="col-sm-9">
  <c:if test="${empty requestscope.users }">
  沒有任何員工信息.
  </c:if>
  <c:if test="${!empty requestscope.users }">
  <div class="table-responsive">
   <table class="table table-bordered">
   <caption>用戶信息表 <a href="user" rel="external nofollow" class="btn btn-default" >add account</a></caption>
   <thead>
   <tr>
    <th>用戶編碼</th>
    <th>賬號名</th>
    <th>郵箱</th>
    <th>性別</th>
    <th>職位</th>
    <th>薪水</th>
    <th>時間</th>
    <th>編輯</th>
    <th>刪除</th>
   </tr>
   </thead>
   <tbody>
   <c:foreach items="${requestscope.users }" var="user">
    <tr>
    <td>${user.id }</td>
    <td>${user.account }</td>
    <td>${user.email }</td>
    <td>${user.sex == 0 ? 'female' : 'male' }</td>
    <td>${user.position.level }</td>
    <td>${user.salary }</td>
    <td><fmt:formatdate value="${user.createddate }" pattern="yyyy-mm-dd hh:mm:ss"/></td>
    <td><a href="user/${user.id}" rel="external nofollow" >edit</a></td>
    <td><a class="delete" href="delete/${user.id}" rel="external nofollow" >delete</a></td>
    </tr>
   </c:foreach>
   </tbody>
   </table>
  </div>
  </c:if>
  </div>
 </div>
 </div>
 
</body>
</html>

注意事項(xiàng)

javax.validation.unexpectedtypeexception: hv000030: no validator could be found for constraint '
使用hibernate validator出現(xiàn)上面的錯誤, 需要 注意
@notnull 和 @notempty 和@notblank 區(qū)別
@notempty 用在集合類上面
@notblank 用在string上面
@notnull 用在基本類型上

如果在基本類型上面用notempty或者notblank 會出現(xiàn)上面的錯,筆者將@notempty用到了date上,導(dǎo)致出了這個問題。若還有問題,還繼續(xù)在這里補(bǔ)充。

以上便是springmvc的表單操作,其中包含了常用知識,如數(shù)據(jù)的格式化,數(shù)據(jù)的校驗(yàn),提示信息國際化,form標(biāo)簽的用法。

原文鏈接:http://www.cnblogs.com/itdragon/p/7722255.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 91av亚洲| 黄网站免费入口 | 久久久三级免费电影 | 成人一级免费视频 | 久久精品视频一区二区三区 | 亚洲成人免费电影 | 自拍偷拍999 | 精品国产一区在线 | 欧美日韩高清一区二区三区 | 暖暖免费观看高清完整版电影 | 久久免费精品视频 | 性生活视频网站 | 久久久久久久久久久久久国产精品 | 成人午夜一区 | 一级做受大片免费视频 | 久久中文字幕在线观看 | 国产成人在线免费观看视频 | 国产精品一区二区x88av | 精品国产久 | 欧美乱码精品一区 | 日本一区二区免费在线播放 | 欧美人与物videos另类 | 久久久久亚洲国产精品 | jizzjizzjizz少妇 | 激情宗合| 成人毛片100部免费观看 | 深夜视频福利 | 免费a视频 | 久久精品79国产精品 | av免费在线播放 | 搜一级毛片 | 日韩视频不卡 | 日本黄色一级视频 | 伊人亚洲精品 | 日韩精品久久一区二区三区 | 99影视在线视频免费观看 | 曰批全过程120分钟免费69 | 久久久久久久久久久av | 91综合在线观看 | av资源在线 | 日本xxxx色视频在线观看免费, |