錯誤信息包括兩種,一種是異常信息的顯示,一種是後臺驗證信息顯示。並且顯示又分直接頁面跳轉的提交,和經過Ajax的提交。 先看,異常信息與直接頁面跳轉的例子。在例子中,運用play框架的catch註解標籤統一處理: 自定義異常類 app.models.MyException:javascript
package models; public class MyException extends Exception{ public MyException(Exception e) { super(e); } public MyException(String msg){ super(msg); } public MyException(String msg, Exception e) { super(msg,e); } }
控制器父類 app.controllers.Application.java中的攔截方法,這裏處理了html請求與ajax請求css
@Catch(MyException.class) public static void ExceptionCatcher(MyException e){ String accept= request.headers.get("accept").toString(); String s[]=accept.split(","); String msg = e.getMessage(); if (s[0].equalsIgnoreCase("[text/html")){ render("errors/550.html",msg); } else if (s[0].equalsIgnoreCase("[application/json")){ Validation.clear(); //有了異常只顯示異常信息,清空以前的validation數據 Validation.addError("ServerError" ,msg); Response.current().status = 550; renderText(JSONUtil.parseObject(Validation.errors())); } else{ render("errors/550.html",msg); } }
製造一個簡單的異常 app.controllers.CalcAction.java:html
package controllers; import models.MyException; public class CalcAction extends Application{ public static void zero() throws MyException{ try{ int ka = 2/0; }catch(Exception e){ throw new MyException(e); } } }
routes中路由節點java
GET /zero CalcAction.zero
錯誤信息的i18n對應文檔,conf/messagesajax
# Validation messages validation.required=%s不能爲空 validation.minSize=%s長度必須大於%d位 validation.maxSize=%s長度不能超過%d位 validation.range=%s必須在 %d和 %d之間 validation.equals=%s必須一致 validation.email=電子郵箱(Email)格式不正確 validation.phone=手機號格式不正確 validation.isTrue=%s must be checked validation.match=%s格式不正確 validation.min=%s必須大於%d validation.invalid=%s輸入無效 validation.unique=%s已存在 serverError=服務器異常,請聯繫管理員
錯誤顯示頁面 views/errors/550.htmljson
Application error <h1>Oops, an error occured</h1> This exception has been logged with id <strong>${msg}</strong>.
顯示結果: 而後是後臺的驗證信息與ajax方式提交的顯示,這種狀況在數據校驗的時候經常使用。統一校驗已經在系列前文中提到,這裏就直接上代碼了,重在顯示驗證錯誤信息的顯示。 使用的models,其中包含了驗證字段,app.models.User.java:服務器
package models; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import play.data.validation.Email; import play.data.validation.MinSize; import play.data.validation.Required; import play.db.jpa.GenericModel; @Entity @Table(name="user") public class User extends GenericModel { @Id public long id; @Required public String code; @MinSize(value = 4) public String name; public String pwd; public int sex; @Email public String email; public String regip; public Date regtime; }
控制器父類 app.controllers.Application.java中的攔截方法app
@Catch(MyException.class) @Before public static void validationIntercept() { if(validation.hasErrors()){ response.status = 550; renderText(JSONUtil.parseObject(validation.errors())); } }
routes路由框架
POST /user UserAction.save
添加用戶的界面veiw/Application/reg.html,這裏爲了方便,將html與javascript代碼寫在一塊兒了。經過引入#{i18n /}能夠直接調用i18n函數,進行國際化。函數
#{extends 'main.html' /} #{set title:'Home' /} #{i18n /} <script type="text/javascript"> var submitform = function(){ $.ajax({ url: "/user", type: "POST", dataType: "json", data: $("#myform").serialize(), success: function(data){ window.location.href="/user/"+data; }, error: function(XMLHttpRequest, textStatus, errorThrown){ if (XMLHttpRequest.status == 550) { var exp = JSON.parse(XMLHttpRequest.responseText); showMsg(exp); } } }); } var showMsg = function(exp,obj){ for(var i=exp.length-1;i>=0;i--){ var object=$('#myform input[name="'+exp[i].key+'"]'); if(exp[i].key!="ServerError"){ object.parent().next().css('color','red'); var error=object.prev().html(); object.parent().next().html(i18n(exp[i].message,error,exp[i].variables[0],exp[i].variables[1])); if(i==0){ object.focus(); } }else{ showMsg(i18n(exp[i].message, exp[i].key)); } } } </script> <body> <div style="padding-left:20px;padding-top: 20px;"> <form action="/user" method="post" id="myform"><div> <label>用戶名:</label><input type="text" id="code" name="user.code"/></div><span></span><br/> <div><label>暱稱:</label><input type="text" id="name" name="user.name"/></div><span></span><br/> <div><label>密碼:</label><input type="password" id="pwdid" name="user.pwd"/></div><span></span><br/> <div><label>郵箱:</label><input type="text" id="email" name="user.email"/></div><span></span><br /> <div><label>性別:</label><label><input type="radio" name="user.sex" value="1"checked="checked">男</label> <label><input type="radio" name="user.sex" value="0">女</label></div><span></span> <input type="button" value="submit" onclick="submitform()"> </form> </div> </body>
測試結果: