温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringMVC表单提交参数出现400错误的解决方法

发布时间:2020-10-26 16:55:00 来源:亿速云 阅读:430 作者:Leah 栏目:开发技术

SpringMVC表单提交参数出现400错误的解决方法?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

1.参数指定问题

如果Controller中定义了参数,而表单内却没有定义该字段

@SuppressWarnings("deprecation") 
@RequestMapping("/hello.do") 
public String hello(HttpServletRequest request,HttpServletResponse response, 
    @RequestParam(value="userName") String user 
){ 
  request.setAttribute("user", user); 
  return "hello"; 
} 

这里,表单内必须提供一个userName的属性!

不想指定的话,你也可以定义这个属性的默认值defaultValue="":

@SuppressWarnings("deprecation") 
@RequestMapping("/hello.do") 
public String hello(HttpServletRequest request,HttpServletResponse response, 
    @RequestParam(value="userName",defaultValue="佚名") String user 
){ 
  request.setAttribute("user", user); 
  return "hello"; 
} 

也可以指定该参数是非必须的required=false:

@SuppressWarnings("deprecation") 
@RequestMapping("/hello.do") 
public String hello(HttpServletRequest request,HttpServletResponse response, 
    @RequestParam(value="userName",required=false) String user 
){ 
  request.setAttribute("user", user); 
  return "hello"; 
} 

2.上传问题

上传文件大小超出了Spring上传的限制

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  <!-- 设置上传文件的最大尺寸1024字节=1K,这里是10K -->  
  <property name="maxUploadSize">  
    <value>10240</value>  
  </property> 
  <property name="defaultEncoding">  
      <value>UTF-8</value>  
  </property>  
</bean> 

我们工程里面是这个问题引起的,但是我实际示例中发现超过大小是直接报错的。

3.时间转换问题

也有网友说是因为时间转换引起的,而我实际操作中发现报错是:

The server encountered an internal error that prevented it from fulfilling this request

这里也顺便提一下,假如你的Controller要一个时间对象,代码如下:

@SuppressWarnings("deprecation") 
@RequestMapping("/hello.do") 
public String hello(HttpServletRequest request,HttpServletResponse response, 
    @RequestParam(value="userName",defaultValue="佚名") String user, 
    Date dateTest 
){ 
  request.setAttribute("user", user); 
  System.out.println(dateTest.toLocaleString()); 
  return "hello"; 
} 

而网页上实际给的是

<input type="text" name="dateTest" value="2015-06-07">

这里需要在Controller增加一个转换器

@InitBinder 
public void initBinder(WebDataBinder binder) { 
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
  dateFormat.setLenient(false); 
  binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); 
}

看完上述内容,你们掌握SpringMVC表单提交参数出现400错误的解决方法的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI