Spring mvc学习指南 使用flash attribute(闪存传值) @ModelAttribute注解 类型转换器 校验器(用于校验数据的准确性)

  • 在配置文件中添加<mvc:annotion-driven/>
  • 在controller方法参数里面添加RedirectAttributes redirectAttributes
  • 通过 redirectAttributes.addFlashAttribute(key,value)即可

@ModelAttribute注解

  • 用于方法参数中
    public String save(@ModelAttribute User user)//用于绑定request对象中的参数
    
    //每次执行前都会调用该方法并将返回值返回存储到页面中并装入到`model`中
    @ModelAttribute
    public User save2(User user)

类型转换器

Converter 可用于每个步骤

将Spring中的String或者其他类型转换成时间类型

  1. 实现org.springframework.core.convert.converter.Converter接口
  2. 编写public Date convert(String dateStr)方法
public class DateConverter implements Converter<String, Date> {

    private Logger logger = LoggerFactory.getLogger(DateConverter.class);

    @Override
    public Date convert(String dateStr) {

        return DateUtils.parseDate(dateStr);

    }
}
  1. 将其注册到配置文件中
<bean id="conversionService"
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.ferelife.emms.web.converter.DateConverter" />
            </list>
        </property>
</bean>

  1. 将该service注入到里面
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

Formatter 用于Controller层(源类型只能为String)

校验器(用于校验数据的准确性)

  • SpringValidation
  • JSR303/JSR349