Java tutorial
/* * 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.epam.ipodromproject.controller; import com.epam.ipodromproject.domain.User; import com.epam.ipodromproject.exceptions.UserAlreadyExistsException; import com.epam.ipodromproject.forms.RegistrationForm; import com.epam.ipodromproject.service.UserService; import javax.validation.Valid; 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.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.bind.annotation.ResponseBody; @Controller @RequestMapping(value = "registration") public class RegistrationController { @Autowired UserService userService; @RequestMapping(value = "checkIfUsernameExists", method = RequestMethod.GET) @ResponseBody public boolean usernameExists(@RequestParam("username") String username) { User user = userService.getUserByUsername(username); return (user != null); } @RequestMapping(method = RequestMethod.GET) public String goToRegistrationPage(Model model) { model.addAttribute("registrationForm", new RegistrationForm()); return "registration"; } @RequestMapping(method = RequestMethod.POST) public String registerUser(@Valid @ModelAttribute("registrationForm") RegistrationForm registrationForm, BindingResult result, Model model) { if (!registrationForm.passwordsMatch()) { model.addAttribute("passwordsDontMatch", true); return "registration"; } if (result.hasErrors()) { return "registration"; } try { userService.registerUser(registrationForm); } catch (UserAlreadyExistsException e) { model.addAttribute("usernameExists", true); return "registration"; } model.addAttribute("message", "registration_was_successfull"); return "login"; } }