com.pw.ism.controllers.MainController.java Source code

Java tutorial

Introduction

Here is the source code for com.pw.ism.controllers.MainController.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.pw.ism.controllers;

import com.pw.ism.users.User;
import com.pw.ism.users.UserRepository;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author Narsel
 */
@Controller
@RequestMapping("/")
public class MainController {

    private UserRepository userRepo;

    @Autowired
    public MainController(UserRepository repo) {
        this.userRepo = repo;
    }

    @RequestMapping
    public String index() {
        return "index";
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createAccount(@ModelAttribute User user) {
        return "create";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ModelAndView create(@Valid User user, BindingResult result, RedirectAttributes redirect) {
        if (result.hasErrors()) {
            return new ModelAndView("/create", "formErrors", result.getAllErrors());
        }
        user.setState(false);
        System.out.println("user sso_id " + user.getSsoId());
        userRepo.save(user);
        redirect.addFlashAttribute("globalMessage", "Successfully created a new account");
        return new ModelAndView("redirect:/");
    }

}