簡體   English   中英

Spring 重定向屬性未傳輸

[英]Spring redirectAttributes not transferred

我想將 id 參數從一種形式(控制器)傳遞到另一種形式。 在這里,我在我的 model 中添加了一個 id 並將其傳遞。

@Controller
public class PersonController 

 @RequestMapping(value = {"/addPerson"}, method = RequestMethod.POST)
    public String savePerson(Model model, //
                             @ModelAttribute("personForm") PersonForm personForm, RedirectAttributes attributes) {//, @ModelAttribute("person") Person newPerson) {

        String firstName = personForm.getFirstName();
        String lastName = personForm.getLastName();
        double money = personForm.getMoney();

        if (firstName != null && firstName.length() > 0
                && lastName != null && lastName.length() > 0) {
            Person newPerson = new Person(firstName, lastName, money);
            personService.save(newPerson);
            attributes.addFlashAttribute("id", newPerson.getId());//

            return "redirect:/addKonto";
        }

        model.addAttribute("errorMessage", errorMessage);
        return "addPerson";
    }

我將數據傳遞給另一個表單,這里的 id 被正確傳遞。 大小 = 3

@RequestMapping(value = {"/addKonto"}, method = RequestMethod.GET)
    public String showAddKontoPage(Model model, @ModelAttribute("id") int id) {

        KontoForm kontoForm = new KontoForm();
        model.addAttribute("kontoForm", kontoForm);
        model.addAttribute("id", id);

        return "addKonto";
    }

當我嘗試進一步傳遞我的 model 時,id 參數會丟失。 大小 = 2

@RequestMapping(value = {"/addKonto"}, method = RequestMethod.POST)
    public String saveKonto(Model model,
                            @ModelAttribute("kontoForm") KontoForm kontoForm) {

        String kontoName = kontoForm.getKontoName();
        double moneyInKonto = kontoForm.getMoneyInKonto();
         model.getAttribute("id"); //    hier is null

        if (kontoName != null && kontoName.length() > 0) {
            Konto newKonto = new Konto(kontoName, moneyInKonto);

            kontoService.save(newKonto);

            return "redirect:/personList";
        }

如何獲取id參數?

在您的savePerson方法中,您添加了attributes.addFlashAttribute()而不是model.addAttribute()就像您在showAddKontoPage方法中一樣。

意思是,對於要通過重定向從 controller 傳遞到 controller 的屬性,您需要通過model.addAttribute()方法添加該屬性。

您可以向 Controller 方法添加新屬性以接受用戶 ID 屬性:

@RequestMapping(value = {"/addKonto"}, method = RequestMethod.GET)
public String showAddKontoPage(Model model,
                               @RequestParam(required = false) String id)
@RequestMapping(value = {"/addKonto"}, method = RequestMethod.POST)
public String saveKonto(Model model,
                        @ModelAttribute("kontoForm") KontoForm kontoForm,
                        @RequestParam(required = false) String id)

Flash 消息用於通過標簽向最終用戶顯示消息。

附帶說明:

Spring 具有驗證您的 Forms的基礎設施。 當然,當您准備好使用該基礎架構時,將來使用該基礎架構會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM