package com.example.spring.contact.controller; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import jakarta.validation.Valid; @Controller public class ContactController { /* * Some values that can be used with @PreAuthorize(): * * hasRole('ADMIN'): Checks if the user contains the authority ROLE_ADMIN. * * hasAnyRole('USER', 'ADMIN'): Passes if the user has at least one matching * authority. * * isAuthenticated(): Verifies that the client is logged into the system */ @GetMapping("/contact") @PreAuthorize("hasAnyRole('USER', 'ADMIN')") public String showForm(Model model) { model.addAttribute("contactForm", new ContactForm()); return "contact/form"; } @PostMapping("/contact") @PreAuthorize("hasAnyRole('USER', 'ADMIN')") public String processSubmission(@Valid @ModelAttribute ContactForm contactForm, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return "contact/form"; } // Do whatever needed with the submitted data here. // For example, invoke a method in a service/componet bean to send an email to // contact person. return "contact/result"; } }