如何在Spring Boot控制器类中传递参数(app正在使用Spring Security)

问题描述 投票:0回答:2

如上所述,如何传递参数?我已成功将ID参数从我的应用程序中的上一页传递到包含表单的页面的URI。我想发布此表单的内容以及要保存到我的数据库的相同ID参数。

我在我的应用程序中使用Spring Security,我怀疑这可能是问题,因为我的表单的POST方法按预期工作,如果我不尝试传递ID参数(即将我的表单数据对象发送到Service类,然后成功将数据保存到数据库中)。但是,只要我添加了旨在传递ID参数的代码,我就会收到HTTP 405错误(“不支持请求方法'POST')。

我的页面的URI包含form = http://localhost:8080/acceptOffer?id=(idvalue)

形成:

<form autocomplete="off" action="#" th:action="@{/acceptOffer}"
    th:object="${offer}" method="POST" class="form-horizontal"
    role="form">    

    Note 
    <label th:if="${#fields.hasErrors('note')}" th:errors="*{note}"
        class="validation-message"></label>
    <input type="text" th:field="*{note}" placeholder="Type Here"
        class="form-control" /> 

    <button type="submit">Accept Offer</button>
</form>

控制器方法:

@RequestMapping(value={"/acceptOffer?id={id}"}, method = RequestMethod.POST)
public ModelAndView acceptOffer(@Valid Offer offer, @PathVariable String id, BindingResult bindingResult){
    ModelAndView modelAndView = new ModelAndView();
    offerService.setId(Integer.valueOf(id));
    offerService.saveOffer(offer);
    modelAndView.addObject("successMessage", "Your offer of acceptance has been received");
    modelAndView.addObject("user", new User());     
    modelAndView.setViewName("acceptOffer");
    return modelAndView;
}           
java spring model-view-controller spring-boot spring-security
2个回答
1
投票

如果您使用路径变量,则将控制器代码更改为

@RequestMapping(value={"/acceptOffer/{id}"}, method = RequestMethod.POST)
public ModelAndView acceptOffer(@Valid Offer offer, @PathVariable String id, BindingResult bindingResult){
    ModelAndView modelAndView = new ModelAndView();
    offerService.setId(Integer.valueOf(id));
    offerService.saveOffer(offer);
    modelAndView.addObject("successMessage", "Your offer of acceptance has been received");
    modelAndView.addObject("user", new User());     
    modelAndView.setViewName("acceptOffer");
    return modelAndView;
}

并称之为

http://localhost:8080/acceptOffer/id


0
投票

我没有按原定的方式解决这个问题,但我通过以下方式解决了这个问题:

  • 通过URI将参数传递给我的控制器的“GET”方法
  • 在我的控制器的“GET”方法中检索参数,然后将其作为属性添加到HttpSession
  • 在我的控制器的表单“POST”方法中将其作为会话属性取回

我不知道,但它有效...

© www.soinside.com 2019 - 2024. All rights reserved.