zoukankan      html  css  js  c++  java
  • HTTP Status 400

    今天使用Spring MVC做一个文件上传的功能,在提交表单的时候出现了如下错误:

    之所以出现这个错误,是我没有为如下表单域选择要上传的文件就直接点保存按钮了:

    看看JSP代码:

                <tr>
                    <td>
                        <fmt:message key="com.studentinfomgt.label.avatar"></fmt:message>
                    </td>
                    <td>
                        <input type="file" name="avatar" accept="image/jpeg,image/png,image/gif">
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <input type="submit" value="Save">
                    </td>
                </tr>

    再看看Spring控制器的代码:

        @RequestMapping(value="/addStudentByForm", method=POST)
        public String addStudentByForm(@RequestPart(value="avatar") byte[] avatar, @Valid Student student, Errors errors) throws Exception {
            if (errors.hasErrors()) {
                return "addStudentForm";
            }

    试了很多方式还是有这个问题,于是我想到了Spring API文档:

    原来@RequestPart, @RequestParam注解都有一个可选的boolean参数required, 默认就是true, 瞬间醒悟,把Controller的代码改成这样就解决了错误:

        @RequestMapping(value="/addStudentByForm", method=POST)
        public String addStudentByForm(@RequestPart(value="avatar", required=false) byte[] avatar, @Valid Student student, Errors errors) throws Exception {
            if (errors.hasErrors()) {
                return "addStudentForm";
            }
  • 相关阅读:
    7、猜年龄
    6、continue语句
    5、break语句
    4、while循环练习
    poj 2378
    poj 2342
    poj 2287
    poj 2228
    poj 1191
    srm 578 dv2 1000pt
  • 原文地址:https://www.cnblogs.com/stonefeng/p/5708835.html
Copyright © 2011-2022 走看看