我正在嘗試學習 Spring Boot。
Control Object partial code:
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class WatchlistItem {
@NotBlank(message="Please enter the title")
private String Title;
private String Rating;
private String Priority;
@Size(max=50, message="Comment should be maximum of 50 characters")
private String Comment;
private Integer ID;
控制器部分代碼:
@PostMapping("/watchlistItemForm")
public ModelAndView getWatchlistItem(@Valid WatchlistItem watchlistItem, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return new ModelAndView("watchlistItemForm");
}
WatchlistItem exisiting = findWatchlistItem(watchlistItem.getID());
if (exisiting == null) {
watchlistItem.setID(index );
watchlistItems.add(watchlistItem);
}else {
//if it is existing then it changes the attributes.
}
RedirectView view = new RedirectView();
view.setUrl("/watchlist");
return new ModelAndView(view);
Html 部分代碼:
<div class = "col-sm-4">
<input th:field="*{title}" type = "text" class = "form-control" placeholder = "Mandatory">
</div>
<div class="col-sm-4">
<span class="text-danger" th:errors="*{title}"> </span>
</div>
</div>
表格作業正常,表格不接受不完整的資訊。但不顯示錯誤訊息。請指教。
uj5u.com熱心網友回復:
如果您不使用自定義驗證訊息,請嘗試將此放在 application.properties 中。
server.error.include-message=always
server.error.include-binding-errors=always
或者,如果您想添加自定義驗證訊息,請為訊息和驗證器添加配置。
@Configuration
public class MessageConfig {
private static final String MESSAGE_SOURCE_PATH = "classpath:/message";
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE_PATH);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}
@Configuration
public class ValidationConfig {
private final MessageSource validationMessageSource;
@Bean
public LocalValidatorFactoryBean getValidator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(validationMessageSource);
return bean;
}
}
然后,在訊息路徑中添加您想要的訊息。message.properties(在resources檔案夾下)
validation.title.empty= Please enter the title
- 自定義驗證訊息使用
@NotBlank(message="{validation.title.empty}")
private String Title;
這是自定義驗證的基本設定。希望您能解決您的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/366405.html
上一篇:Vaadin多用戶會話管理
