Spring form validation for plain HTML form - java

I need to validate some simple forms in my application. In these forms I have one or two input text to validate so I'd like to not create a specific ModelAttribute class for every form. I'd like to use instead plain HTML form and use #RequestParam annotations to handle POST parameters.
Is there a way to use Spring form validation in this situation (without using model attribute) or should I implement a backing-form object and a validator for each form?

Currently it is not possible to use #Valid on individual #RequestParam, #PathVariable etc. to trigger validation. This is the relevant feature request on the Spring Issue Tracker. Let's cross our fingers for Spring 4.1!
In your case, you will either have to use #ModelAttribute, or perform custom validation inside the controller (or maybe a Spring interceptor if you want the same validation to apply to multiple endpoints)

I think you can do this with Annotation. You can specifie for your parameters annotation like :
#Size(min=3, max=5)
#NotNull
#NotEmpty
...

Without a model attribute, Spring form Validation is not possible. Because Spring Form Validation depends on Spring Form Binding, which is a linkage between form elements and Model Attribute. So how small the form may be, create a DTO(Model Attribute), bind it to form and Perform Validations.

Definitely not possible using Spring's validation API (Errors object):
java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the #RequestBody or the #RequestPart arguments to which they apply

You could instantiate a model object, fill it with the data from the plain form and validate that object programmatically.

Related

Are Spring Model objects (and their attributes) tied to their respective controller endpoints / templates?

I'm just starting with spring so please bear with me. I've just solved a bug in my code that was coming from my assumption that once an attribute is added to any Model object, it would also be available to the templating implementation at other endpoints.
#GetMapping("/user_page")
public String getUserPage( Model model ) {
Page page = new Page();
model.addAttribute("user_page", page);
return "user_page";
In my Thymeleaf template I was able to use this attribute fine at user_page.html. Now at another endpoint and template I was also trying to use this user_page attribute. Note that it was throwing some errors:
Exception evaluating SpringEL expression:
and
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'name' cannot be found on null
It looks like Thymeleaf couldn't find the user_page attribute.
but I also hadn't added a Model parameter to the controller that handled this other endpoint. After adding a Model to the method parameters and adding the page again model.addAttribute("user_page", page);, this time to the controller handling the different endpoint, the problem went away.
Is Spring autowiring non-singleton Model objects to these controllers? Why did I have to add the same page instance to the model twice? So are these Models tied specifically to the template (maybe even endpoint) that their respective controller returns?
Read Dispatcher Servlet Processing Sequence.
Are Spring Model objects (and their attributes) tied to their respective controller endpoints / templates?
There is no such a thing, as "Model's respective controller"; rather, a fresh instance of the Model's implementation gets instantiated each time, any handler method gets invoked.
When an HTTP request hits dispatcher servlet, and the latter passes the servlet request-response objects into the corresponding handler method, Spring MVC's infrastructure looks up the signature of corresponding handler method and passes a fresh instance of the Model (along with many others), if it is expected.
You can also use modelAttribute element in your template's form, and this way, you will directly bind the data to the handler method's Model parameter, having the argument being pre-filled with the form data. In this case, you can also enable Bean Validation.

How do I configure validation check in Spring MVC with JSP?

I need a quick help regarding validation check in Spring MVC. I have a basic HTML form not the JSTL Tag form. How do I check or implement a straight forward data validation check in Spring MVC? One way in my mind coming right now is to use regex to verify the user name is alphanumeric [a-zA-Z0-9].
But I have seen people use Validator do this job. I want to use Validator as it seems more profession.
Second question,
I'm trying to get a Exception handling working properly but it is not working. I want the absolute basic response to happen, the response throws a HTTP.404 response. My simple method:
#RequestMapping(value="/request/view/{id}",method=RequestMethod.GET)
public String requestSubmit(Model model)
Now with my response String, how can I do it? After search on Stackoverflow. They said to create a generic class such as NotFoundException and extend it RunTimeException. But I still don't know how to I set the response intentionally to be 404 or any other response actually, even Http.BANDWIDTH_EXCEEEDED_RESPONSE
Fist thing you should know: it's better to use POST instead of GET in form submitting. Because when you use GET, all your model properties sent as url parameter and it's not a good practice.
For using validation, you can use #Valid as this:
public String requestSubmit(#Valid Model model)
Then you can use validation annotation like #NotNull, #Size, ... at every property of Model class you want to validate it.
When a user submits your form, if every form attribute has validation problem, spring throws MethodArgumentNotValidException automatically. For getting validation errors, you can use try-catch block in your controller or better way is to have central exception handler with #ControllerAdvice.

Spring #RequestBody annotation in Restful web service

Thanks to #RestController I don't need to add annotation #ResposneBody, cause spring knows that it is rest controller, and he will not generate view, but instead it will return json object.
Unfortunately there is one more annotation related to this topic. It is #RequestBody, when controller method accept json object as a parameter. And it will have to be pointed before that parameter.
My question is there a way to get rid of that annotation (#RequestBody).? If my controller is rest controller (#RestController instead of regular #Controller) it should be demanded from spring?
No, you'll have to specify #RequestBody. A Java method can have only a single return value, and so the #ResponseBody is unambiguous, but there are multiple possible ways that mapped controller parameters might be interpreted (in particular, using #ModelAttribute with form encoding is a very common alternative to #RequestBody with JSON), and you'll need to tell Spring how to map the incoming request.

How to handle in spring validation of json request / bean if the json cannot be converted to the bean?

I have classic Spring MVC application.
I want to validate a Form using a corresponding Java Bean, annotated with JSR-303 validation annotation.
The form data is sent by an ajax call using JSON. This Json is converted to the target Java Bean with Jackson - automatically by spring:
#RequestMapping(value = ControllerConstants.CALCULATION_MAPPING_SUBMIT_FORM,method = RequestMethod.POST)
public String submitForm(#Valid #RequestBody MyFormBean bean, final BindingResult result) {
...
}
Problem is for example if I have an Integer field in my bean but, in JSON the values is not a number. In this case it cannot create the target bean, that cannot be validated. This situation cannot be solved with custom property editors, since there is no way to convert a a text that not represents an Integer to Integer.
It seems that this is solved in Grails, we get errors from validator (errors is domain object) which has to be created during the data binding. So I assume spring supports this, thus Grails just uses Spring's support)
So how to elegantly solve this situation to handle this "validation" error?
UPDATE
Actually I figured out, that is this is supported by spring if we use simple form submit. The problem is with integration of Jackson deserialized. It does not fills errors. Still how to solve this?
I see two options...
Have client side validation that would not allow the form to be submitted if the there are formatting issues.
On the server side you will have to have a mechanism of handling the exception that would catch it and report the problem back to client.
Hope that helps.
EDIT:
Well not having client side validations may not be a good user experience. Users do not want to be reminded about validation errors after they have made a server round trip. However, if this is still a constraint have a look at following url and it gives elegant way of handling such issues and reporting informative error messages.
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/

controller in spring for form handling

I am newbie in spring. using spring 3.0 mvc.
I am creating a spring application, I have a login form,Any one please suggest what controller i should use, as when I am using SimpleFormController its saying deprecated,
Any specific controller I can use.
First of all as everybody already told you use annotation-base controller
secondly for creating a form you can use spring form taglib
thirdly you can create method like this
public String updateHouse(House house, #RequestParam("file") MultipartFile file, Model model) {
this is from my sample application. House object is auto generated from form. In my form I have fields of my House object and it is send to the method as object. #RequestParam allows me to fetch the file witch is uploaded via form (POST), Model is my view model.
As you can see it is easy :)
Why don't you try annotation-based controllers? They are easy and fun to use.
You can try annotation based controller. Please refer below link:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

Categories

Resources