弹出未显示自定义验证消息

时间:2016-05-15 20:12:44

标签: java spring hibernate spring-mvc

我目前正在使用以下环境:

  • Netbeans 8
  • Jdk 1.7
  • 春季4
  • Hibernate 5.0.1
  • Bean验证器1.1

我有以下文件:

  • Servlet配置(Spring):

            <context:component-scan base-package="mz.co.hypervision.web" />
    
            <mvc:annotation-driven />
    
           <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
           <property name="prefix" value="/WEB-INF/jsp/" />
           <property name="suffix" value=".jsp" />
          </bean>
    
          <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
          <property name="basename" value="messages"/>
          </bean>
    

学生班:

   public class Student {
   @NotNull(message = "{age.notnull}")
   private Integer age;
   private String name;
   private Integer id;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }

   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
}

消息属性文件:

位置:SpringTest \ build \ web \ WEB-INF \ classes

# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.

age.notnull=The age of the student may not be null

已更新

控制器代码:

import javax.validation.Valid;
import mz.co.hypervision.domain.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;

@Controller
public class StudentController {

   @RequestMapping(value = "/student", method = RequestMethod.GET)
   public ModelAndView student() {
      return new ModelAndView("student", "student", new Student());
   }

   @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   public String addStudent(@ModelAttribute("student") @Valid Student student, 
   BindingResult result, ModelMap model) {

      if(result.hasErrors()) {

          return "student";
      } else {
        model.addAttribute("name", student.getName());
        model.addAttribute("age", student.getAge());
        model.addAttribute("id", student.getId());

        return "result";
      }
   }
}

请在下面查看该消息显示为{age.notnull}:

Image with the situation

请帮助弄清楚它为什么不起作用,按照我的观点,我已经按照每一步来实现它

1 个答案:

答案 0 :(得分:0)

通过将messages.properties文件添加到java类路径

来解决该问题
相关问题