Spring MVC default value not working - java

#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"?

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.

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.

make sure you don't pass empty string value
Valid Methods:
1. Fin_AddBankAccount?name=
O/P: name="N/A"
Fin_AddBankAccount?
O/P: name="N/A"
Invalid Methods:
Fin_AddBankAccount?name=""
this will set empty string to variable i.e. name="";

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.

Related

Accessing optional parameters in Spring Boot GraphQL

I have this QueryMapping method where I have some parameters marked as required in my GrapthQL schema, but not all. Using #Argument allows me to grab all required parameters, but when I send a Query without an optional parameter it crashes. Using the RequestParam annotation with a default value doesn't work since its type is an integer and the annotation requires a string. (I guess it's supposed to be called within a REST-API)
#QueryMapping
public List<Record> getRecord(Argument String email, #Argument int dateFrom, #RequestParam(required = false, defaultValue = 0) int dateTo) {
return repository.findSpecific(email, dateFrom);
}
Edit: Method overloading does not work.
What can I do?
I found a solution by using Kotlin: Adding a Question mark behind the Parameter Type allows me to set the value to null.

REST RequestParam optional parameter

I have an Interface method which can be called as below -
{{url}}/packageName/{{var}}/list
It can take in a param of type Collection<String> , so i can fetch specific results.
{{url}}/packageName/{{var}}/list?paramIds=param1&paramIds=param2
Now if i leave paramIds empty as below, Spring MVC creates LinkedHashMap , size 0 and i get no results back.
{{url}}/packageName/{{var}}/list?paramIds=
This is my annotation #RequestParam(value = "paramIds", required = "false") Collection<String> paramIds
I tried to get rid of required and use defaultValue but unable to set defaultValue to null.
For now i changed the annotation to #RequestParam(value = "paramIds", defaultValue = "none") and added code in the dao to handle "none" as null - wondering if there is a better way to solve this problem.
Thanks in advance.
It sounds to me like Spring is giving you the best option, an empty list is usually better than a null.
My first choice would be to modify your DAO code to handle an empty list instead of expecting null, but assuming that's not possible, why not have a check in your controller to pass null to your DAO if the collection is empty, like:
if (paramsIds.isEmpty()) {
dao.doSomething(null);
}

Can you have an optional QueryParam in jersey?

Using java jersey, I have the following #QueryParam's in my method handler:
#Path("/hello")
handleTestRequest(#QueryParam String name, #QueryParam Integer age)
I know if I do:
http://myaddress/hello?name=something
It will go into that method....
I want to make it so that I can call:
http://myaddress/hello?name=something
And it will also go into that same method. Is there any way I can flag an "optional" PathParam? Does it work with #FormParam too? Or am I required to create a separate method with a different method signature?
In JAX-RS parameters are not mandatory, so if you do not supply an age value, it will be NULL, and your method will still be called.
You can also use #DefaultValue to provide a default age value when it's not present.
The #PathParam parameter and the other parameter-based annotations, #MatrixParam, #HeaderParam, #CookieParam, and #FormParam obey the same rules as #QueryParam.
Reference
You should be able to add the #DefaultValue annotation the age parameter, so that if age isn't supplied, the default value will be used.
#Path("/hello")
handleTestRequest(
#QueryParam("name") String name,
#DefaultValue("-1") #QueryParam("age") Integer age)
According to the Javadocs for #DefaultValue, it should work on all *Param annotations.
Defines the default value of request meta-data that is bound using one of the following annotations: PathParam, QueryParam, MatrixParam, CookieParam, FormParam, or HeaderParam. The default value is used if the corresponding meta-data is not present in the request.
You can always wrap return type in optional, for example: #QueryParam("from") Optional<String> from

How can I put a bean object to sessionMap, and then retrieve its properties on jsp page using Struts 2 property tag

In login Action I am checking user authentication, and if it is validated, I am putting the user bean into sessionMap:
public String execute()
{
if(userValid)
sessionMap.put("userBean", userBean); //userBean retrieved from DB
}
Now on the landing jsp, when trying to retrieve the session items:
<s:property value="#session.userBean.name" />
Obviously this would return an Object type, as I am storing it that way, so how can I type caste this to UserBean class.
I was expecting to get a solution for this on Google, but found it nowhere since this seems to be a basic implementation. So please let me know if there is any other way to implement this functionality using Struts2.
This works fine for me...
<sp:property value="#session.usertype"/>
<sp:property value="#session.bean.loginID"/>
This both worked fine for me...
sessionMap.put("bean", loginBean);
sessionMap.put("usertype", loginBean.getUserType());
I declared something like this....
Just make sure that in property tag you you same name you used while setting the bean in sessionMap ....
This should probably work....
Obviously you can't cast it to UserBean class if the object is not the instance of that class. In the value attribute you have put a string "#session.userBean.name". Struts parse this string for OGNL expression and if it's a valid expression that returns a value, it will replace it with that value. The returned type is Object, but this type is determined by ValueStack implementation.
Then property tag writes this object to the out. It uses toString() to convert the object to string. And if your object implements this method, then this value would be written.
Looks like your expression returns an Object, which has instance type String, so it's already implemented this method.

Why is Struts2 converting my string to a string array?

I have a Struts 2 (JDK 1.7, Struts 2.2.1) application that contains a list of filtering criteria, stored as strings in a map.
Map< String, String > m_filters = new HashMap< String, String >();
public Map< String, String > getFilters() {
return m_filters;
}
I pass a URL formatted like this:
http://myserver.com/myapp/GenerateReport.action?reportID=Whatever&filters.fromDate=0&filters.toDate=2000000000&filters.FcsType=piv_cardholder_3kp&detailed=true
Even though the Map has both key & value types specified as String, attempting to get a value from this
Map< String, String > filters = getFilters();
String value = filters.get( "fromDate" );
causes this exception to be thrown:
java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
I reproduced this in a unit test, and confirmed in a debugger that Struts 2 seems to be creating a String[1] instead of a String for each of the parameters. i.e. it is a length-1 string array with the only string being the expected value ("0" in this case).
My question is: Is this a bug in Struts2, or am I doing something incorrectly?
If it is a bug, is there a known workaround?
There are no issues if you follow Java bean conventions.
Here are some guidelines to resolve the issue:
This issue does not happen if you name the private member "filter" and provide only a getter for filter.
This issue does not happen if you provide a public setter (even if you use a different name for the private member such as m_filter) in addition to the getter
this issue only happens if you do not provide a setter and the property does not have the same name as the getter.
Long story short follow conventions. Above behaviour tested with Struts 2.3.4
What I'm guessing is happening: The getter allows for setting too (If there was only a setter you could only set one item in the map, well with the current parameter interceptor this is the case). The bean is inspected for the property to see how it should do type conversion probably first it looks for a setter failing that it looks at the action for a propterty of that name to determine the type failing that it will need to use the default. The default parameter type is a mapping of String to String[] and this is what you are seeing.
You're using the wrong notation. filters.fromDate would be the equivalent of getFilters().setFromDate(), which is not actually what you want. Dot notation is for JavaBeans.
Try using brackets, such as filters['fromDate'].
Refer to: http://struts.apache.org/2.2.1/docs/type-conversion.html#TypeConversion-RelationshiptoParameterNames.
Try this:
Object[] obj = (Object[]) filters.get( "fromDate" );
String value = (String)obj[0]);
It's not a bug you can consider it's a feature. Access RequestParameters
ParameterAware Interceptor
Let us suppose /http://localhost:8080/myApp/login.action?name=struts2&name=rocks
if you try to access the name parameter string[0] = struts2, string1=rocks

Categories

Resources