javascript
rest spring_Spring REST:异常处理卷。 3
rest spring
這是該系列中有關Spring REST異常處理的最后一篇文章。 最后,這次我將討論在表單處理期間可能發生的REST異常的處理。 因此,在本教程中,您將看到與REST,表單和異常處理有關的所有內容。 客戶端呢? JQuery將用于反映REST服務的所有響應。
與以前的教程一樣,我將使用Smartphone應用程序 。 現在是宣布此帖子主要目的的好時機– 智能手機實體需要在創建和編輯之前進行驗證。
讓我們看一下更新的Smartphone類:
@Entity @Table(name="smartphones") public class Smartphone {@Id@GeneratedValueprivate Integer id;@Length(min=1, max=20)private String producer;@Length(min=1, max=20)private String model;@Range(min=1, max=1500)private double price;/*** Method updates already existed {@link Smartphone} object with values from the inputed argument.* @param sPhone - Object which contains new Smartphone values.* @return {@link Smartphone} object to which this method applied.*/public Smartphone update(Smartphone sPhone) {this.producer = sPhone.producer;this.model = sPhone.model;this.price = sPhone.price;return this;}@Overridepublic String toString() {return producer+": "+model+" with price "+price;}//getters and setters are omitted}請注意@Length和@Range批注。 這些注釋是bean驗證的標準方法。 通過添加以下依賴項來更新已存在的pom.xml文件后,可以使用這些注釋:
org.hibernatehibernate-validator5.0.1.Finaljavax.validationvalidation-api1.1.0.Final在此之后,我需要更新messages.properties文件:
Length.smartphone.producer = Length of a Smartphone producer should be from 1 to 20 characters. Length.smartphone.model = Length of a Smartphone model should be from 1 to 20 characters. Range.smartphone.price = Price of a Smartphone should be from 1 to 1 500.00 $現在,讓我們看一下SmartphoneController類中的createSmartphone方法:
...@RequestMapping(value="/create", method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.APPLICATION_JSON_VALUE)@ResponseBodypublic Smartphone createSmartphone(@RequestBody @Valid Smartphone smartphone) {return smartphoneService.create(smartphone);} ...@Valid注釋應用于方法參數。 要特別注意缺少BindingResult ,它不需要像傳統的Spring MVC應用程序中那樣進行驗證。 如果Smartphone對象中的某些屬性的值不合適,則@Value批注將引發MethodArgumentNotValidException 。
在實體創建/編輯期間處理異常需要使用不同的模型來表示信息。 我的意思是上一篇文章中的 ErrorInfo類。 我們需要傳輸其他信息,其中包含錯誤字段名稱和該字段的某些錯誤消息。 為此,這里是一個新類:
public class ErrorFormInfo {private String url;private String message;private List< FieldErrorDTO > fieldErrors = new ArrayList< FieldErrorDTO >();public ErrorFormInfo() {}public ErrorFormInfo(String url, String message) {this.url = url;this.message = message;}public ErrorFormInfo(List< FieldErrorDTO > fieldErrors, String url, String message) {this.fieldErrors = fieldErrors;this.url = url;this.message = message;}//getters and setters are omitted}第二個類是FieldErrorDTO它在上面的代碼示例中使用:
public class FieldErrorDTO {private String fieldName;private String fieldError;public FieldErrorDTO(String fieldName, String fieldError) {this.fieldName = fieldName;this.fieldError = fieldError;}//getters and setters are omitted}引入錯誤傳輸對象后,我可以繼續@ControllerAdvice類中的錯誤處理。 這是RestExceptionProcessor類的代碼片段:
...@ExceptionHandler(MethodArgumentNotValidException.class)@ResponseStatus(value=HttpStatus.BAD_REQUEST)@ResponseBodypublic ErrorFormInfo handleMethodArgumentNotValid(HttpServletRequest req, MethodArgumentNotValidException ex) {String errorMessage = localizeErrorMessage("error.bad.arguments");String errorURL = req.getRequestURL().toString();ErrorFormInfo errorInfo = new ErrorFormInfo(errorURL, errorMessage);BindingResult result = ex.getBindingResult(); List< FieldError > fieldErrors = result.getFieldErrors();errorInfo.getFieldErrors().addAll(populateFieldErrors(fieldErrors));return errorInfo;}/*** Method populates {@link List} of {@link FieldErrorDTO} objects. Each list item contains* localized error message and name of a form field which caused the exception.* Use the {@link #localizeErrorMessage(String) localizeErrorMessage} method.* * @param fieldErrorList - {@link List} of {@link FieldError} items* @return {@link List} of {@link FieldErrorDTO} items*/public List< FieldErrorDTO > populateFieldErrors(List< FieldError > fieldErrorList) {List< FieldErrorDTO > fieldErrors = new ArrayList< FieldErrorDTO >();StringBuilder errorMessage = new StringBuilder("");for (FieldError fieldError : fieldErrorList) {errorMessage.append(fieldError.getCode()).append(".");errorMessage.append(fieldError.getObjectName()).append(".");errorMessage.append(fieldError.getField());String localizedErrorMsg = localizeErrorMessage(errorMessage.toString());fieldErrors.add(new FieldErrorDTO(fieldError.getField(), localizedErrorMsg));errorMessage.delete(0, errorMessage.capacity());}return fieldErrors;}/*** Method retrieves appropriate localized error message from the {@link MessageSource}.* * @param errorCode - key of the error message* @return {@link String} localized error message */public String localizeErrorMessage(String errorCode) {Locale locale = LocaleContextHolder.getLocale();String errorMessage = messageSource.getMessage(errorCode, null, locale);return errorMessage;} ...可以通過本文開頭的鏈接找到RestExceptionProcessor類的完整版本。 我希望上面的代碼片段能自我解釋。 如果否,請隨時在評論中提問。
我需要做的最后一件事是開發客戶端代碼端:
$(document).ready(function() {$('#newSmartphoneForm').submit(function(event) {var producer = $('#producer').val();var model = $('#model').val();var price = $('#price').val();var json = { "producer" : producer, "model" : model, "price": price};$.ajax({url: $("#newSmartphoneForm").attr( "action"),data: JSON.stringify(json),type: "POST",beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "application/json");xhr.setRequestHeader("Content-Type", "application/json");$(".error").remove();},success: function(smartphone) {var respContent = "";respContent += "Smartphone was created: [";respContent += smartphone.producer + " : ";respContent += smartphone.model + " : " ;respContent += smartphone.price + "]";$("#sPhoneFromResponse").html(respContent); },error: function(jqXHR, textStatus, errorThrown) {var respBody = $.parseJSON(jqXHR.responseText);var respContent = "";respContent += "";respContent += respBody.message;respContent += "";$("#sPhoneFromResponse").html(respContent);$.each(respBody.fieldErrors, function(index, errEntity) {var tdEl = $("."+errEntity.fieldName+"-info");tdEl.html(""+errEntity.fieldError+"");});}});event.preventDefault();});});客戶端new-phone.jsp文件的完整版本可通過本文開頭的鏈接找到。
到此為止,我必須對上面文章中開發的所有內容進行演示。 因此場景很簡單,我將打開“新智能手機”頁面并提交包含無效數據的表單。
摘要
 我希望我關于Spring REST應用程序中的異常處理的三篇文章對您有所幫助,并且您學到了一些新知識。 這些文章僅重點介紹了異常處理的基本流程,以及您只能在實際項目的整個實踐中獲得的所有其他內容。 感謝您閱讀我的博客。 
翻譯自: https://www.javacodegeeks.com/2013/12/spring-rest-exception-handling-vol-3.html
rest spring
總結
以上是生活随笔為你收集整理的rest spring_Spring REST:异常处理卷。 3的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 苹果电脑跳出广告(苹果电脑总有广告弹窗怎
- 下一篇: mx3无法连接电脑(索尼mx3怎么连电脑
