javax.validation.Valid with Spring MVC - java

I am using #Valid for validation during a form submission and encountered error that a property is null. I have a Country class which have properties such as code, name and createdBy all with their predefined values. When user load the page the loaded property on the form are only code and name. After user changes the value and perform submission the value of createdByis null thus validation fails. I am thinking of storing createdBy value in a hidden field on html so the validation should pass. In view of security I think anyone can actually modify the hidden field value. Is there a better approach ? Will OpenSessionInViewFilter helps in any way ?
UPDATED
Sorry that I forgot to mention, the data the browser gets from the server is in form of JSON (List of json object). Before form submission a wrote a JavaScript to populate the form based on the chosen object (with ID) within a html table. So what I send to the server is basically
<input type="hidden" name="id"/>
<html:field name="code" labelCode="label.code" type="text"/>
<html:field name="name" labelCode="label.name" type="text"/>

Related

Spring MVC and form binding : how to tell Spring not to instantiate child objects if all their fields are empty?

I have trouble to understand how to stop Spring from initializing the child member object of a form bean if none of his fields were modified by the corresponding form. For example I have an User Object that has a field Address, I pass the empty User instance to the form (the Address is null at the time).
In the form I have input fields for all User as well as Address fields:
<form action="#" th:action="#{/user/add}" th:object="${user}" method="post">
...
<input type="text" th:field="*{address.street}"/>
<input type="text" th:field="*{firstName}"/>
...
when I set a breakpoint in the corresponding controller method, the Address object exist within the User object and all its fields are null,0,false(default values). I know the initialization occurs in the WebDataBinder. How can I instruct it not to do so?
The same happens with the dynamic lists, if i had List then the List would get a new entry after form submit.
Would really appreciate any help
You need that object instantiated or you could not store the values entered in the form anywhere.
If you don't want to save the empty object to the DB then you probably need to check it on modification before saving.

How to process form by <jsp:setBean> and send it to servlet?

Could you help me to come up with solution.
There are JSP-page which sends form parameters to servlet.
Usually I parse parameters by HttpServletRequest.getParameter() which works fine for forms with tiny parameter numbers.
Now I'm developing application which has a lot of JSPs with number of parameters and the standard way of form processing is inconvenient.
I think that possible solution might be by using -action.
I don't understand whether it works for me.
I browsed a lot of materials but find nothing about it.
I mean that there is any information regarding possibility to get form parameters in jsp by ,
automatically create instance of the entity class,
map all the parameters to entity-properties and send the entity-instance to the servlet.
Please take a look at the code:
index.jsp
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="NewFormServlet" enctype="application/x-www-form-urlencoded">
<jsp:useBean id="client-bean" class="model.entity.Client" scope="request"/>
<h3>Please enter client information</h3><br>
Client first name<input type="text" name="first-name"/><br>
<jsp:setProperty name="client-bean" property="firstName" value="${requestScope.first-name}"/>
Client last name<input type="text" name="last-name"/><br>
<jsp:setProperty name="client-bean" property="lastName" value="${requestScope.last-name}"/>
Client address<input type="text" name="address" size="100"/><br>
<jsp:setProperty name="client-bean" property="address" value="${requestScope.address}"/>
Client city<input type="text" name="city"/><br>
<jsp:setProperty name="client-bean" property="city" param="${requestScope.city}"/>
Client postal code<input type="text" name="postal-code"><br>
<jsp:setProperty name="client-bean" property="postalCode" value="${requestScope.postal-code}"/>
<input type="hidden" name="jsp-identifier" value="client-form">
<input type="submit" value="Submit">
</form>
</body>
</html>
What is incorrect in this code? Thank you in advance.
You should first think about what occurs on server and what occurs in browser, as well as what is transmitted via HTTP. A form submission uses many phases :
on server : the JSP is executed using servlet context, session, and request attributes, with still full access at the previous request (parameters, ...) => all that generates a HTML page (with eventually css or javascript linked or included)
on browser : the browser gets and parses the HTML page, optionnaly gets linked resources (images, etc.), and display the form to the user
on browser : the user fills the input fields of the form and clicks the input button
on browser : the browser collates data form input fields, generate an new HTTP request (usually a POST one) and sends it to server
on server : the servlet container pre-processes the request (until that is is only a stream of bytes conforming to HTTP protocol) and calls the appropriate servlet method with a new HttpServletRequest reflecting current HTTP request, and a HttpServletResponse to prepare what will be sent back to browser after processing
All that means that anything you can do to request attributes in the JSP part will be lost at the time of processing of the submitted form by the servlet. You can only rely on session attributes, and on input form fields that will be accessible as request parameters.
So with your current JSP, the Servlet will find nothing in request attributes (it is a different HttpServletRequest) and will only be able to use parameters with names firstName, lastName, address, city, etc.
I can understand it is not the expected answer, but HTTP protocol is like that ...
EDIT per comment :
You can put the attribute in session, and then the servlet will use the same session as the JSP. But read again what I wrote above and think when things happen :
on server, when executing the JSP, you create an empty Client bean that you put in session scope, and use its value to initialize the form fields. Stop for the server part
on client, user fills the input fields - the server knows nothing on that - and submit the form through a new request
on server, the servlet has the values in request parameters, but the session still contains the previous values and so the Client bean has null values
I'm sorry but there's not enough magic for the server to automatically find in its attributes (either request or session) what comes from form submission : it only exists in request parameters, and it is the servlet job to process them and eventually put them in attributes.
Edit:
It appears that jsp:useBean is an old school way to collect up a group of parameter values for easier display on a page.
It does not add an attribute when the request is posted.
Based on that,
I see little value in the jsp:useBean tag,
since you can use el expressions to access attributes that you set in a servlet.
This does not help you get the posted parameter values into a bean in the servlet.
You can write a method on the bean to extract the parameter values from the request (visitor pattern).
For example:
class bean
{
private String value;
public void loadFromHttpServletRequest(final HttpServletRequest request)
{
value = request.getParameter("value");
}
}
Consider using a package like spring-mvc.

Spring MVC: Form Bind: Erroneous inputs do not retain value

I am using standard spring mvc tags, ala:
<form:input id="startDate" path="startDate" cssClass="datepicker" cssErrorClass="error datepicker" placeholder="Start Date" />
backed by a form object.
My inputs are validated on the serverside, either using annotation based binding on the form object, ala:
#NotNull
getStartDate() {
return this.startDate();
}
or being explicitly rejected, ala:
FieldError fieldErr = new FieldError("theForm", "startDate", "Please check your dates");
BindingResult result.addError(fieldErr);
If an input fails validation, the spring tag correctly adds the cssErrorClass to the input. However, my problem. I'd like the erroneous content to stay populated in the input tag. If 1/1/14 is determined to be invalid, I want the form to be repopulated with 1/1/14 as the value of that input.
So... help? Anyone have a workaround for this? Thanks!
you have 2 options:
1- add the form to model again with same name used in
2- put your form as #SeeeionAttribute, but in this case your form will be stored in session and you will need to clean your session from it after finish of using it.

How to Get an id in jsp instead of value?

how to get button id from jsp to servlet instead of getting the button value
<input id="${section.id}" type="submit" name="submit" value="Edit">
how to get that id in servlet?
You can't that id is for client side use only. You will need to set the name or value to match the id of the element.
Alternatively as a workaround you could create a hidden input field that contains the id value by adding something like this to your JSP:
<input type="hidden" name="submit_id" value="${section.id}" />
This will then be available in the servlet upon form submit under the submit_id parameter.
String submitId = (String)request.getParameter("submit_id");
The only way you would be able to do that is by intercepting the form submit using javascript and setting the id as an extra post/get parameter.
the only way is make a javascript function that change your button value for the id , but i dont know why you want to do that, you could use a hidden input to send the data in the form
<input type="hidden" name="id" value="the_id_number" />
You cannot get any button id value to servlet. When a request from browser is submitted, all the input fields(input tag) will be transferred to server.The value of each input attribute can be accessed using the name of that field.All other fields like id, class etc are used for css and JavaScript functionalists.You should not design to pass the button id to server side.Think of other methods like hidden input fields

Spring - Displaying a Label that reflects and updates a #ModelAttribute field

I have a #ModelAttribute account which has a field named title. I need to display this field in my JSP, and also bind it in the next call cycle. If I do this;
Title: ${editAccountForm.account.title} <br/>
It only displays the value. When someone submits the Form in the JSP, account is empty again. How do I get the label to reflect the value, just like a form:input tag?
I tried this:
<form:label path="account.issuer">some text</form:label> <br/>
but it dint work. Please help.
You can put a
<input type="hidden" name="account.title" value="${editAccountForm.account.title}" />
The name attribute must be the same as the one generated by a spring form:input.
but that is the same to displaying it normally ${editAccountForm.account.title}. After that, populate the value in a hidden field. that will update the value in the model

Categories