de.asgarbayli.rashad.hbd.controllers.ParametersController.java Source code

Java tutorial

Introduction

Here is the source code for de.asgarbayli.rashad.hbd.controllers.ParametersController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package de.asgarbayli.rashad.hbd.controllers;

import de.asgarbayli.rashad.hbd.controllers.definitions.Navigation;
import de.asgarbayli.rashad.hbd.models.Parameters;
import de.asgarbayli.rashad.hbd.controllers.definitions.Messages;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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.servlet.ModelAndView;

/**
 * Controller of the parameters editor.
 * @author rashad
 */
@Controller
public class ParametersController {

    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("title", "Parameters");
        Messages.resetMessage(model);
    }

    @RequestMapping(value = Navigation.PARAMETERS, method = RequestMethod.GET)
    public ModelAndView showParameters(@ModelAttribute(Navigation.PARAMETERS) Parameters parameters,
            BindingResult result, Model model) {
        // Check for binding errors
        if (result.hasErrors()) {
            String message = "Binding result on " + Navigation.PARAMETERS
                    + " has error(s) for the GET request method.";
            Messages.showErrorMessage(model, message);
            return new ModelAndView(Navigation.PARAMETERS);
        }

        parameters.loadParameters();
        return new ModelAndView(Navigation.PARAMETERS, "command", parameters);
    }

    @RequestMapping(value = Navigation.PARAMETERS, method = RequestMethod.POST)
    public ModelAndView changeParameteres(@ModelAttribute(Navigation.PARAMETERS) Parameters parameters,
            BindingResult result, Model model) {
        // Check received data
        if (result.hasErrors()) {
            String message = "Binding result on " + Navigation.PARAMETERS
                    + " has error(s) for the POST request method.";
            Messages.showErrorMessage(model, message);
            return new ModelAndView(Navigation.PARAMETERS);
        }

        // Process the received data
        parameters.saveParameters();

        // Log
        String message = "Parameters were successfully changed.";
        Messages.showSuccessMessage(model, message);

        // Done, reload and show on the same page
        return new ModelAndView(Navigation.PARAMETERS, "command", parameters);
    }
}