Spring BindingResult and {{ hasErrors('formName' }} not working

737 views
Skip to first unread message

henriqu...@blackwelllearning.co.uk

unread,
Feb 14, 2017, 10:47:34 AM2/14/17
to Pebble Templating Engine
Hi,

I am new to pebble, I am trying to use spring validation + pebble. I am able to validate on my controller, but I am not able to show error messages on my html file. hasErrors is not working.

my code:

MvcConfig.java

import javax.servlet.ServletContext;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.validation.Validator;

import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import org.springframework.web.servlet.ViewResolver;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


import com.mitchellbosecke.pebble.PebbleEngine;

import com.mitchellbosecke.pebble.loader.Loader;

import com.mitchellbosecke.pebble.loader.ServletLoader;

import com.mitchellbosecke.pebble.spring4.PebbleViewResolver;

import com.mitchellbosecke.pebble.spring4.extension.SpringExtension;


@Configuration

@ComponentScan(basePackages = { "com.example.controller", "com.example.service" })

@EnableWebMvc

public class MvcConfig extends WebMvcConfigurerAdapter {


    @Autowired

    private ServletContext servletContext;


    @Override

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);

    }


    @Bean

    public PebbleEngine pebbleEngine() {

        return new PebbleEngine.Builder().loader(this.templateLoader()).extension(this.springExtension()).build();

    }


    @Bean

    public SpringExtension springExtension() {

        return new SpringExtension();

    }


    @Bean

    public Loader<?> templateLoader() {

        return new ServletLoader(this.servletContext);

    }


    @Bean

    public ViewResolver viewResolver() {

        PebbleViewResolver viewResolver = new PebbleViewResolver();

        viewResolver.setPrefix("/WEB-INF/templates/");

        viewResolver.setSuffix(".html");

        viewResolver.setPebbleEngine(this.pebbleEngine());

        return viewResolver;

    }

    

    @Bean

    public Validator validatorFactory () {

        return new LocalValidatorFactoryBean();

    }


}


WebAppInitializer.java

Enter code here...package com.example.config;


import javax.servlet.Filter;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    /**
     * {@inheritDoc}
     *
     * @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer
     *      #getRootConfigClasses()
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { MvcConfig.class };
    }

    /**
     * {@inheritDoc}
     *
     * @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer
     *      #getServletConfigClasses()
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#getServletFilters()
     */
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        encodingFilter.setForceEncoding(true);

        return new Filter[] { encodingFilter };
    }

    /**
     * {@inheritDoc}
     *
     * @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#getServletMappings()
     */
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}


My controller ProfileController.java

package com.example.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.example.data.User;
import com.example.service.UserService;

@Controller
public class ProfileController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/profile")
    public ModelAndView getUserProfile(@RequestParam("id") long id) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("user", this.userService.getUser(id));
        mav.setViewName("profile");
        return mav;
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView getAddForm() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("form");
        return mav;
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addProfile(@ModelAttribute @Validated User user, BindingResult bindingResult) {
   
        ModelAndView mav = new ModelAndView();
        
        mav.setViewName("profile");
        if (bindingResult.hasErrors()) {
        return "form";
        }
        return "profile";
    }

}

I can see that bindingResult has errors, but I am not able to see on html view.


My pojo User.java

package com.example.data;

import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;

public class User {

    private long id;

    @NotNull
    @Size(min=3, max=8)
    private String firstName;

    @NotNull
    @Size(min=3, max=8)
    private String lastName;

    private Date birthday;

    @NotNull
    @Size(min=3, max=8)
    private String gender;

    @Email
    private String email;
    
    public User() {
}

public User(long id, String firstName, String lastName, Date birthday, String gender, String email) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthday = birthday;
        this.gender = gender;
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

}


and finally my html file

{% extends 'base' %} {% set activeNav = 'add' %} {% block content %}


<div class="profile">

<h2>Add a new Profile</h2>

<form method="POST" action="{{context}}add" name="add" id="add">

<section id="errors">

{# if(hasErrors('add')) #}

{% for err in getAllErrors('add') %}

    <p>{{ err }}</p>

{% endfor %}

{% for err in getAllErrors('add') %}

    <p>{{ err }}</p>

{% endfor %}

{% for err in getGlobalErrors('add') %}

    <p>{{ err }}</p>

{% endfor %}

{# endif #}

</section>

<section>

<p class="field-container">

<input class="" type="text" id="firstName" name="firstName" required

autocapitalize=off autocorrect=off auto-suggest> 

<label

for="firstName">First Name</label> <span

class="validation--message"></span>

</p>

<p class="field-container">

<input class="" type="text" id="lastName" name="lastName" required

autocapitalize=off autocorrect=off auto-suggest> 

<label

for="lastName">Last Name</label> <span

class="validation--message"></span>

</p>

<p class="field-container">

<input class="" type="text" id="email" name="email"> 

<label

for="email">Email</label> <span

class="validation--message"></span>

</p>

<p class="field-container">

<input class="" type="text" id="gender" name="gender" required>

<label for="gender">Pass</label> <span

class="validation--message"></span>

</p>

{# <label class="login__remember"><input type="checkbox">{{rememberMe}}</label>

#}

</section>


<footer class="login__action">

<button type="submit" class="btn btn--secondary">save</button>

</footer>

</form>


</div>


{% endblock content%}


I hope you guys can help me, I've working on it for one day and a half

Jochem

unread,
Jul 18, 2018, 9:45:51 AM7/18/18
to Pebble Templating Engine
Could you try this:

{% for err in getAllErrors('user') %}


    <p>{{ err }}</p>


{% endfor %}


The form name is not correctly set in the map with binding results.

Reply all
Reply to author
Forward
0 new messages