Exemple d’annotation de gestion de formulaire Spring MVC

Exemple d'annotation de gestion des formulaires Spring MVC

Dans ce didacticiel, nous vous montrons comment gérer les formulaires à l'aide d'annotations dans l'application Web Spring MVC.

Note
Cet exemple basé sur des annotations est converti à partir des derniers Spring MVCform handling XML-based example. Alors, comparez et repérez les différents.

1. SimpleFormController vs @Controller

Dans l'application Web Spring MVC basée sur XML, vous créez un contrôleur de formulaire en étendant la classeSimpleFormController.

En fonction des annotations, vous pouvez utiliser@Controller à la place.

SimpleFormController

public class CustomerController extends SimpleFormController{
      //...
}

Annotation

@Controller
@RequestMapping("/customer.htm")
public class CustomerController{
      //...
}

2. formBackingObject () vs RequestMethod.GET

Dans SimpleFormController, vous pouvez initialiser l'objet de commande pour la liaison dans la méthodeformBackingObject(). En fonction des annotations, vous pouvez faire de même en annotant le nom de la méthode avec@RequestMapping(method = RequestMethod.GET).

SimpleFormController

        @Override
    protected Object formBackingObject(HttpServletRequest request)
        throws Exception {

        Customer cust = new Customer();
        //Make "Spring MVC" as default checked value
        cust.setFavFramework(new String []{"Spring MVC"});

        return cust;
    }

Annotation

        @RequestMapping(method = RequestMethod.GET)
    public String initForm(ModelMap model){

        Customer cust = new Customer();
        //Make "Spring MVC" as default checked value
        cust.setFavFramework(new String []{"Spring MVC"});

        //command object
        model.addAttribute("customer", cust);

        //return form view
        return "CustomerForm";
    }

3. onSubmit () vs RequestMethod.POST

Dans SimpleFormController, la soumission du formulaire est gérée par la méthodeonSubmit(). En fonction des annotations, vous pouvez faire de même en annotant le nom de la méthode avec@RequestMapping(method = RequestMethod.POST).

SimpleFormController

       @Override
    protected ModelAndView onSubmit(HttpServletRequest request,
        HttpServletResponse response, Object command, BindException errors)
        throws Exception {

        Customer customer = (Customer)command;
        return new ModelAndView("CustomerSuccess");

    }

Annotation

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(
        @ModelAttribute("customer") Customer customer,
        BindingResult result, SessionStatus status) {

        //clear the command object from the session
        status.setComplete();

        //return form success view
        return "CustomerSuccess";

    }

4. referenceData () vs @ModelAttribute

Dans SimpleFormController, vous placez généralement les données de référence dans le modèle via la méthodereferenceData(), afin que la vue formulaire puisse y accéder. En fonction des annotations, vous pouvez faire de même en annotant le nom de la méthode avec@ModelAttribute.

SimpleFormController

    @Override
    protected Map referenceData(HttpServletRequest request) throws Exception {

        Map referenceData = new HashMap();

        //Data referencing for web framework checkboxes
        List webFrameworkList = new ArrayList();
        webFrameworkList.add("Spring MVC");
        webFrameworkList.add("Struts 1");
        webFrameworkList.add("Struts 2");
        webFrameworkList.add("JSF");
        webFrameworkList.add("Apache Wicket");
        referenceData.put("webFrameworkList", webFrameworkList);

        return referenceData;
    }

Forme du printemps

    

Annotation

    @ModelAttribute("webFrameworkList")
    public List populateWebFrameworkList() {

        //Data referencing for web framework checkboxes
        List webFrameworkList = new ArrayList();
        webFrameworkList.add("Spring MVC");
        webFrameworkList.add("Struts 1");
        webFrameworkList.add("Struts 2");
        webFrameworkList.add("JSF");
        webFrameworkList.add("Apache Wicket");

        return webFrameworkList;
    }

Forme du printemps

    

5. initBinder () vs @InitBinder

Dans SimpleFormController, vous définissez la liaison ou enregistrez l'éditeur de propriétés personnalisées via la méthodeinitBinder(). En fonction des annotations, vous pouvez faire de même en annotant le nom de la méthode avec@InitBinder.

SimpleFormController

    protected void initBinder(HttpServletRequest request,
        ServletRequestDataBinder binder) throws Exception {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

Annotation

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

De la validation

Dans SimpleFormController, vous devez enregistrer et mapper la classe de validateur à la classe de contrôleur via le fichier de configuration du bean XML, et la vérification de validation et les flux de travail seront exécutés automatiquement.

En fonction des annotations, vous devez exécuter explicitement le validateur et définir manuellement le flux de validation dans la classe@Controller. Voir les différents:

SimpleFormController

    
                
        

        
        
            
        
    

Annotation

@Controller
@RequestMapping("/customer.htm")
public class CustomerController{

    CustomerValidator customerValidator;

    @Autowired
    public CustomerController(CustomerValidator customerValidator){
        this.customerValidator = customerValidator;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(
        @ModelAttribute("customer") Customer customer,
        BindingResult result, SessionStatus status) {

        customerValidator.validate(customer, result);

        if (result.hasErrors()) {
            //if validator failed
            return "CustomerForm";
        } else {
            status.setComplete();
            //form success
            return "CustomerSuccess";
        }
    }
    //...

Exemple complet

Voir un exemple complet de @Controller.

package com.example.customer.controller;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.support.SessionStatus;

import com.example.customer.model.Customer;
import com.example.customer.validator.CustomerValidator;

@Controller
@RequestMapping("/customer.htm")
public class CustomerController{

    CustomerValidator customerValidator;

    @Autowired
    public CustomerController(CustomerValidator customerValidator){
        this.customerValidator = customerValidator;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(
        @ModelAttribute("customer") Customer customer,
        BindingResult result, SessionStatus status) {

        customerValidator.validate(customer, result);

        if (result.hasErrors()) {
            //if validator failed
            return "CustomerForm";
        } else {
            status.setComplete();
            //form success
            return "CustomerSuccess";
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initForm(ModelMap model){

        Customer cust = new Customer();
        //Make "Spring MVC" as default checked value
        cust.setFavFramework(new String []{"Spring MVC"});

        //Make "Make" as default radio button selected value
        cust.setSex("M");

        //make "Hibernate" as the default java skills selection
        cust.setJavaSkills("Hibernate");

        //initilize a hidden value
        cust.setSecretValue("I'm hidden value");

        //command object
        model.addAttribute("customer", cust);

        //return form view
        return "CustomerForm";
    }


    @ModelAttribute("webFrameworkList")
    public List populateWebFrameworkList() {

        //Data referencing for web framework checkboxes
        List webFrameworkList = new ArrayList();
        webFrameworkList.add("Spring MVC");
        webFrameworkList.add("Struts 1");
        webFrameworkList.add("Struts 2");
        webFrameworkList.add("JSF");
        webFrameworkList.add("Apache Wicket");

        return webFrameworkList;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }

    @ModelAttribute("numberList")
    public List populateNumberList() {

        //Data referencing for number radiobuttons
        List numberList = new ArrayList();
        numberList.add("Number 1");
        numberList.add("Number 2");
        numberList.add("Number 3");
        numberList.add("Number 4");
        numberList.add("Number 5");

        return numberList;
    }

    @ModelAttribute("javaSkillsList")
    public Map populateJavaSkillList() {

        //Data referencing for java skills list box
        Map javaSkill = new LinkedHashMap();
        javaSkill.put("Hibernate", "Hibernate");
        javaSkill.put("Spring", "Spring");
        javaSkill.put("Apache Wicket", "Apache Wicket");
        javaSkill.put("Struts", "Struts");

        return javaSkill;
    }

    @ModelAttribute("countryList")
    public Map populateCountryList() {

        //Data referencing for java skills list box
        Map country = new LinkedHashMap();
        country.put("US", "United Stated");
        country.put("CHINA", "China");
        country.put("SG", "Singapore");
        country.put("MY", "Malaysia");

        return country;
    }
}

Pour que les annotations fonctionnent, vous devez activer la fonction de numérisation automatique des composants dans Spring.



    

    

    
    
        
    

    
              
                 /WEB-INF/pages/
              
              
                 .jsp
              
        

Télécharger le code source