The Hibernator Validator framework follows the DRY (Don't Repeat Yourself) principle. Using Hibernator Validator you need to specify the constraints using annotations in the domain object. Once you specify the constraints you can use it in any layer of your application without duplicating it.
Hibernate Validator comes with basic buit-in constraints like @Length(min=, max=), @Max(value=), @Min(value=), @NotNull, @NotEmpty and so on. You can also build your own constraints easily.
In this example you will see how to integrate Struts 2 with Hibernator Validator using the Full Hibernate Plugin 1.4 GA.
You need to have all the lib files that we used in the previous example ( Struts 2 Hibernate Integration ).
The domain object User, with the validation constraints is shown below.
package com.vaannila.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.validator.Length; import org.hibernate.validator.NotEmpty; @Entity @Table(name = "USER") public class User implements Serializable { private static final long serialVersionUID = 6295524232169619097L; private Long id; private String name; private String password; private String gender; private String country; private String aboutYou; private Boolean mailingList; @Id @GeneratedValue @Column(name = "USER_ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @NotEmpty @Length(max=50) @Column(name = "USER_NAME", nullable = false, length = 50) public String getName() { return name; } public void setName(String name) { this.name = name; } @Length(min=6, max=10) @Column(name = "USER_PASSWORD", nullable = false, length = 10) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @NotEmpty(message="Please select a gender") @Column(name = "USER_GENDER") public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @NotEmpty(message="Please select a country") @Column(name = "USER_COUNTRY") public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @NotEmpty @Length(max=100) @Column(name = "USER_ABOUT_YOU", length = 100) public String getAboutYou() { return aboutYou; } public void setAboutYou(String aboutYou) { this.aboutYou = aboutYou; } @Column(name = "USER_MAILING_LIST") public Boolean getMailingList() { return mailingList; } public void setMailingList(Boolean mailingList) { this.mailingList = mailingList; } }
As you can see in addition to the JPA annotations you have the Hibernator Validator constraints.
The @NotEmpty constraint checks if the String is not null or not empty.
The @Length(min=6, max=10) constraint checks whether the lenght is within the min max range.
The validation messages are auto generated by the plug-in. You can also override the default message using the message attribute of the constraint. For gender and country properties we specify a customized message.
@NotEmpty(message="Please select a gender") @Column(name = "USER_GENDER") public String getGender() { return gender; } @NotEmpty(message="Please select a country") @Column(name = "USER_COUNTRY") public String getCountry() { return country; }
In the UserAction class you need to specify the @Valid annotation for the domain object that needs to be validated.
package com.vaannila.web; import java.util.ArrayList; import java.util.List; import org.hibernate.validator.Valid; import com.opensymphony.xwork2.ActionSupport; import com.vaannila.dao.UserDAO; import com.vaannila.dao.UserDAOImpl; import com.vaannila.domain.User; public class UserAction extends ActionSupport { private static final long serialVersionUID = -6659925652584240539L; @Valid private User user; private List<User> userList = new ArrayList<User>(); private UserDAO userDAO = new UserDAOImpl(); public String add() { userDAO.saveUser(user); return SUCCESS; } public String list() { userList = userDAO.listUser(); return SUCCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } }
Since we use the Hibernate Plugin you need to extend the package form hibernate-default package. The hibernate-default package has the following three interceptor stacks.
- basicStackHibernate: Struts2 basickStack + Hibernate session and transaction capability.
- defaultStackHibernate: Struts2 defaultStack (no validations) + Hibernate validation, session and transaction capability.
- defaultStackHibernateStrutsValidation: Struts2 defaultStack (with validation) + basicStackHibernate.
The struts configuration file is shown below.
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="default" extends="hibernate-default"> <action name="addUser" method="add" class="com.vaannila.web.UserAction"> <result name="input">/register.jsp</result> <result name="success" type="redirect">listUser</result> </action> <action name="listUser" method="list" class="com.vaannila.web.UserAction"> <interceptor-ref name="basicStackHibernate" /> <result name="success">/register.jsp</result> </action> </package> </struts>
By default the defaultStackHibernate interceptor stack will be used. In the addUser action we use this inteceptor stack since we need validation capability and during the listUser action action we use basicStackHibernate because we don't need validation capability this time.
In the register.jsp page instead of using the name attribute to specify the property value we use the key attribute. This is need for the default validation messages to be generated.
01.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
02.
pageEncoding="ISO-8859-1"%>
03.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
04.
<%@taglib uri="/struts-tags" prefix="s"%>
05.
<
html
>
06.
<
head
>
07.
<
meta
http-equiv
=
"Content-Type"
content
=
"text/html; charset=ISO-8859-1"
>
08.
<
title
>Registration Page</
title
>
09.
<
s:head
/>
10.
<
style
type
=
"text/css"
>
11.
@import url(style.css);
12.
</
style
>
13.
</
head
>
14.
<
body
>
15.
<
s:actionerror
/>
16.
<
s:form
action
=
"addUser"
>
17.
<
s:hidden
name
=
"user.id"
/>
18.
<
s:textfield
key
=
"user.name"
/>
19.
<
s:password
key
=
"user.password"
/>
20.
<
s:select
key
=
"user.gender"
list
=
"{'Male','Female'}"
headerKey
=
""
21.
headerValue
=
"Select"
label
=
"Gender"
/>
22.
<
s:select
key
=
"user.country"
list
=
"{'India','USA','UK'}"
headerKey
=
""
23.
headerValue
=
"Select"
label
=
"Country"
/>
24.
<
s:textarea
key
=
"user.aboutYou"
/>
25.
<
s:checkbox
key
=
"user.mailingList"
26.
label
=
"Would you like to join our mailing list?"
/>
27.
<
s:submit
/>
28.
</
s:form
>
29.
30.
31.
<
s:if
test="userList.size() > 0">
32.
<
div
class
=
"content"
>
33.
<
table
class
=
"userTable"
cellpadding
=
"5px"
>
34.
<
tr
class
=
"even"
>
35.
<
th
>Name</
th
>
36.
<
th
>Gender</
th
>
37.
<
th
>Country</
th
>
38.
<
th
>About You</
th
>
39.
<
th
>Mailing List</
th
>
40.
</
tr
>
41.
<
s:iterator
value
=
"userList"
status
=
"userStatus"
>
42.
<
tr
43.
class
=
"<s:if test="
#userStatus.odd == true ">odd</
s:if
><
s:else
>even</
s:else
>">
44.
<
td
><
s:property
value
=
"name"
/></
td
>
45.
<
td
><
s:property
value
=
"gender"
/></
td
>
46.
<
td
><
s:property
value
=
"country"
/></
td
>
47.
<
td
><
s:property
value
=
"aboutYou"
/></
td
>
48.
<
td
><
s:property
value
=
"mailingList"
/></
td
>
49.
</
tr
>
50.
</
s:iterator
>
51.
</
table
>
52.
</
div
>
53.
</
s:if
>
54.
</
body
>
55.
</
html
>
The key values should be specified in the UserAction.properties file and this file should be saved next to the UserAction.java file.
1.
user.name=User Name
2.
user.password=Password
3.
user.aboutYou=About You
4.
user.mailingList=Mailing List
The default validation messages will be generated using the field labels as prefix.
When you execute the example and submit the form without entering any values you will see the following validation messages.
The validation messge for the fields User Name, Password and About You has the field label before the default validation error message. This is because we specified the key values in theUserAction.properties file. If you only want the validation message to be displayed then don't specify an entry for that field in the properties file. Here the gender and the country fields have only the customized error messages and not the field labels.
Everything else remains the same as the previous example ( Struts 2 Hibernate Integration ).
You can download and try this example here.
相关推荐
本篇文章将详细探讨Struts2如何使用Validation框架进行数据验证。 一、Struts2 Validation框架概述 Struts2的Validation框架是用于处理用户输入验证的一种机制。它允许开发者定义验证规则,这些规则会在用户提交...
1. 添加依赖:在项目中引入Struts2和Validation相关的jar包,例如struts2-core、struts2-convention-plugin、hibernate-validator等。 2. 配置Struts2:在struts.xml配置文件中启用Struts2的验证插件,如`...
在Struts2中,Validation框架是用于处理数据验证的重要组件,它允许开发者在用户输入提交到服务器之前或之后进行验证,确保数据的准确性和完整性。下面将详细解释Struts2中的Validation框架及其在前后台验证中的应用...
**Hibernate Validation 深度解析与实践指南** Hibernate Validation 是一个强大的 Java Bean 验证框架,它是 JSR-303(Java Bean Validation)规范的实现,后来在 JSR-349 中进行了扩展,增加了更多的验证注解和...
综上所述,"Struts2_Validation"文件包很可能是围绕如何在Struts2中进行有效数据验证这一主题展开的,包括如何配置Validation.xml,编写验证规则,处理验证错误,以及如何结合其他Struts2特性进行更复杂的验证操作。...
Struts2提供了一些基于XWork Validation Framework的内建验证程序,它们大大简化了输入验证工作。 使用这些验证程序不需要编程,程序员只需要在一个XML文件里对验证程序应该如何工作做出声明就行了。需要声明的内容...
- **Validation Framework**:在 Action 类中使用 Struts 的验证框架进行数据校验,确保传入的数据符合预期。 #### 七、视图层设计 视图层负责显示数据,通常使用 JSP 页面。 - **JSP 页面**:展示用户界面,与...
Struts2 Validation是Apache Struts框架的一个重要组成部分,主要用于处理Web应用中的数据验证。这个框架提供了灵活且强大的机制,帮助开发者实现对用户输入的有效性检查,确保数据的准确性和安全性。下面将详细介绍...
标题中的“spring2.5 struts2 hibernate”是指一种经典的Java Web开发技术栈,它由Spring框架的2.5版本、Struts2框架和Hibernate ORM工具组成。这个技术组合在2000年代中期至后期非常流行,用于构建企业级的Web应用...
Struts框架的主要模块包括Action,Form Bean,Validation,Tiles等。 Hibernate框架 Hibernate是一个开源的关系数据库持久层框架,它提供了一个通用的数据访问层,帮助开发者快速构建企业级应用程序。Hibernate...
而Hibernate Validation则是Java世界中用于数据验证的主流库,它基于JSR 303和JSR 349标准,提供了丰富的验证规则和易于使用的API。在Spring MVC中集成Hibernate Validation,可以实现对输入数据的有效性检查,从而...
### JavaEE企业应用实战-Struts2+Spring3+Hibernate整合开发(第3版)核心知识点解析 #### 一、JavaEE概述与架构 - **JavaEE简介**:JavaEE(Java Platform, Enterprise Edition)是Java平台的企业版,提供了一套...
本文将深入探讨Resin如何支持Spring MVC 5.0及以上版本,以及它对Hibernate Validation的支持。 首先,Spring MVC 5.0引入了许多改进和新特性,例如对Java 8的全面支持、更好的类型安全的模型绑定、增强的路径变量...
Struts2、Hibernate3.2和Spring2.5是Java Web开发中著名的SSH(Struts2、Spring、Hibernate)框架的三个核心组件。这组框架的整合为开发者提供了强大的MVC(模型-视图-控制器)架构支持,使得企业级应用的开发变得...
Struts和Hibernate是两个流行的Java开发框架,Struts主要用于处理Web应用中的用户交互和业务逻辑,而Hibernate则是一个对象关系映射(ORM)工具,负责将数据库操作与Java对象解耦。将两者整合在一起可以创建出高效且...
"Struts2+Hibernate实现用户登录和增删改查案例" 本文将介绍Struts2+Hibernate实现用户登录和增删改查案例的详细实现过程。通过本文,读者可以了解Struts2和Hibernate的基本概念和使用方法,并学习如何将它们结合...
Struts和Hibernate是两个流行的Java开发框架,它们分别用于处理MVC(模型-视图-控制器)架构的控制层和持久层。这篇文章将详细介绍如何整合这两个框架,以便在一个Web应用程序中实现数据管理与用户交互。 **一、...
文档列举了引用 Hibernate Validation各注解的用法,完成对实体约束验证的配置。