Validation

A considerable part of the XML Schema language deals with facets, enabling the programmer to restrict the basic datatypes. We have seen that the JAXB compiler doesn't care much about these facets as it just translates the basic datatype into one of Java's built-in types. A meticulous interpretation of these facets for checking that the XML data meets the constraints must be done during a schema validation.

If you want to validate your document before it is unmarshalled, JAXB lets you request validation by passing an object of the class javax.xml.validation.Schema to the Unmarshaller object. First, you create this schema object by setting up a schema factory for the schema language of your choice. Then you create the Schema object by calling the factory's method newSchema:

Schema mySchema;
SchemaFactory sf = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
try {
mySchema = sf.newSchema( file );
} catch( SAXException saxe ){
// ...(error handling)
mySchema = null;
}

After the Unmarshaller object has been established, you pass it the schema.

JAXBContext jc = JAXBContext.newInstance( packagePath );
Unmarshaller u = jc.createUnmarshaller();
u.setSchema( mySchema );

Basically that's all there is to it. If the XML data validation fails, an UnmarshalException (from javax.xml.bind) is thrown. Make sure to let the user of your program see the exception message so that the problem can be fixed. If you'd like to create your own error messages, you can pass a ValidationEventCollector to the unmarshaller which will store validation events into it so that you can retrieve an event and query its individual attributes. Insert these lines before you call the unmarshal method:

ValidationEventCollector vec = new ValidationEventCollector();
u.setEventHandler( vec );

The best place for checking the event collector is in the finally phrase of the try statement wrapping all of this:

if( vec != null && vec.hasEvents() ){
for( ValidationEvent ve: vec.getEvents() ){
String msg = ve.getMessage();
ValidationEventLocator vel = ve.getLocator();
int line = vel.getLineNumber();
int column = vel.getColumnNumber();
System.err.println( origin + ": " + line + "." + column + ": " + msg );
}
}

Now this looks as if the validation process would be kind enough to present you with all the errors in your XML document, or at least as many as possible but, alas, it appears that the validation process throws an exception as soon as the first deviation is detected. If you want to continue as long as possible, you'll have to catch all errors with a ValidationEventHandler.

Validation Event Handling

The interface javax.xml.bind.ValidationEventHandler is quite simple. Implementing classes must provide a single method to catch a ValidationEvent as we've seen it in the previous section.

boolean handleEvent( ValidationEvent event )

To register, the Unmarshaller method setEventHandler is called. If the calling object is implementing the event handler interface, we might write:

Unmarshaller u = jc.createUnmarshaller();
u.setEventHandler( this );

JAXB - Validate Document before It is Unmarshalled的更多相关文章

  1. 《JavaScript 源码分析》之 jquery.unobtrusive-ajax.js

    /*! ** Unobtrusive Ajax support library for jQuery ** Copyright (C) Microsoft Corporation. All right ...

  2. dom4j使用总结

    1.加载Xml 从文件加载 SAXReader reader = new SAXReader(); String filePath = "/xmlfile/" + fileName ...

  3. 利用JS提交表单的几种方法和验证

    第一种方式:表单提交,在form标签中增加onsubmit事件来判断表单提交是否成功 <script type="text/javascript"> function ...

  4. jquery.unobtrusive-ajax.js的扩展,做到片段式加载

    //ajax支持库 /*! ** Unobtrusive Ajax support library for jQuery ** Copyright (C) Microsoft Corporation. ...

  5. jquery.unobtrusive-ajax.js源码阅读

    /*! ** Unobtrusive Ajax support library for jQuery ** Copyright (C) Microsoft Corporation. All right ...

  6. ASP.NET jQuery 随笔 使用allValidator插件简单实现客户端验证功能

    首先放出该插件的下载地址:http://pan.baidu.com/s/1Aa3yD,里面有帮助文档,详细了解可以自行下载学习,本章只讲解一些基本的验证功能,页面代码如下: <%@ Page L ...

  7. 纯JS实现图片验证码功能并兼容IE6-8

    最近要搞一个图片验证码功能,但是又不想自己写后台代码.于是自己准备搞一个纯前端的验证码功能,于是网上搜索了一下,找到一个插件gVerify.js,简单好用,实现完美.不过后面接到说要兼容IE8,想想也 ...

  8. AugularJS从入门到实践(三)

      前  言  前端    AngularJS是为了克服HTML在构建应用上的不足而设计的.(引用百度百科) AngularJS使用了不同的方法,它尝试去补足HTML本身在构建应用方面的缺陷.Angu ...

  9. JS表单提交的几种方式

    第一种方式 : 表单提交,在 form 标签中增加 onsubmit 事件来判断表单是否提交成功 <script type="text/javascript"> fun ...

随机推荐

  1. HDU-2262 Where is the canteen 概率DP,高斯消元

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2262 题意:LL在一个迷宫里面转,每次走向周围能走的点的概率都是一样的,现在LL要随机的走到cante ...

  2. [.NET]c#.net程序中使用ffmpeg.exe来处理视频并生成上传视频的截图

    添加如下前台代码: <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Butto ...

  3. jitsi-meet

    Jitsi Meet在Ubuntu上的快速安装与卸载 1. 进入到终端,切换到root用户 # sudo su 添加相应的代码仓库: # echo 'deb http://download.jitsi ...

  4. PT100运算放大器电路

     运放输出电压<=运放电源电压,电源电压能决定它的最大输出能力即动态范围,若是电源为0-5v,则输出就只能在这之间. 其次要是放大电路,反馈必须接成负反馈 由于我这次使用的电源是5V,要是采用两 ...

  5. nyoj 975 关于521

    关于521 时间限制:1000 ms  |  内存限制:65535 KB 难度:2   描述 Acm队的流年对数学的研究不是很透彻,但是固执的他还是想一头扎进去. 浏览网页的流年忽然看到了网上有人用玫 ...

  6. 在线性级别时间内找出无序序列中的第k个元素

    在一个无序序列中找出第k个元素,对于k很小或者很大时可以采取特殊的方法,比如用堆排序来实现 .但是对于与序列长度N成正比的k来说,就不是一件容易的事了,可能最容易想到的就是先将无序序列排序再遍历即可找 ...

  7. NPOI导出Excel示例

    摘要:使用开源程序NPOI导出Excel示例.NPOI首页地址:http://npoi.codeplex.com/,NPOI示例博客:http://tonyqus.sinaapp.com/. 示例编写 ...

  8. Python FTP多线程爆破脚本

    初学python, 自己编写了个FTP多线爆破小脚本代码很丑= = #!usr/bin/env python #!coding=utf-8 __author__='zhengjim' from ftp ...

  9. sqlite3使用教程1 SQLite 命令

    http://www.runoob.com/sqlite/sqlite-commands.html 本章将向您讲解 SQLite 编程人员所使用的简单却有用的命令.这些命令被称为 SQLite 的点命 ...

  10. C# Winform 支持Hex与ASCII输入和切换的文本框

    最近一直在做一个支持串口,TCP,UDP通讯调试的一体化工具(也就是C#串口调试工具 v2.0的第三版),其中涉及到16进制数据和ASCII码的输入,所以继承了TextBox的基础上,写了这个支持He ...