Failed to load resource: the server responded with a status of 400 (Bad Request) 错误请求解决

前言

  这个问题是我在用ajax做文件上传时遇到的,朋友也遇到这种情况,在这里总结一下

分析

  Failed to load resource: the server responded with a status of 400 (Bad Request)   是错误请求的报错

   出现这种错误一般情况是:

  1.前端的参数类型和后端的参数类型不匹配,比如前端string 类型,后端是date类型

<input type="date" id="bornDay" name="bornDay"/>  //这里是date控件,但是实际数据类型是string,而且格式是yyyy-MM-dd(可以alert一下值和值得类型检验)
private Date bornDay;  //这里是后端用于接收信息的实体类的属性,这里是Date类型

  解决:在给Date 类型的数据加注解

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date bornDay; 

  如果还是没有解决,需要查看一下SpringMVC的配置文件中是否加入扫描注解的配置,还要指定扫描的包路径

<!-- 方式一过时的扫描注解配置 不建议使用,这两个配置可能因为版本问题没有起到效果,导致没有扫描到注解 -->
<!--<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> -->
<!-- 方式二扫描注解的配置(建议使用) -->
<mvc:annotation-driven/>

2.前端的控件的name属性和后端接收的参数名称不匹配,比如下面的image和image123,还有接收信息实体类的字段名也需要与前端控件的name属性一致

<input type="file" class="fileinp" name="image"/>
public String register(User user, @RequestParam("image123") CommonsMultipartFile file, HttpSession session)

  解决:将两个名称改一致

扫描二维码关注公众号,回复: 8437504 查看本文章

猜你喜欢

转载自www.cnblogs.com/zero666/p/12154708.html