我有一个主页和一个能够向页面添加文本的方法,我想确保普通用户看不到“添加文本”按钮,我该怎么做?
@GetMapping("/")
public String home(Model model) {
model.addAttribute("text", text);
return "index";
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/addText")
public String addText(@RequestParam("text") String newText) {
text += newText;
return "redirect:/";
}
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Главная страница</title>
</head>
<body>
<h1>Главная страница</h1>
<p th:text="${text}"></p>
<form action="/addText" method="post">
<input type="text" name="text" />
<button type="submit">Добавить текст</button>
</form>
</body>
</html>
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((requests) -> requests
.requestMatchers("/login**","/logout**", "/register").permitAll()
.requestMatchers("/one", "/addText").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin((form) -> form
.loginPage("/login")
.permitAll());
return http.build();
}