0

I want to inject into the new object a class that contains the user.

    @GetMapping
    public String listTopic(Principal principal, Model model){


        Optional<Users> user = usersService.findByUsername(principal.getName());

        if (user.isPresent()){
            Topics topic = new Topics();
            topic.setUsers(user.get());

            model.addAttribute("newTopic", topic);
            model.addAttribute("topics", topicsService.listTopics());

            return "forum/forum";
        }

        return "/error";
    }

    @PostMapping
    public String addTopic(@Valid @ModelAttribute("newTopic") Topics topic, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            return "forum/forum";
        }
        topicsService.addTopic(topic);
        System.out.println(topic);
        return "redirect:/forum";
    }

When I pass sysout after setting user obect or adding attribute at getmapping section it shows me the exact object, but when I want to see it at the postmapping it throws nullpointerexception.

1 Answers1

1

Your model is a request scope object. After each request it is lost. You need to pass this information to a session object that is alive through different requests in the same session

https://stackoverflow.com/a/18795626/7237884

Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47
  • Thanks a lot :) point 6 helped me. Maybe you also know how to solve this? https://stackoverflow.com/questions/66908650/thymeleaf-and-uniqueconstraint – Daniel Avoyan Apr 02 '21 at 22:56