`

JEE6/JSF2.0 error messages, bean validation and i18n

 
阅读更多

With JEE6/JSF2.0, validation can be done by bean validation annotations. these annotations can be put on the JEE6 entity beans OR managed backing beans, as long as they conform to the Java Bean requirement, ie, providing getter and setter methods for instance variables.

 

Bean validation messages are i18n ready. To internationalize the validation messages, you need to provide the localized messages in a properties file "ValidationMessages.properties" and put it under the applications class path. For web applications, this would be "WEB-INF/classes". This is similar to JSF's i18n solution. But you don't need to configure it in "web.xml" or "faces-config.xml", since it's bean validation framework available to you automatically.

 

For example, if you want to support both English and Chinese for your bean validation, you can provide the messages in two files and put them under "WEB-INF/classes":

 

WEB-INF/classes/ValidationMessages.properties

WEB-INF/classes/ValidationMessages_zh.properties

 

Following is an example of ValidationMessages.properties :

bean.validate.username.required=username is required to login
bean.validate.nameFilter.required=name filter is required to search!
bean.validate.nameFilter.short=name filter too short, at least 3 chars

 

And the corresponding message for Chinese support from ValidationMessages_zh.properties :

bean.validate.username.required=\u7528\u6237\u540D\u662F\u5FC5\u987B\u5730\uFF01
bean.validate.nameFilter.required=\u540D\u5B57\u662F\u5FC5\u987B\u5730\uFF0C\u5A9A\u7EB8\uFF01
bean.validate.nameFilter.short=\u540D\u5B57\u592A\u77ED\u4E86\uFF0C\u81F3\u5C11 3 \u4E2A\u5B57\u7B26

 

Here's an exmple for JEE entity bean:

package com.jxee.model;

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 javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

/**
 * entity bean to table "test.user"
 * validation done here as well -- this is excellent!
 */
@Entity
@Table(name="USER", uniqueConstraints = @UniqueConstraint(columnNames = "username"))
public class User implements Serializable {
  
  @Id
  @GeneratedValue
  @Column(name="id")
  private Integer userid;
  
  @Column(name="username")
  // NotNull validation message are localized and defined in
  // ValidationMessages.properties/ValidationMessages_zh.properties
  @NotNull(message="{bean.validate.username.required}")
  // Size validation message is hard-coded here:
  @Size(min=4,max=20,message="username must be 4-20 characters")
  private String username;

  // other instance variables, getters and setters...

}

 

 

The following code illustrates how to use it in you bean class (the managed student search bean):

 

package com.jxee.action.student;

import java.io.Serializable;
import java.util.List;
import java.util.TimeZone;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.inject.Inject;

// bean validation annotations
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.log4j.Logger;

import com.jxee.ejb.student.StudentDAO;
import com.jxee.model.student.Student;

@ManagedBean(name="ss")
@ViewScoped
public class StudentSearchUseFlash implements Serializable {

  private static final Logger log = Logger.getLogger(StudentSearchUseFlash.class);
  private static final String SEARCH_PAGE = "/student/studentSearch.xhtml";
  
  private List<Student> searchResultList;
  private @EJB StudentDAO dao;

  // use bean validation to validate the search filter
  @NotNull(message="{bean.validate.nameFilter.required}")
  @Size(min=3, message="{bean.validate.nameFilter.short}")
  private String nameFilter;

  private int maxRows = 50;

  ......

} 

 

 

To display the localized bean validation message, you use <h:messages/>, <h:message for="inputId"/>, or Primefaces tags <p:messages/> and <p:message for="inputId"/>. This is standard JSF2.0 stuff, as illustrated here:

 

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
   				xmlns:h="http://java.sun.com/jsf/html"
      			xmlns:f="http://java.sun.com/jsf/core"
      			xmlns:ui="http://java.sun.com/jsf/facelets"
      			xmlns:p="http://primefaces.org/ui"
   				template="/template/template1.xhtml">
   				
	<ui:define name="title">#{msgs.studentSearch}</ui:define>
    
	<ui:define name="content">
		<h:form id="searchForm">
		    <p:panel header="#{msgs.studentSearch}" style="width:60%">
	        <h:panelGrid columns="4">
	            <h:outputLabel value="#{msgs.name}: "/>
	            <h:inputText id="nf" value="#{ss.nameFilter}"/>
	            <p:message for="nf"/>
	            <h:commandButton type="submit" value="#{msgs.search}" 
                                     action="#{ss.findByName}"/>
	        </h:panelGrid>
		    </p:panel>
		</h:form>
		    	
		......

         </ui:define>
</ui:composition>

 

Here's the screen shot for the student search screen, where it requires the name filter to be at 3 characters long:


 

We can see that bean validation framework and JSF2 can work together pretty well.

 

One last thing to mention is how to localize a FacesMessage in my program? That is, how to access the i18n messages in backing beans? Since the i18n messages are handled as resource bundles, you need to reference it by the ResourceBundle class:

 

FacesContext cntxt = FacesContext.getCurrentInstance();
Locale locale = cntxt.getViewRoot().getLocale();
// load the i18n messages as resource bundle to access
// note: the base name must match the file path, ie, "/com/jxee/messages.properties"
ResourceBundle messages = ResourceBundle.getBundle("com.jxee.messages", locale);
String msg = messages.getString("nameFilterRequired");
log.debug("error message: " + msg);
cntxt.addMessage(null, new FacesMessage(msg));
 

 

This might be useful when it comes to cross-field validations. For single field vaidation, bean validation is handy and clean, thus much easier to use.

 

  • 大小: 16.8 KB
分享到:
评论

相关推荐

    JEE6编程模型

    CDI(Contexts and Dependency Injection,上下文和依赖注入)是JEE6中引入的一套全新的依赖注入规范。CDI旨在统一不同组件之间的依赖注入和生命周期管理,支持对Java EE组件的依赖查找和注入操作。CDI通过注解来...

    jee6 学习笔记 5 - Struggling with JSF2 binding GET params

    在Java企业版(Java EE)6的开发过程中,JSF(JavaServer Faces)2.0是用于构建用户界面的重要组件。这篇"jee6 学习笔记 5 - Struggling with JSF2 binding GET params"主要探讨了开发者在使用JSF2绑定GET参数时可能...

    jaxb2.0 JEE5

    JEE5规范中提出。从java对象转成xsd,反之也可以

    websphere6 ejb2.0

    【描述】:WebSphere 6是一个由IBM推出的强大企业级应用服务器,它支持Java Enterprise Edition(JEE)规范,其中包括EJB 2.0(Enterprise JavaBeans 2.0)。EJB 2.0是Java平台上用于构建分布式企业级应用程序的核心...

    JEE6 (JSR316) Final Draft.pdf

    6. **Bean Validation**:提供了一种声明式的验证机制,允许开发者定义复杂的业务规则,确保数据的完整性和正确性。 7. **批处理**:通过JSR 352定义了批处理操作的标准API,便于执行大型批处理任务。 ##### 技术...

    restlet2.0版本jee源代码

    9. **测试和支持(Testing and Support)**: 除了源代码,Restlet 2.0还提供了示例和测试用例,帮助开发者更好地理解和学习如何使用框架。此外,社区支持和官方文档也提供了丰富的资源。 10. **版本2.0.14**: 这个...

    pet-catalog:JEE6版本

    宠物目录样本这是一个完整的 JEE6 示例,包含 JSF2.0、EJB3.1 和 JPA2.0。 此示例使用 Stackato 旧版构建包中的 JavaEE 框架。数据库配置因为我们已经在 manifest.yml 文件中指定了一个framework标签,所以 Stackato...

    Create a Java EE 6 Application with JSF 2, EJB 3.1, JPA, and NetBeans IDE 7

    在本教程中,我们将深入探讨如何使用Java EE 6中的核心技术——JavaServer Faces 2.0 (JSF),Enterprise Java Beans 3.1 (包括Session Bean和Message-Driven Bean)以及Java Persistence API (JPA),结合NetBeans IDE...

    jee 入门(深入浅出学习JEE)

    【JEE入门(深入浅出学习JEE)】 Java企业版(Java Enterprise Edition,简称JEE),也称为Java EE,是Oracle公司推出的企业级应用程序开发平台。它为开发分布式、多层架构的Web应用程序提供了全面的框架和服务。JEE...

    jee6poc:使用 JEE6 平台的概念证明。 使用 Deltaspike、JSF 和 Primefaces 和 JBoss Logging

    jee6poc 使用 JEE6 平台的概念证明。 它使用 Deltaspike、JSF with Primefaces 和 JBoss Logging。 JBoss 环境设置 概念验证参考环境是 JBoss EAP 6.3GA,需要正确配置 POC 才能按预期工作。 先决条件 安装并配置了...

    Code-Samples:JavaJEE示例代码

    具有Servlet,RESTful服务和JSF 2.0接口的Web应用程序。 REST服务以XML(使用JAXB),JSON和纯文本形式返回信息。 JPA实体bean(数据库:Oracle 11g) (有关其他代码示例,请参见[Gists:] )

    jee6 学习笔记 6.3 - @Asynchronous

    `@Asynchronous`是Java EE 6引入的EJB 3.1规范的一部分,它可以应用在无状态会话bean(Stateless Session Bean)的方法上。当一个带有`@Asynchronous`的方法被调用时,调用者会立即返回,而实际的方法执行将在另一...

    JEE-Full-Stack-2.0

    【标题】"JEE-Full-Stack-2.0"是一个涵盖了Java企业级开发全栈技术的项目或教程,旨在帮助开发者掌握从后端到前端的全套技能。在这个项目中,我们将深入探讨JEE(Java Enterprise Edition)的核心技术和现代Web开发...

    JEE5_API1-JEE5_API1

    - JSF是一个用于构建用户界面的MVC(Model-View-Controller)框架,JSF 1.2在JEE5中引入,提供了一套标准的UI组件和事件处理机制。 - **UI组件**:例如按钮、输入字段等,通过HTML标签或自定义组件实现。 - **...

    jee 参考手册 (实用版)

    除了这些核心组件,JEE还包括了其他服务,如JNDI(Java Naming and Directory Interface)用于服务发现,JPA(Java Persistence API)用于对象关系映射,以及JAX-RS(Java API for RESTful Web Services)用于构建...

    JEE7帮助文档.rar

    JEE7是该平台的一个重要版本,它在JEE6的基础上进行了一系列的改进和增强,旨在提高开发效率、简化编程模型,并引入了云服务支持。JEE7帮助文档是开发者在学习和使用JEE7时的重要参考资料,包含了详细的API文档、...

    eclipse-jee-indigo-SR1-win32(6/6)

    eclipse-jee-indigo-SR1-win32(6/6)

    jee6 学习笔记 1 - 开发环境的配置

    NULL 博文链接:https://jxee.iteye.com/blog/1575432

    基于SpringBoot2.0的极简低门槛JEEWEB前后端分离开发源码

    本源码是一款基于SpringBoot2.0、MyBatis、Shiro等框架构建的极简JEEWEB平台,支持前后端分离开发。包含3555个文件,涵盖1021个Java类、775个JavaScript脚本、617个HTML页面、221个PNG图片、197个GIF图片、178个CSS...

Global site tag (gtag.js) - Google Analytics