使用@PathVariable SpringBoot将信息/当前ID /传递给子Controller

时间:2018-08-10 06:22:27

标签: java spring

,但想问一个问题。首先在我的应用程序中,我想以一种形式注册用户,然后重定向到另一种形式,用户必须填写UserDetails形式。这是两个具有OneToOne关系的实体UserUserDetail。在第二个控制器UserDetailController中,我想传递UserId的{​​{1}}属性,我进行了研究,但找不到答案。我尝试使用User,但无法正常工作。     这是我的部分代码:

@PathVariable

UserController

abstract class BaseController {

    protected ModelAndView view(String view, ModelAndView modelAndView) {
        modelAndView.setViewName(view);

        return modelAndView;
    }

   protected ModelAndView view(String view) {
        return this.view(view, new ModelAndView());
    }

    protected ModelAndView redirect(String route) {
        return this.view("redirect:" + route);
    }
}

UserDetailController

        @GetMapping("/register")
    public ModelAndView register() {
                return this.view("register");
    }

    @PostMapping("/register")
    public ModelAndView registerConfirm(@ModelAttribute UserRegisterBindingModel userRegisterBindingModel,
                                        HttpSession session, HttpServletRequest request
                                        ) {
        if (!userRegisterBindingModel.getPassword()
                .equals(userRegisterBindingModel.getConfirmPassword())) {
            return this.view("register");
        }



        this.userService.createUser(this.modelMapper.map(userRegisterBindingModel, UserServiceModel.class));
        String id = request.getParameter("userId");
        return this.redirect("user-profile/" + id);
    }

此代码无效,因为“ id”返回NULL。如何从注册传递到用户个人资料/ {id}-> id?

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

在registerConfirmMethod

model.addAttribute("userId", userId);
return new ModelAndView("redirect:/user-profile", model);

在最后一种方法中,您必须添加

ModelAndView modelAndView = new ModelAndView("user-profile");
modelAndView.addObject("id", id);
return modelAndView;

答案 1 :(得分:0)

您可以使用RedirectView这样的东西

当您添加带有“ id”的属性

变量'{id}'与模型属性匹配,因此它将被自动替换为重定向URL中的pathparam

@PostMapping("/register")
public RedirectView registerConfirm(@ModelAttribute UserRegisterBindingModel userRegisterBindingModel,
                                HttpSession session, HttpServletRequest request, Model model
                                ) {


    this.userService.createUser(this.modelMapper.
    map(userRegisterBindingModel, UserServiceModel.class));

    String id = request.getParameter("userId");

    model.addAttribute("id", id);

    RedirectView rv = new RedirectView();
    rv.setContextRelative(true);
    rv.setUrl("/user-profile/{id}");
    return rv;
}

以及您的用户个人资料控制器中

@GetMapping("/user-profie/{id}")
public ModelAndView add(@PathVariable("id") String id) {

   //  sout id
    return this.view("user-profile");
}