blob: abc7e831bf91a3182836180a4bcff5a315fb89da (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
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";
}
}
|