MainController.java 1.56 KB
package com.PFE.ServerManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller // This means that this class is a Controller
public class MainController {
    @Autowired // This means to get the bean called userRepository which is auto-generated by Spring, we will use it to handle the Customers
    CustomerRepository customerRepository;

    @RequestMapping(value="/")
    public String home(){
        return "redirect:login";
    }

    @GetMapping(path="/login") // Map ONLY GET Requests
    public String login() {
        return "login";  //return "redirect:/...."; //to send a request to redirect the current page
    }

    @PostMapping(path="/login")
    public String addNewUser(@RequestParam String pseudo, @RequestParam String password) {
        // @RequestParam means it is a parameter from the GET or POST request
        //the model Map is used by thymeleaf as a storage for values display on the html page
        Customer n = new Customer();
        n.setPseudo(pseudo);
        n.setPassword(password);
        Customer temp = customerRepository.findByPseudo(pseudo);

        if(temp != null) {
            return "redirect:login?error";
        }

        customerRepository.save(n);
        return "redirect:login?ok";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<Customer> getAllUsers() {
        // This returns a JSON or XML with the users
        return customerRepository.findAll();
    }
}