2014-10-06 2 views
0
This is my project structure. 

MySpringVAlidation 
    -src/main/java 
     -com.myproject.controllers 
      -SearchCustomerController.java 
     -com.myproject.model 
      -SearchCustomer.java 
     -applicationContext.xml 
     -messages_en_US.properties 
    -src/main/webapp/WEB-INF 
    -mvc-dispatcher-servlet.xml 
    -web.xml 
    -src/main/webapp/WEB-INF/views 
     -AddModifyCustomer.jsp 


messages_en_US.properties (properties file has custom messages) 
========================== 
NotEmpty.SearchCustomerForm.custId = Customer Id must be 7 characters. 

mvc-dispatcher-servlet.xml (dispatcher has Spring configurations) 
=========================== 
<mvc:annotation-driven /> 

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
    <property name="basename"> 
     <value>messages_en_US.properties</value> 
    </property> 
</bean> 


SearchCustomer.java 
======================-========================================================== 

    @NotEmpty 
    @XmlAttribute(name="CustomerID") 
    public String getCustId() { 
     return custId; 
    } 

SearchCustomerController.java 
================================= 
@RequestMapping(value="/searchCustomer" , method = RequestMethod.POST) 
public String processAdd(@ModelAttribute("searchCustomerForm") @Valid SearchCustomer sCust, 
      BindingResult result, Map<String, Object> model, HttpSession session) throws IOException, JMSException { 
     sCust.setOrganizationCode("SUPPLY"); 
     //System.out.println("Session ID:"+session.getId()); 
     System.out.println("Errors :- "+result.hasErrors()+result.getAllErrors()); 
     if(result.hasErrors()){ 
      Customer customerForm = new Customer(); 
      model.put("customerForm", customerForm); 
      return "AddModifyCustomer"; 
     }else{ 
       postSearchRequest.postMessage(sCust, "SearchCustomer.xml",session.getId());  
       //For the second tab 
         Customer customerForm = new Customer(); 
         model.put("customerForm", customerForm); 

       return "AddModifyCustomer"; 
     } 
    } 

AddModifyCustomer.jsp 
===================== 

<form:form action="searchCustomer" method="post" commandName="searchCustomerForm">        
<label style="padding-right: .25em;width: 7em;text-align: right;float: left;"> 
Customer ID : </label><form:input id="custId" path="custId" /> 

<input style="float:center;" type="submit" name="Search" id="Search" value="Search" />&nbsp; <button type="button" name="add" id="add" value="add">add</button>  
<br/><form:errors path="custId"></form:errors>      
<form:hidden path="organizationCode" />   
</form:form> 

Ожидаемого результата, когда я нажимаю на поиск клиента без предоставления какого-либо ввода:
Customer Id должен быть 7 символов.
Фактический результат: - may not be empty Обратите внимание на @NotEmpty, даже я пытался делать @NotEmpty(message="{NotEmpty.SearchCustomerForm.custId}"), но по-прежнему получать тот же результатпроверки Spring не собирание сообщения от message.properties

The messages in properties file is not get picked up. Its always showing default messages. Where am i going wrong?  
+0

Вы используете Maven и структуру Maven по умолчанию? – Desorder

+0

да. Я использую maven. – user3035087

+0

Первоначально я получал предупреждение, не в состоянии найти пакет messages_en_US.properties. Поэтому я сохранил его в моей папке src/main/java вместо src/main/webapp/resources – user3035087

ответ

0

Ваш класс SearchCustomer, но в свой файл свойств вы используете SearchCustomerForm.

Попробуйте NotEmpty.SearchCustomer.custId = Customer Id must be 7 characters.

Синтаксис сообщения должен быть:

[Constraint].[Class name].[Property]=[Message] 
+0

Я по-прежнему получаю ту же ошибку, даже если я изменяю синтаксис на NotEmpty.SearchCustomer.custId = Идентификатор клиента должен быть 7 символов. – user3035087

+0

Ваш компонент ReloadableResourceBundleMessageSource не определен. Вы не должны указывать полное имя, только «сообщения», «_en_US.properties» добавляется к весне, когда он выполняет поиск. Try: <боб ID = "messageSource" \t класс = "org.springframework.context.support.ReloadableResourceBundleMessageSource"> \t <имя свойства = значение "базовое" = "путь к классам: сообщения" /> \t – alfcope

+0

все еще получает тот же результат. нет изменений: ошибка поля в объекте 'searchCustomerForm' в поле 'custId': отклоненное значение []; коды [NotEmpty.searchCustomerForm.custId, NotEmpty.custId, NotEmpty.java.lang.String, NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: коды [searchCustomerForm.custId, custId]; аргументы []; сообщение по умолчанию [custId]]; сообщение по умолчанию [может не быть пустым]] – user3035087

Смежные вопросы