简体   繁体   中英

Spring boot injection failure

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM