Spring MVC default value not working

℡╲_俬逩灬. 提交于 2019-12-08 06:15:39

问题


@RequestMapping(value = "/Fin_AddBankAccount", method = RequestMethod.POST)
public @ResponseBody JsonResponse addCoaCategory(
    @RequestParam(value="code", required=true) long code,
    @RequestParam(value="startFrom", required=true) long startFrom,
    @RequestParam(value="name", required=true, defaultValue="N/A") String name)
    {

    }

defaultValue="N/A" not working , As I did not provide any text in name field , it store null in database instead of "N/A"?


回答1:


What is the point of setting a default value if you really want that parameter. if you mark it as required true(not needed as it is default) then no need of a default value. If that parameter is not mandatory then mark it as false and give a default value.




回答2:


Documentation of Spring RequestParam.required

Default is true, leading to an exception thrown in case of the parameter missing in the request. Switch this to false if you prefer a null in case of the parameter missing.

From your question I figured out that you are sending parameter name with empty value using POST request. According to the Spring documentation you should not send name parameter in the request in order to use default value. Simply remove name field from HTML form if it is empty.

It seems that default values makes more sense for GET requests.




回答3:


In my project

@RequestParam(value="name", required=true, defaultValue="N/A") String name

This code correctly sets name variable as defaultvalue N/A when requestparam "name" was not provided. My guess is you are not inserting this name variable into the table properly so database is storing null instead of "N/A". Please show us or double check the data access object code. Good luck


Thanks @Tiarê Balbi, in fact you do not need "required=true" because defaultValue="N/A" implicitly sets this variable as required=false anyways.




回答4:


make sure you don't pass empty string value Valid Methods: 1. Fin_AddBankAccount?name= O/P: name="N/A"

  1. Fin_AddBankAccount? O/P: name="N/A"

Invalid Methods: Fin_AddBankAccount?name="" this will set empty string to variable i.e. name="";



来源:https://stackoverflow.com/questions/16504401/spring-mvc-default-value-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!