W jaki sposób powinno odbywać się sterowanie encją - mam na myśli przekazywanie informacji, na którym użytkowniku(encja) powinna zostać wykonana jakaś operacja?
Próbowałem w taki sposób - przekazując konkretną encję w modelu, jednak po wciśnięciu "Increase rank"(wykonaniu metody POST "/increase", gdzie powininna być przekazana encja usera, a przekazany jest null) wyrzuca NullPointerException, przy wywołaniu metody user.increase().
java.lang.NullPointerException: null
at User.increase()
at MainController.increase()
@Entity
@Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames ={"email"}))
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
private int rank;
public void increase() {
rank++;
}
}
@Controller
public class MainController {
@Autowired
UserRepository userRepository;
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/")
public String home(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userRepository.findByEmail(auth.getName());
model.addAttribute("loggedUser", user);
return "home";
}
@PostMapping("/increase")
public String increase(@ModelAttribute("loggedUser") User user){
user.increase();
return "redirect:/";
}
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
Name: <span th:text = "${loggedUser.email}"></span>
<form th:action="@{/increase}" method="post" th:object="${loggedUser}">
<button type="submit">Increase rank</button>
</form>
</body>
</html>