com.senfino.yodo.controller.AccontController.java Source code

Java tutorial

Introduction

Here is the source code for com.senfino.yodo.controller.AccontController.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 com.senfino.yodo.controller;

import com.senfino.yodo.domain.Account;
import com.senfino.yodo.request.AccountForm;
import com.senfino.yodo.service.AccountService;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
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.ResponseBody;

/**
 *
 * @author Piotr 
 */
@Controller
@RequestMapping(value = "/users")
public class AccontController {

    private static final Logger log = LoggerFactory.getLogger(AccontController.class);

    @Autowired
    private AccountService accountService;

    @ResponseBody
    @RequestMapping(value = "new", method = RequestMethod.GET)
    public String getRegistrationForm(Model model) {
        log.info("View registrationForm ");
        model.addAttribute("account", new AccountForm());
        return "users/registartionForm";

    }

    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.POST)
    public String postRegistrationForm(@ModelAttribute("account") @Valid AccountForm form,
            BindingResult bindingResult) {
        convertPasswordError(bindingResult);
        accountService.registerAccount(toAccount(form), form.getPassword(), bindingResult);
        log.info("Create registration : ", form);
        return "redirect:registration_ok";
    }

    private Account toAccount(AccountForm form) {
        Account account = new Account();
        account.setEmail(form.getEmail());
        return account;

    }

    private void convertPasswordError(BindingResult bindingResult) {
        for (ObjectError objectError : bindingResult.getGlobalErrors()) {
            String msg = objectError.getDefaultMessage();
            if ("account.password.mismatch.message".equals(msg)) {
                if (bindingResult.hasFieldErrors("password")) {
                    bindingResult.rejectValue("password", "error.mismatch");
                }
            }
        }
    }

}