Exemple de gestion de formulaire MVC Spring

Exemple de gestion des formulaires Spring MVC

spring-mvc-form-handling-demo

Dans ce didacticiel, nous allons vous montrer un projet de gestion de formulaire Spring MVC pour effectuer les tâches suivantes:

  1. Liaison de valeur de formulaire - JSP et modèle.

  2. Validation de formulaire et affichage d'un message d'erreur.

  3. Formez un modèle POST / REDIRECT / GET et ajoutez des messages à l'attribut flash.

  4. Opérations CRUD, ajoutez, obtenez, mettez à jour et supprimez avec un formulaire HTML.

Technologies utilisées:

  1. Spring 4.1.6.RELEASE

  2. Maven 3

  3. Bootstrap 3

  4. Pilote HSQLDB 2.3.2

  5. Logback 1.1.3

  6. JDK 1.7

  7. JSTL 1.2

  8. Eclipse IDE

What you’ll build :
Un simple projet de gestion des utilisateurs, vous pouvez lister, créer, mettre à jour et supprimer un utilisateur, via des formulaires HTML. Vous verrez également comment effectuer la validation du formulaire et afficher le message d'erreur de manière conditionnelle. Ce projet porte le style avec Bootstrap 3 et les données sont stockées dans la base de données intégrée HSQL.

La structure URI:

URI Méthode action

/utilisateurs

GET

Liste, afficher tous les utilisateurs

/utilisateurs

POST

Enregistrer ou mettre à jour l'utilisateur

/users/{id}

GET

Afficher l'utilisateur {id}

/users/add

GET

Afficher le formulaire d'ajout d'utilisateur

/users/{id}/update

GET

Afficher le formulaire utilisateur de mise à jour pour {id}

/users/{id}/delete

POST

Supprimer l'utilisateur {id}

Note
Autrefois, avant le printemps 3.0, nous utilisionsSimpleFormController pour gérer les formulaires. Comme Spring 3.0, cette classe est déconseillée au profit de Spring annotated @Controller.

Spring MVC Form Binding

Avant de démarrer le didacticiel, vous devez comprendre le fonctionnement de la liaison de formulaire Spring MVC.

1.1 In controller, you add an object into a model attribute.

    @RequestMapping(value = "/users/add", method = RequestMethod.GET)
    public String showAddUserForm(Model model) {

        User user = new User();
        model.addAttribute("userForm", user);
        //...
    }

1.2 In HTML form, you use spring:form tag and bind the controller object via modelAttribute.

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

    
         
        
    

1.3 When the HTML form is “POST”, you get the value via @ModelAttribute.

@RequestMapping(value = "/users", method = RequestMethod.POST)
public String saveOrUpdateUser(@ModelAttribute("userForm") User user,
        BindingResult result, Model model) {
    //...
}

Terminé. Commençons le tutoriel.

1. Répertoire des projets

Il s'agit de la structure finale du répertoire du projet. Un projet Maven standard.

spring-mvc-form-handling-directory

2. Dépendances du projet

Pour développer un projet Spring MVC, vous avez besoin despring-webmvc.

pom.xml


    4.0.0
    com.example.form
    spring-mvc-form
    war
    1.0-SNAPSHOT
    SpringMVC + Form Handling Example

    
        1.7
        4.1.6.RELEASE
        2.3.2
        1.1.3
        1.7.12
        1.2
        3.1.0
    

    

        
        
            org.springframework
            spring-core
            ${spring.version}
            
               
                commons-logging
                commons-logging
                
            
        

        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        

        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        

        
        
            org.hsqldb
            hsqldb
            ${hsqldb.version}
        

        
        
            org.slf4j
            jcl-over-slf4j
            ${jcl.slf4j.version}
        

        
            ch.qos.logback
            logback-classic
            ${logback.version}
        

        
        
            jstl
            jstl
            ${jstl.version}
        

        
            javax.servlet
            javax.servlet-api
            ${servletapi.version}
            provided
        

    

    
        

            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.3
                
                    ${jdk.version}
                    ${jdk.version}
                
            

            
            
                org.eclipse.jetty
                jetty-maven-plugin
                9.2.11.v20150529
                
                  10
                  
                    /spring-mvc-form
                  
                
            

            
            
                org.apache.maven.plugins
                maven-eclipse-plugin
                2.9
                
                    true
                    true
                    2.0
                    spring-mvc-form
                
            

        
    

3. Manette

Classe Spring@Controller pour vous montrer comment lier la valeur du formulaire via@ModelAttribute, ajouter un validateur de formulaire, ajouter un message dans l'attribut flash, remplir des valeurs pour la liste déroulante et les cases à cocher, etc. Lisez les commentaires pour s'expliquer d'eux-mêmes.

UserController.java

package com.example.form.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.example.form.model.User;
import com.example.form.service.UserService;
import com.example.form.validator.UserFormValidator;

@Controller
public class UserController {

    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    UserFormValidator userFormValidator;

    //Set a form validator
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(userFormValidator);
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        logger.debug("index()");
        return "redirect:/users";
    }

    // list page
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public String showAllUsers(Model model) {

        logger.debug("showAllUsers()");
        model.addAttribute("users", userService.findAll());
        return "users/list";

    }

    // save or update user
    // 1. @ModelAttribute bind form value
    // 2. @Validated form validator
    // 3. RedirectAttributes for flash value
    @RequestMapping(value = "/users", method = RequestMethod.POST)
    public String saveOrUpdateUser(@ModelAttribute("userForm") @Validated User user,
            BindingResult result, Model model,
            final RedirectAttributes redirectAttributes) {

        logger.debug("saveOrUpdateUser() : {}", user);

        if (result.hasErrors()) {
            populateDefaultModel(model);
            return "users/userform";
        } else {

            // Add message to flash scope
            redirectAttributes.addFlashAttribute("css", "success");
            if(user.isNew()){
              redirectAttributes.addFlashAttribute("msg", "User added successfully!");
            }else{
              redirectAttributes.addFlashAttribute("msg", "User updated successfully!");
            }

            userService.saveOrUpdate(user);

            // POST/REDIRECT/GET
            return "redirect:/users/" + user.getId();

            // POST/FORWARD/GET
            // return "user/list";

        }

    }

    // show add user form
    @RequestMapping(value = "/users/add", method = RequestMethod.GET)
    public String showAddUserForm(Model model) {

        logger.debug("showAddUserForm()");

        User user = new User();

        // set default value
        user.setName("example123");
        user.setEmail("[email protected]");
        user.setAddress("abc 88");
        user.setNewsletter(true);
        user.setSex("M");
        user.setFramework(new ArrayList(Arrays.asList("Spring MVC", "GWT")));
        user.setSkill(new ArrayList(Arrays.asList("Spring", "Grails", "Groovy")));
        user.setCountry("SG");
        user.setNumber(2);
        model.addAttribute("userForm", user);

        populateDefaultModel(model);

        return "users/userform";

    }

    // show update form
    @RequestMapping(value = "/users/{id}/update", method = RequestMethod.GET)
    public String showUpdateUserForm(@PathVariable("id") int id, Model model) {

        logger.debug("showUpdateUserForm() : {}", id);

        User user = userService.findById(id);
        model.addAttribute("userForm", user);

        populateDefaultModel(model);

        return "users/userform";

    }

    // delete user
    @RequestMapping(value = "/users/{id}/delete", method = RequestMethod.POST)
    public String deleteUser(@PathVariable("id") int id,
        final RedirectAttributes redirectAttributes) {

        logger.debug("deleteUser() : {}", id);

        userService.delete(id);

        redirectAttributes.addFlashAttribute("css", "success");
        redirectAttributes.addFlashAttribute("msg", "User is deleted!");

        return "redirect:/users";

    }

    // show user
    @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    public String showUser(@PathVariable("id") int id, Model model) {

        logger.debug("showUser() id: {}", id);

        User user = userService.findById(id);
        if (user == null) {
            model.addAttribute("css", "danger");
            model.addAttribute("msg", "User not found");
        }
        model.addAttribute("user", user);

        return "users/show";

    }

    private void populateDefaultModel(Model model) {

        List frameworksList = new ArrayList();
        frameworksList.add("Spring MVC");
        frameworksList.add("Struts 2");
        frameworksList.add("JSF 2");
        frameworksList.add("GWT");
        frameworksList.add("Play");
        frameworksList.add("Apache Wicket");
        model.addAttribute("frameworkList", frameworksList);

        Map skill = new LinkedHashMap();
        skill.put("Hibernate", "Hibernate");
        skill.put("Spring", "Spring");
        skill.put("Struts", "Struts");
        skill.put("Groovy", "Groovy");
        skill.put("Grails", "Grails");
        model.addAttribute("javaSkillList", skill);

        List numbers = new ArrayList();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        model.addAttribute("numberList", numbers);

        Map country = new LinkedHashMap();
        country.put("US", "United Stated");
        country.put("CN", "China");
        country.put("SG", "Singapore");
        country.put("MY", "Malaysia");
        model.addAttribute("countryList", country);

    }

}

4. Validateur de formulaire

4.1 Spring validator example.

UserFormValidator.java

package com.example.form.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.example.form.model.User;
import com.example.form.service.UserService;

@Component
public class UserFormValidator implements Validator {

    @Autowired
    @Qualifier("emailValidator")
    EmailValidator emailValidator;

    @Autowired
    UserService userService;

    @Override
    public boolean supports(Class clazz) {
        return User.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {

        User user = (User) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotEmpty.userForm.name");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotEmpty.userForm.email");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "NotEmpty.userForm.address");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty.userForm.password");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword","NotEmpty.userForm.confirmPassword");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "sex", "NotEmpty.userForm.sex");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "country", "NotEmpty.userForm.country");

        if(!emailValidator.valid(user.getEmail())){
            errors.rejectValue("email", "Pattern.userForm.email");
        }

        if(user.getNumber()==null || user.getNumber()<=0){
            errors.rejectValue("number", "NotEmpty.userForm.number");
        }

        if(user.getCountry().equalsIgnoreCase("none")){
            errors.rejectValue("country", "NotEmpty.userForm.country");
        }

        if (!user.getPassword().equals(user.getConfirmPassword())) {
            errors.rejectValue("confirmPassword", "Diff.userform.confirmPassword");
        }

        if (user.getFramework() == null || user.getFramework().size() < 2) {
            errors.rejectValue("framework", "Valid.userForm.framework");
        }

        if (user.getSkill() == null || user.getSkill().size() < 3) {
            errors.rejectValue("skill", "Valid.userForm.skill");
        }

    }

}

validation.properties

NotEmpty.userForm.name = Name is required!
NotEmpty.userForm.email = Email is required!
NotEmpty.userForm.address = Address is required!
NotEmpty.userForm.password = Password is required!
NotEmpty.userForm.confirmPassword = Confirm password is required!
NotEmpty.userForm.sex = Sex is required!
NotEmpty.userForm.number = Number is required!
NotEmpty.userForm.country = Country is required!
Valid.userForm.framework = Please select at least two frameworks!
Valid.userForm.skill = Please select at least three skills!
Diff.userform.confirmPassword = Passwords do not match, please retype!
Pattern.userForm.email = Invalid Email format!

Pour exécuter Spring Validator, ajoutez le validateur via@InitBinder et annotez le modèle avec@Validated

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(userFormValidator);
}

@RequestMapping(value = "/users", method = RequestMethod.POST)
public String saveOrUpdateUser(... @Validated User user,
        ...) {

    //...

}

Ou exécutez-le manuellement.

@RequestMapping(value = "/users", method = RequestMethod.POST)
public String saveOrUpdateUser(... User user,
        ...) {
    userFormValidator.validate(user, result);
    //...
}

5. Formulaires HTML

Tous les formulaires HTML sont de style css avec le framework Bootstrap et utilisent des balises de formulaire Spring pour effectuer l'affichage et la liaison de formulaire.
5.1 Listes d'utilisateurs.

list.jsp

<%@ page session="false"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>








    

All Users

#ID Name Email framework Action
${user.id} ${user.name} ${user.email} ${framework} ,

show.jsp

<%@ page session="false"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>






User Detail


${user.id}
${user.name}
${user.email}
${user.address}
${user.newsletter}
${user.framework}
${user.sex}
${user.number}
${user.country}
${user.skill}

userform.jsp

<%@ page session="false"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>






Add User

Update User





6. Base de données Stuff

6.1 Create a table and insert some data for testing.

create-db.sql

CREATE TABLE users (
  id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 100, INCREMENT BY 1) PRIMARY KEY,
  name VARCHAR(30),
  email  VARCHAR(50),
  address VARCHAR(255),
  password VARCHAR(20),
  newsletter BOOLEAN,
  framework VARCHAR(500),
  sex VARCHAR(1),
  NUMBER INTEGER,
  COUNTRY VARCHAR(10),
  SKILL VARCHAR(500)
);

insert-data.sql

INSERT INTO users (name, email, framework) VALUES ('example', '[email protected]', 'Spring MVC, GWT');
INSERT INTO users (name, email) VALUES ('alex', '[email protected]', 'Spring MVC, GWT');
INSERT INTO users (name, email) VALUES ('joel', '[email protected]', 'Spring MVC, GWT');

6.2 Start a HSQLDB embedded database, create a datasource and jdbcTemplate.

SpringDBConfig.java

package com.example.form.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

@Configuration
public class SpringDBConfig {

    @Autowired
    DataSource dataSource;

    @Bean
    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
        return new NamedParameterJdbcTemplate(dataSource);
    }

    @Bean
    public DataSource getDataSource() {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        EmbeddedDatabase db = builder.setName("testdb")
                        .setType(EmbeddedDatabaseType.HSQL)
            .addScript("db/sql/create-db.sql")
                        .addScript("db/sql/insert-data.sql").build();
        return db;
    }

}

6.3 User object.

user.java

package com.example.form.model;

import java.util.List;

public class User {
    // form:hidden - hidden value
    Integer id;

    // form:input - textbox
    String name;

    // form:input - textbox
    String email;

    // form:textarea - textarea
    String address;

    // form:input - password
    String password;

    // form:input - password
    String confirmPassword;

    // form:checkbox - single checkbox
    boolean newsletter;

    // form:checkboxes - multiple checkboxes
    List framework;

    // form:radiobutton - radio button
    String sex;

    // form:radiobuttons - radio button
    Integer number;

    // form:select - form:option - dropdown - single select
    String country;

    // form:select - multiple=true - dropdown - multiple select
    List skill;

    //Check if this is for New of Update
    public boolean isNew() {
        return (this.id == null);
    }

    //...

}

7. Services et DAO

UserService.java

package com.example.form.service;

import java.util.List;
import com.example.form.model.User;

public interface UserService {

    User findById(Integer id);

    List findAll();

    void saveOrUpdate(User user);

    void delete(int id);

}

UserServiceImpl.java

package com.example.form.service;

import java.util.List;

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

import com.example.form.dao.UserDao;
import com.example.form.model.User;

@Service("userService")
public class UserServiceImpl implements UserService {

    UserDao userDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List findAll() {
        return userDao.findAll();
    }

    @Override
    public void saveOrUpdate(User user) {

        if (findById(user.getId())==null) {
            userDao.save(user);
        } else {
            userDao.update(user);
        }

    }

    @Override
    public void delete(int id) {
        userDao.delete(id);
    }

}

UserDao.java

package com.example.form.dao;

import java.util.List;

import com.example.form.model.User;

public interface UserDao {

    User findById(Integer id);

    List findAll();

    void save(User user);

    void update(User user);

    void delete(Integer id);

}

UserDaoImpl.java

package com.example.form.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.example.form.model.User;

@Repository
public class UserDaoImpl implements UserDao {

    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    public void setNamedParameterJdbcTemplate(
        NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    @Override
    public User findById(Integer id) {

        Map params = new HashMap();
        params.put("id", id);

        String sql = "SELECT * FROM users WHERE id=:id";

        User result = null;
        try {
            result = namedParameterJdbcTemplate
                          .queryForObject(sql, params, new UserMapper());
        } catch (EmptyResultDataAccessException e) {
            // do nothing, return null
        }

        return result;

    }

    @Override
    public List findAll() {

        String sql = "SELECT * FROM users";
        List result = namedParameterJdbcTemplate.query(sql, new UserMapper());
        return result;

    }

    @Override
    public void save(User user) {

        KeyHolder keyHolder = new GeneratedKeyHolder();

        String sql = "INSERT INTO USERS(NAME, EMAIL, ADDRESS, PASSWORD, NEWSLETTER, FRAMEWORK, SEX, NUMBER, COUNTRY, SKILL) "
                + "VALUES ( :name, :email, :address, :password, :newsletter, :framework, :sex, :number, :country, :skill)";

        namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(user), keyHolder);
        user.setId(keyHolder.getKey().intValue());

    }

    @Override
    public void update(User user) {

        String sql = "UPDATE USERS SET NAME=:name, EMAIL=:email, ADDRESS=:address, "
            + "PASSWORD=:password, NEWSLETTER=:newsletter, FRAMEWORK=:framework, "
            + "SEX=:sex, NUMBER=:number, COUNTRY=:country, SKILL=:skill WHERE id=:id";

        namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(user));

    }

    @Override
    public void delete(Integer id) {

        String sql = "DELETE FROM USERS WHERE id= :id";
        namedParameterJdbcTemplate.update(sql, new MapSqlParameterSource("id", id));

    }

    private SqlParameterSource getSqlParameterByModel(User user) {

        MapSqlParameterSource paramSource = new MapSqlParameterSource();
        paramSource.addValue("id", user.getId());
        paramSource.addValue("name", user.getName());
        paramSource.addValue("email", user.getEmail());
        paramSource.addValue("address", user.getAddress());
        paramSource.addValue("password", user.getPassword());
        paramSource.addValue("newsletter", user.isNewsletter());

        // join String
        paramSource.addValue("framework", convertListToDelimitedString(user.getFramework()));
        paramSource.addValue("sex", user.getSex());
        paramSource.addValue("number", user.getNumber());
        paramSource.addValue("country", user.getCountry());
        paramSource.addValue("skill", convertListToDelimitedString(user.getSkill()));

        return paramSource;
    }

    private static final class UserMapper implements RowMapper {

        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setName(rs.getString("name"));
            user.setEmail(rs.getString("email"));
            user.setFramework(convertDelimitedStringToList(rs.getString("framework")));
            user.setAddress(rs.getString("address"));
            user.setCountry(rs.getString("country"));
            user.setNewsletter(rs.getBoolean("newsletter"));
            user.setNumber(rs.getInt("number"));
            user.setPassword(rs.getString("password"));
            user.setSex(rs.getString("sex"));
            user.setSkill(convertDelimitedStringToList(rs.getString("skill")));
            return user;
        }
    }

    private static List convertDelimitedStringToList(String delimitedString) {

        List result = new ArrayList();

        if (!StringUtils.isEmpty(delimitedString)) {
            result = Arrays.asList(StringUtils.delimitedListToStringArray(delimitedString, ","));
        }
        return result;

    }

    private String convertListToDelimitedString(List list) {

        String result = "";
        if (list != null) {
            result = StringUtils.arrayToCommaDelimitedString(list.toArray());
        }
        return result;

    }

}

8. Configuration du ressort

Mélanger Spring XML et JavaConfig.

SpringWebConfig.java

package com.example.form.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
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 org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({ "com.example.form.web", "com.example.form.service", "com.example.form.dao",
        "com.example.form.exception", "com.example.form.validator" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
        rb.setBasenames(new String[] { "messages/messages", "messages/validation" });
        return rb;
    }

}

spring-web-servlet.xml



    
    

web.xml



    Spring3 MVC Application

    
        spring-web
        
            org.springframework.web.servlet.DispatcherServlet
        
        1
    

    
        spring-web
        /
    

    
        500
        /WEB-INF/views/jsp/error.jsp
    

    
        404
        /WEB-INF/views/jsp/error.jsp
    

    
        /WEB-INF/views/jsp/error.jsp
    

9. Demo

Téléchargez le projet et saisissezmvn jetty:run

$ mvn jetty:run
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringMVC + Form Handling Example 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
//...
[INFO] Started Jetty Server
[INFO] Starting scanner at interval of 10 seconds.

spring-mvc-form-handling-demo1

spring-mvc-form-handling-demo-add

9.3 Form validation.

spring-mvc-form-handling-demo-add-error

spring-mvc-form-handling-demo-add-done

spring-mvc-form-handling-demo-delete

Télécharger le code source

Téléchargez-le -spring4-form-handle-example.zip (80 ko)

Github - à déterminer