Spring MVC Front End Validations - spring

I wanted to validate user inputs in my jsp which were binded to Springformdata objects using <spring:bind> without hitting the controller.
Is there any other way I can achive this in spring MVC without using javascrpit.
See below code
<tr><td>
<spring:bind path="applyDmlFormData.file">
Select DML File : <input type="file" name="file"/>
</spring:bind>
</td></tr>
Here I am asking user to browse/select the input file and then attaching that to applyDmlFormData objects' file property.
If user don't selects any file and submits the form I wanted to validate that in the forntend itself without hitting the controller and display a error message saying file must me choosen. Basically I wanted to achieve the same functionality which is available in struts validation framework.
One more thing to add is I dont want to use validator which will be invoked by controller
#RequestMapping(value="/applyDml.htm", method = RequestMethod.POST)
public String process(#ModelAttribute("applyDmlFormData") ApplyDmlFormData applyDmlFormData, BindingResult result, SessionStatus status, HttpServletRequest request)
{
String mav = applyDmls;
validator.validate(applyDmlFormData, result);
if(!result.hasErrors())
{ //Business logic goes here
}
}
In the above code I am validating user inputs using validator.validate I dont want to do that.

The Struts Validator framework generates client-side JavaScript; AFAIK, Spring MVC doesn't offer a similar functionality. You need to roll your own client-side validation code. Even if you include Spring JS in your application, you still need to write your own validation code; here's an example.
Note that you don't need to use use a Validator object in your handler methods. You can also annotate your #ModelAttribute with #Valid and use JSR-303 annotations. See http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#validation-beanvalidation-overview for details.

You can explore the Rhino library..find the spring integration api here

Related

Spring annotations #ModelAttribute and #Valid

What are the advantages of using #ModelAttribute and #Valid?
Which are the differences?
Is it possible to use them together?
#ModelAttribute is used to map/bind a a method parameter or method return type to a named model attribute. See #ModelAttributes JavaDoc. This is a Spring annotation.
#Valid is an annotation that marks an object for JSR-303 bean validation. See #Valids JavaDoc. It is part of JavaEE 6, but I think Hibernate has an earlier implementation that most people use instead.
The advantage of using #ModelAttribute is that you can map a form's inputs to a bean. The advantage of #Valid is that you can utilize JSR-303 bean validation to ensure that the bean that is made is validated against some set of rules.
Yes you can use #ModelAttribute and #Valid together.
The best way to transfer data from a form (sic View) to the a Model object is to follow the typical/traditional MVC design pattern using Spring. My personal preferred way is to have a form in a JSP with Spring JSTL <form:*> tags, with a modelAttribute set. On the Controller, have a handler to accept the POST from the form that has a matching #ModelAttribute that is a bean that represents the form's input. I would then pass that "Form Bean" to a service layer to do some things, including translating the "Form Bean" into any models if needed (not necessary if the form is creating your model objects directly) and saving/updating/etc via a DAO. This is but one way to do things, but it's probably the bulk of what I do with Spring in my day-to-day job.
I would highly recommend reading the Spring reference materials and following the tutorials. The reference materials are very well written, easy to follow, and includes lots of examples on the various ways you can do things in Spring, and there are usually quite a few options on how you do things in Spring.
please check the below part fro spring reference documentation:
In addition to data binding you can also invoke validation using your own custom validator passing the same BindingResult that was used to record data binding errors. That allows for data binding and validation errors to be accumulated in one place and subsequently reported back to the user:
#RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(#ModelAttribute("pet") Pet pet, BindingResult result) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}
// ...
}
Or you can have validation invoked automatically by adding the JSR-303 #Valid annotation:
#RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(#Valid #ModelAttribute("pet") Pet pet, BindingResult result) {
if (result.hasErrors()) {
return "petForm";
}
// ...
}

How to handle DTOs for Request, Response and Entities in Spring MVC

I'm a little bit unsure about how to design a complex Spring MVC application in the best way.
The problem is related to a usermanagement system. My UserVO implements the UserDetails interface of Spring.
But for request and response only a special part of information is needed.
In the request it should be allowed to send the password in order to change it. But flags like 'enabled', 'expired', 'locked' should obviously not be changable by the user.
On the other side this information should be displayed to the user, so must be included in the Response. The password is never send to the client.
I started with using the JsonIgnore and JsonAttribute Annotations on setter- and getter. But as the flags are boolean they are persisted with the default value 'false' every time I update.
Possible solution: Writing a DTO for response as well as for the request and using the ObjectMapper of Spring to persist them. Is this the right approach? I would feel more comfortable if I could just work with my VOs and set some magic annotations if you know what I mean ;)
You probably need a form-backing bean. You will find a ton of examples on internet.
EDIT :
Example with user. Your form contains the username, a field to change the password and a field to reconfirm the password.
The username is in you User POJO wich contains all the data relative to your user.
To catch the password and password confirm from your form (and all other data that you expose from your User POJO you need a form-backing bean).
public class UserBacking {
private String newPsw;
private String confirmPsw;
private User user;
}
In your form
<form:form action="${postUrl}" commandName="userBacking " method="POST">
<!-- Fields goes here -->
</form>
In your Controller, your method will receive as ModelAttribute the UserBacking object.

<form:form modelAttribute .. using two beans in JSP

This is a spring based application. My form definition in JSP is as below,
<form:form modelAttribute="article" enctype="multipart/form-data" method="POST"
action="${sendEmailUrl}" name="postAd" id="postAd">
I want to display some data from 'article' bean on my form so I've defined modelAttribute='article'. Till here it is all fine. But on submit of the form, I want to collect data in different bean than article. Since I can define modelAttribute only once in the form, can someone please advise how can I use two beans in JSP?
P.S. In case I am not clear, let me give more details. On submit of form, data entered by user will be collected in bean 'X' and email will be sent using java email. But bean 'Y' (article in this case) is holding some values which needs to be displayed on the form.
Hope I am clear.
You could create a FormBean class, containing the two beans you said. Use this new class as a modelAttribute in your form and you will be able to access to both object's properties.
public class FormBean {
public Article article;
public YourOtherObject yourOtherObject;
}

spring mvc form handling without using spring tag

Recently, I have been researching a new framework for the purpose of building a web-application. To this end, I wanted to try out Spring MVC. Of the many parameters for evaluating a framework, one is that I don't want to be bound to the tag libs associated with the framework to make use of the HTTP request parameter -> Java bean translation. The Spring MVC documentation repeatedly mentions that it is possible to do view related things with only JSTL and no Spring tags, however, I haven't found a way to get the Request-to-Bean translation feature [SimpleFormController] to work without Spring tags.
As of now, the only way seems to extract the request parameters one by one and set to my bean. Is there any way to perform this translation w/o using framework dependent tags?
I appreciate your inputs!
I use Spring Web MVC without Velocity templates (non-JSP templating). To answer your question, you need to understand how Spring performs data binding. Basically, it's all in the name you give your input elements. E.g
<input name="properytOne" value="1" type="hidden">
<input name="properytTwo" value="2" type="hidden">
<input name="rich.property3" value="3" type="hidden">
will bind values to an object like this
class CommandOne {
private String propertyOne;
private String popertyTwo;
private CommandTwo rich;
// Getters and setters
}
class CommandTwo {
private String propertyThree;
// Getters and setters
}
You also have to be sure to instantiate your command object, but that will be handled in your SimpleFormController.
Spring tags are completely optional.
Read chapter 15, 16, and 17 of the Spring Reference Document You can use annotations to retrieve request parameters with your controller (see section 15.3).
As per my understanding, what you are trying to achieve is Binding your form to your Bean Class, which is very nicely implemented in JSF. JSF works on component architecture and very easy to start with, plus it has many component builers available such as primefaces, omnifaces, icefaces, openfaces, etc. Reusability of self-designed components can help you a lot in specific projects. Try giving a chance to JSF. Thanks, hope this was helpful.

Spring webflow validation

complete and utter newbie on spring webflow (and indeed, spring mvc).
30 minutes in... got the first page of my flow appearing, which happens to be a captcha, an input field and a submit button.
The actual captcha value is stored in session and i need to validate that the input field values matches the value in session.
In order to do validation, my model is passed a 'ValidationContext'.
Question: i can't seem to access session data from the ValidationContext. How do i do this?
Thanks!
try MessageContext in place of validationContext
In spring webflow we have a model class and a model validator class. Make sure you have created a validator method in the validator class and it must have same name as the method you are trying to validate (The method where you have those input fields). This should give you a guideline on getting started.

Resources