如何在弹簧mvc后的方法中获取参数?

2022-09-01 02:28:45

我正在使用弹簧mvc。当方法=post时,我无法从url获取参数。但是当我将方法更改为GET时,所以我可以得到所有参数。

这是我的形式:

<form method="POST" action="http://localhost:8080/cms/customer/create_customer" id="frmRegister" name ="frmRegister" enctype="multipart/form-data">
    <input class ="iptRegister" type="text" id="txtEmail" name="txtEmail" value="" />
    <input class ="iptRegister" type="password" id="txtPassword" name="txtPassword" value="" />
    <input class ="iptRegister" type="text" id="txtPhone" name="txtPhone" value="" />

    <input type="button" id="btnRegister" name="btnRegister" value="Register" onclick="" style="cursor:pointer"/>
</form>

这是我的控制器:

@RequestMapping(value= "/create_customer", method = RequestMethod.POST)
@ResponseBody
public String createCustomer(HttpServletRequest request, 
        @RequestParam(value="txtEmail", required=false) String email, 
        @RequestParam(value="txtPassword", required=false) String password, 
        @RequestParam(value="txtPhone", required=false) String phone){

    ResultDTO<String> rs = new ResultDTO<String>();
    rs.setStatus(IConfig.SHOW_RESULT_SUCCESS_ON_MAIN_SCREEN);
    try{
        Customer c = new Customer();
        c.setEmail(email);
        c.setPassword(password);
        c.setPhone(phone);
        customerService.insert(c);
        rs.setData("Insert success");
    }catch(Exception ex){
        log.error(ex);
        rs.setStatus(IConfig.SHOW_RESULT_ERROR_ON_MAIN_SCREEN);
        rs.setData("Insert failure");
    }
    return rs.toString();
}

我该如何解决这个问题?


答案 1
  1. 如果删除,弹簧注释将正常工作。enctype="multipart/form-data"

    @RequestParam(value="txtEmail", required=false)
    
  2. 您甚至可以从对象中获取参数。request

    request.getParameter(paramName);
    
  3. 如果属性数量很大,请使用表单。这将很方便。教程,以帮助您入门。

  4. 如果要接收 ,请配置多部分解析程序。enctype="multipart/form-data"

    <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="250000"/>
    </bean>
    

请参阅春季文档


答案 2

如果更改内容类型,它也有效

    <form method="POST"
    action="http://localhost:8080/cms/customer/create_customer"
    id="frmRegister" name="frmRegister"
    enctype="application/x-www-form-urlencoded">

在控制器中还添加标头值,如下所示:

    @RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")

推荐