How to put a default value in an object with Annotation? (#RequestParam) - spring

Is it possible to give an object a default value using #RequestParam?
When I name the form tag the same as the field in the object
I know that it automatically assigns a value to an object.
But if the object's field is an int, null value is entered, an error occurs.
★ Plant_list2VO class
★ form
★ controller:
public String reg4(HttpServletRequest request, HttpServletResponse response,
Plant_list2VO plant_list2VO,
#RequestParam(name="inv_count", defaultValue="0") int inv_count,
#RequestParam(name="inv_count_disable", defaultValue="2") int inv_count_disable,
Model model) {
}
★ console:
WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'plant_list2VO' on field 'inv_count': rejected value [];
codes [typeMismatch.plant_list2VO.inv_count,typeMismatch.inv_count,typeMismatch.int,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [plant_list2VO.inv_count,inv_count]; arguments [];
default message [inv_count]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'inv_count'; nested exception is java.lang.NumberFormatException: For input string: ""]
Field error in object 'plant_list2VO' on field 'inv_count_disable': rejected value [];
codes [typeMismatch.plant_list2VO.inv_count_disable,typeMismatch.inv_count_disable,typeMismatch.int,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [plant_list2VO.inv_count_disable,inv_count_disable]; arguments []; default message [inv_count_disable]];
default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'inv_count_disable'; nested exception is java.lang.NumberFormatException: For input string: ""]]

I see you define inv_count and inv_count_disable are int attributes. So, you should change values of defaultValue to a number to resolve java.lang.NumberFormatException

Judging by the console log, the inv_count and inv_count_disable values passed to your controller are not null, but empty Strings.
I can assume you use an old version of Spring, because before 3.2.x version empty String values were accepted by AbstractNamedValueMethodArgumentResolver as actual values (see method resolveArgument here), and defaultValue wasn't used in that case, resulting in conversion exception, because empty String cannot be converted to an integer.
In 3.2.x and later versions of Spring empty String is considered as there were no value passed, and defaultValue is used in case it's present (see method resolveArgument here).
So, if you want to stick to an older version of Spring, you may want to change your form to send some default number if the field is empty, or create a DTO, where these fields are of type String with some logic in setters.
Also this may help: Is it possible to have empty RequestParam values use the defaultValue?

Related

Can simple protobuf types be migrated to "optional"

In protobuf version 3 required and optional keywords first have been removed, since required often caused problems protobuf issue 2497.
Recently the 'optional' keyword has been reintroduced protobuf v3.15.0.
Is it possible to simply add the optional keyword to an existing message?
I.e. change
message Test {
int32 int32_value = 1;
string text_value = 2;
}
to
message Test {
optional int32 int32_value = 1;
optional string text_value = 2;
}
Or will this break the binary format?
non-optional primitive types in protobuf don't accept null-values and normally also map to non-nullable types like int in Java or C#.
But this doesn't mean, that the field is always included in the binary representation.
In fact, if a field contains the default value for the corresponding type the field is omitted in the binary representation.
Thus the following message
message Test {
int32 int32_value = 1;
string text_value = 2;
}
Test test = new Test();
byte[] buffer = test.ToByteArray();
gets serialized to buffer containing an empty byte[].
So missing fields default to default values without the use of optional.
If the optional keyword is changing the behaviour for missing fields in the binary format and for default values specified:
Missing fields indicate the field has not been specified and indicate null. Setting default values will not result in an empty byte[] but in the default values being serialized.
Thus changing a primitive field to optional won't break the format, but will change the semantics:
All fields of old messages that have been specified with the default value will be interpreted as null. Other values are not affected.
The same for optional being removed from a field:
The api won't break, but change semantics. Unspecified fields will then default to default values for the corresponding type.

Why protobuf both required/optional field accepts "default" value, I expect only "optional" should

The google protobuf allow me to write proto code like this:
syntax="proto2";
message hello
{
optional int32 id=1;
required string str=2[default="abc"];
optional int32 op=3 [default=15];
}
It compiles, no problem. I don't just quite understand that, for "optional" field, when there's no value specified, the decode stream return me the default value, it's OK. But what about the "required" field, it cann't be empty, so how its "default" is also valid? In what scenario?
The "default" value is the value returned by the field's getter when the field has not been set yet. When you create a new message object, initially, none of the fields are set -- even required fields. So, the default value is what the getter will return if you call it immediately.
Granted, this is not particularly useful for required fields, but there didn't seem to be any reason to prohibit it.

Spring MVC - Throws exception when the int value of ModelAttribute is null

I'm building an web application using Spring 3.0 MVC.
I have a method which has prototype below.
#RequestMapping(value = "/blahblah/blah.do", method=RequestMethod.GET)
public void searchData(#RequestParam(value="uniqOid", required=false) String uniqOid, #ModelAttribute("MasterVo") MasterVo searchVo,
ModelMap model, HttpServletResponse response, HttpServletRequest request)
The problem is that, the view (jsp) contains inputs that matches to searchVo(ModelAttribute).
When the int or long value of searchVo didn't come from the jsp, the server throws 404 page not found exception.
If the type of value is "String", it has no problem.
In my opinion, it is the problem of type casting.
How could I solve this problem, and which part of the server code that I have to check?
Thanks in advance.
I will go ahead and assume a few things about your problem.
It is not a type-cast problem. Spring has default converters that can easily convert from a String to some primitive type.
Now what you are facing is I think a null assigment to primitive type problem. Suppose the name of the property that's causing the problem is named primitiveProperty. Now, the request-paramters could include a parameter named primitiveProperty with an empty-String value, or some value that cannot be converted to a number. If the type of the primitiveProperty is String, it can assign the value of that parameter to it without any problem.
If the type of the primitiveProperty is int, long or some other primitive type that cannot have a null value, a problem occurs. When Spring converts the empty-string or a non-numeric string valued request-param named primitiveProperty, it cannot do so since that string can't be converted to a valid int or long value. So it is converted to null. Now, when Spring tries to assign that null value to a property that cannot have a null value (any primitve type), you get an Exception. If you are getting an empty-string as your request-param, you can replace the troublesome property in your domain object with its equivalent wrapper class (int with Integer, long with Long and so on). If you are getting a non-numeric value from your view, well, make sure that you don't get a non-numeric value.
You need to check the setter of the fields that are giving the typecast problem, in your case MasterVo .
The Spring will call the setter of the property to bind the value, where i presume you will see the error coming.
Just add a debug point to this setter and you will see the problem.

string was not recognized as a valid datetime. in c#

i am using this code for passing datetime.
Convert.ToDateTime(textBox1.Text)
but the compiler show an error that string was not recognized as a valid datetime. so how to avoid this error and is a datetime field in my database.
Convert.ToDateTime(textBox1.Text)
This code will throw an exception if the string value in textBox1.Text doesn't represent a valid DateTime (or at least can't be parsed into one with default functionality in C#). You can add some defensive programming to handle errors like this.
The DateTime type (as well as most, if not all, common value types in .NET) has a method on it called TryParse() specifically for the purpose to attempting to parse a value into that type without throwing an exception. The method returns true if the parse was successful, false otherwise. And it accepts an out parameter to hold the resulting parsed value (or the original value if parsing is unsuccessful).
So instead of this:
var dateTimeValue = Convert.ToDateTime(textBox1.Text);
You could use something like this:
var dateTimeValue = DateTime.MinValue;
if (DateTime.TryParse(textBox1.Text, out dateTimeValue))
// use the value for something

while inserting it show type converting error

i am calling the validator method in Insert to check for empty text box...and print msg
it prints the msg but Show this msg i.e
Failed to convert property value of type java.lang.String to required type float for property advance; nested exception is java.lang.NumberFormatException: empty String
the text box field which i am validating is float type...
can any body tell me how to remove this error.
this is the form tag
[form:input path="advance" id="addpa"]
..>> enttiy
class name is order
private float advance ;
getter and setter method

Resources