【问题标题】:How to retrieve form elements at controller in java如何在java中的控制器处检索表单元素
【发布时间】:2014-03-19 16:51:15
【问题描述】:

我正在尝试使用 java spring 向控制器提交表单,在以下代码中,我正在通过以下方式成功检索文件元素,但没有获得如何检索其他元素(短名和全名)值。 请帮帮我。

<body>
    <div style="text-align: center; margin-top: 60px;">
        <form action="upload" enctype="multipart/form-data">
            <input type="hidden" id="shortName" name="michael">
            <input type="hidden" id="fullName" name="michael jackson">
            Select file:
            <input type="file" name="dataFile" id="fileAttachment"/><br/><br/>
                <div style="text-align: center; margin-top: 100px;">
                    <input style="cursor: pointer;" onmouseover="" onclick="uploadAttachment()" class="dialogbox" type="submit" value="Upload Report" />
                </div>
        </form>
    </div>
</body>

控制器端代码:

@RequestMapping(value = "upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response,
            @RequestPart("dataFile") MultipartFile file
             ){
System.out.println(file.getSize());
}

【问题讨论】:

  • 你试过@RequestParam String shortName@RequestParam String fullName吗?
  • 是的,我确实尝试过你的语法,但它有帮助。感谢您的回复。

标签: java spring multipartform-data form-data


【解决方案1】:

首先更改输入元素并为 shortName 和 fullName 创建 name 属性,如下所示:

<input type="hidden" id="shortNameId" name="shortName" value="michael">
<input type="hidden" id="fullNameId" name="fullName" value="michael jackson">

但是您可以删除默认值属性,并在页面呈现时自己输入值,因此 value="michael" 和 value="michael jackson" 是可选的!

然后你可以像这样检索那些输入元素:

@RequestMapping(value = "upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("shortName")String shortName, @RequestParam("fullName")String fullName
        @RequestPart("dataFile") MultipartFile file
         ){ .... }

祝你好运!

【讨论】:

    【解决方案2】:

    在您的控制器中,尝试这样的操作,

    @RequestMapping(value = "/your/url/{formParamenter}", method = RequestMethod.GET)
        public String yourfunction(@PathVariable("formParameter") Type formParameter{}
    

    Type 是数据的类型,(String/int/float..etc)。

    在您的情况下,只需将 RequestPart 更改为 @PathVariable

    【讨论】:

      猜你喜欢
      • 2020-08-13
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 2013-09-13
      • 1970-01-01
      • 2016-11-12
      相关资源
      最近更新 更多