com.epam.ipodromproject.controller.MainPageController.java Source code

Java tutorial

Introduction

Here is the source code for com.epam.ipodromproject.controller.MainPageController.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.epam.ipodromproject.controller;

import com.epam.ipodromproject.domain.User;
import com.epam.ipodromproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
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
public class MainPageController {

    @Autowired
    UserService userService;

    @RequestMapping(value = { "home", "" }, method = RequestMethod.GET)
    public String goToHome(Model model) {
        User user = userService.getUserByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        model.addAttribute("user", user);
        model.addAttribute("totalMoneyWon", userService.getTotalMoneyWon(user));
        model.addAttribute("totalMoneyLost", userService.getTotalMoneyLost(user));
        return "mainPage";
    }

    @RequestMapping(value = "changeNameOfUser", method = RequestMethod.POST)
    @ResponseBody
    public String changeNameOfUser(@RequestParam(value = "name") String name) {
        User user = userService.getUserByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        if (user.getEnabled() == false) {
            return "this_user_is_blocked";
        }
        if (userService.changeNameOfUser(user.getUsername(), name)) {
            return "name_changed_successfully";
        } else {
            return "Name_4_to_15_characters";
        }
    }

    @RequestMapping(value = "changeSurnameOfUser", method = RequestMethod.POST)
    @ResponseBody
    public String changeSurnameOfUser(@RequestParam(value = "surname") String surname) {
        User user = userService.getUserByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        if (user.getEnabled() == false) {
            return "this_user_is_blocked";
        }
        if (userService.changeSurnameOfUser(user.getUsername(), surname)) {
            return "surname_changed_successfully";
        } else {
            return "Surname_4_to_15_characters";
        }
    }

    @ExceptionHandler(Throwable.class)
    public String catchAnyException(Throwable throwable) {
        return "errorpage";
    }

}