Freemarker模板中不显示Spring MVC验证错误

时间:2016-09-07 20:48:49

标签: validation spring-mvc spring-security freemarker

我试图在用户注册中显示验证错误'如果控制器返回绑定错误,则使用freemarker模板构建页面。

我的控制器代码如下:

@Controller
@RequestMapping("/")
public class UserController  {

@Autowired
private UserService userService;

@Autowired
private SecurityService securityService;

@Autowired
private UserValidator userValidator;

@RequestMapping(value = "/registration", method = RequestMethod.GET)
   public String registration(Model model) {
   model.addAttribute("userForm", new User()); 
   return "registration";
  }

@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("useraccount") User userForm,     BindingResult bindingResult, Model model) {

    userValidator.validate(userForm, bindingResult);

    if (bindingResult.hasErrors()) {

        return "registration";
        }

    userService.save(userForm);

    securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());

    return "redirect:/explore";
}

虽然这是我正在尝试构建的registration.ftl freemarker模板:

 <div>
<fieldset>
    <h1>Create your Account</h1>
    <form id="regForm" class="idealform" action="registration" method="post" name='useraccount'>
            Username: <input type="text" name="username" /> <errors path="username" cssClass="error"/><br/>
            Password: <input type="text" name="password" /><errors path="password" cssClass="error"/><br/>
               <label class="main-label" style="width: 91px;">&nbsp;</label>
        <input type="submit" value="submit">
    </form>
</fieldset>

我也尝试了这里推荐的解决方案:

Displaying Spring MVC validation errors in Freemarker templates

并且registration.ftl变为:

  <#assign form=JspTaglibs["http://www.springframework.org/tags/form"] />

  <#macro formErrors>
  <#assign formErrors><@form.errors path="*" /></#assign>
  <#if formErrors?has_content>
    <div id="errors">
     <@spring.message "admin.error.globalMessage" />
    </div>
  </#if>
 </#macro>

<div>
<fieldset>
    <h1>Create your Account</h1>
    <@form.form id="regForm" class="idealform" action="registration"   method="post" name='useraccount'>
            Username: <input type="text" name="username" path="username" />    <br/>

            Password: <input type="text" name="password" path="password" /><br/>

    <@formErrors />
        <label class="main-label" style="width: 91px;">&nbsp;</label>
        <input type="submit" value="submit">
    </@form.form>
</fieldset>

</div>

但仍未显示验证消息。

你能否就这个问题与我分享你的想法? 非常感谢你。

1 个答案:

答案 0 :(得分:1)

我将控制器代码重写为以下内容:

@Controller
@RequestMapping("/")
public class UserController {

@Autowired
private UserService userService;

@Autowired
private SecurityService securityService;

@Autowired
private UserValidator userValidator;

@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(@ModelAttribute(name = "userForm") User user) {
    return "registration";
}

@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute(name = "userForm") User user, BindingResult result) {
    userValidator.validate(user, result);

    if (result.hasErrors()) {
        return "registration";
    }

    userService.save(user);

    securityService.autologin(user.getUsername(), user.getPasswordConfirm());

    return "redirect:/explore";
}
}

1)如果使用不带参数的构造函数,则无需使用model.addAttribute("modelName", model),而是可以使用指定name属性的@ModelAttribute注释(默认情况下,名称来自类名) 。您只需确保此模型处于一致状态。此外,您需要传递与视图中使用的名称完全相同的名称(自由标记模板)。

现在“registration.ftl”

...
<#import "/spring.ftl" as spring/>
...
<fieldset>
  <h1>Create your Account</h1>
  <form id="regForm" class="idealform" action="<@spring.url '/registration'/>" method="post">
    <@spring.bind 'userForm.username'/>
    Username: <input type="text" name="${spring.status.expression}" value="${spring.status.value?html}"/>
    <#list spring.status.errorMessages as error>
      <span class="error">${error}</span>
      <br>
    </#list>
    <@spring.bind 'userForm.password'/>
    Password: <input type="password" name="${spring.status.expression}" value="${spring.status.value?html}"/>
    <#list spring.status.errorMessages as error>
      <span class="error">${error}</span>
      <br>
    </#list>
    <label class="main-label" style="width: 91px;">&nbsp;</label>
    <input type="submit" value="submit">
  </form>
</fieldset>
...

1)您需要<#import "/spring.ftl" as spring/>才能添加非常有用的spring用户定义指令。
2)使用<@spring.bind 'userForm.username'>指令将以下输入绑定到模型。这里“userForm”是您的模型,“username”是您要绑定的字段。该指令还声明了一个新变量“spring.status”,它包含一个“表达式”变量 - 一个路径,一个“值” - 填充表单以防它返回错误,而“errorMessages”来自BindingResult。
3)如果您使用消息来源支持不同的语言,则应将<span class="error">${error}</span>更改为<@spring.message '${error}'/>,否则您只会获得消息代码。

希望它有所帮助。