Get value from jsp via spring controller - java

I've created MVC Template via Spring Tool Suite IDE, but I can't realize, how to get values from jsp. For exmaple - I've created text input in jsp
<input type="text" />
but how to get the value to controller to be able to work with it there? I know, that when I add atribute to model in my controller, then I can access it via ${name} , but how to do it the other way?

You need a form and then submit the value to the controller ...
Something like :
<form name="foo" action="/foo/bar" method="post">
<input name="fieldName" type="text" />
<input type="submit" value="Submit">
<form>
And then get it in your controller :
#Controller
#RequestMapping(value = "/foo")
public class AdminController {
#RequestMapping(value = "/bar")
public String testAction(#RequestParam String fieldName) {
// yourValue contain the value post from the html form
return "yourview";
}
}

Related

Validate a single field against a result from a service in Spring MVC

I can't figure out how to do a simple, 1-field validation where I check the value against a service (or really any other logic check).
Most of the form validation I see uses a class to hold form data using javax.validation and marking up with attributes like #NotNull, #Min(10), etc. And then checking a BindingResult.hasErrors(). Like here: https://spring.io/guides/gs/validating-form-input/
I'm trying to do this for a single field and I want to validate against what a service will return to me rather than one of those validation attributes.
What do I put in my POST handler in the controller to get this going?
This is what I have in my controller to manage the result from the form
#RequestMapping(value = "/myController", method=RequestMethod.POST)
public String checkFieldVal(#RequestParam String valFromForm){
if(!myService.isThisValueGood(valFromForm)) {
//Show the user their value is bad
}
//return to some other page
}
And this is in my JSP (something simple like this):
<form id="form" method="POST">
<label for="valueToCheck">What's your value:</label>
<input type="text" id="valueToCheck" name="valueToCheck"></input>
<input type="submit" value="Submit">
</form >
Try to replace this:
<form id="form" method="POST">
With adding the action like this:
<form action="myController" id="form" method="POST">
And replace this:
#RequestMapping(value = "/myController", method=RequestMethod.POST)
public String checkFieldVal(#RequestParam String valFromForm){
With adding the right name:
#RequestMapping(value = "/myController", method=RequestMethod.POST)
public String checkFieldVal(#RequestParam("valueToCheck") String valueToCheck){
The param name must match in both controller and html.
#RequestParam String valFromForm
<input ... name="valueToCheck">
Option 1: Leaving jsp as it is, you change controller code as,
#RequestParam String valueToCheck
Or you may add qualifier to parameter name as,
#RequestParam("valueToCheck") String valFromForm
Option 2: Leaving controller as it is, you change jsp as,
<input ... name="valFromForm">

Spring-MVC : two jsps into one controller with one requestMapping

Can I use one request mapping for two jsps?
I am currently calling one request mapping from one controller but one of the jsps doesn't seem to be caught by the controller.
Both jsps have the same form action and same form method:
first.jsp look like this:
<form:form method="POST" action="/ShowroomNav/requestQuote" id="requestQuoteForm">
<input type="hidden" value=${product.productCode } name="productCodes" />
<input type="hidden" id="requestQuoteEmailAddress" name="requestQuoteEmailAddress" />
</form:form>
the second.jsp look like this:
<form:form method="POST" action="/ShowroomNav/requestQuote" id="requestQuoteForm">
<input type="hidden" id="requestQuoteEmailAddress" name="requestEmailAddress" />
<c:forEach var="product" items="${products}">
<input type="hidden" value=${product.productCode } name="productCodes" />
<div class="box">
<img
src="public/productImages/${product.productCode}/${product.productCode}A.jpg"
style="max-width: 100%"
onclick="productProfile('${product.productCode}')" /><br /> <label
class="name">${product.productName}</label>
</div>
</c:forEach>
</form:form>
both of them submits the function by a javascript call of :
$("#requestQuoteSubmitButton").one("click",function(){
$("#requestQuoteEmailAddress").val($("#requestQuoteEmailAddressModal").val());
alert($("#requestQuoteEmailAddress").val());
$("#requestQuoteForm").submit();
});
this is how the controller.java looks like:
#RequestMapping(value = "/requestQuote", method = RequestMethod.POST) // or GET
public String requestQuote(#RequestParam("requestQuoteEmailAddress") String requestQuoteEmailAddress, #RequestParam("productCodes") String[] productCodes) {
System.out.println(">>>> requesting quotes >>>>");
for(int i=0; i<productCodes.length; i++) {
System.out.println(" Product Codes : " + productCodes[i]);
}
System.out.println("requestQuoteEmailAddress : " + requestQuoteEmailAddress );
System.out.println("<<<<< requesting quotes <<<<");
return "productSearch";
}
So I don't know why the second.jsp cannot be caught by the controller as it always shows this error when I try to submit it.
HTTP Status 400 - The request sent by the client was syntactically incorrect.
Can somebody help please?
The problem is (a typo?) in your 2nd line of your second.jsp snippet:
<input type="hidden" id="requestQuoteEmailAddress" name="requestEmailAddress" />
The id attribute is mainly for client side reference, and doesn't matter when form is submitted (see HTML input - name vs. id). What's important is the name attribute. So when the POST request is sent to server, the request body looks like:
requestEmailAddress=...&productCodes=...&productCodes=...
Since you annotated the handler method parameter as #RequestParam("requestQuoteEmailAddress"), Spring MVC looks for requestQuoteEmailAddress instead of requestEmailAddress, thus the error (#RequestParam's required is true by default).

How to pass two objects to use in a form using thymeleaf?

My problem is the following :
I've 2 differents objects that I've to fill from a single form.
With 1 object, I simply do in the newFoo.html:
<form th:object="${foo}" th:action="#{/foo}" method="post">
<input type="text" th:field="*{name}"/>
<button type="submit">Go</button>
</form>
and in the FooController:
#RequestMapping(value = "/foo/new", method = RequestMethod.GET)
public String newFoo(final Foo foo, Model model) {
return "newFoo";
}
#RequestMapping(value = "/foo/new", method = RequestMethod.POST)
public String saveFoo(final Foo foo, final BindingResult bindingResult, Model model) {
fooService.save(foo);
return "redirect:/foo/new";
}
Let's say I've an other object bar with a "status" variable in it. How can I do to pass that object so I can submit the input within the same form?
Like:
<form th:object="${foo} && ${bar}" th:action="#{/foo}" method="post">
<input type="text" th:field="*{name}"/>
<input type="text" th:field="*{status}"/>
<button type="submit">Go</button>
</form>
So far I tried to do with to fieldset with a th:object in it, that doesn't work, I tried to put two th:object in the form, that doesn't work either.
The only way I found is to build an other object containing those two objects, and pass it. That works well, but I can't create that kind of object, it's nonsense (even if it works).
Of course, the objects aren't as simple as Foo and Bar here, otherwise I would have merge those two. But that's not something I can do.
Is it even possible to pass two objects like that to use in a form ?
Thanks already.
I don't think you need to use two th:objects. Just use th:value
<form th:action="#{/foo}" method="post">
<input type="text" th:value="${foo.name}" name="name"/>
<input type="text" th:value="${bar.status}" name="status"/>
<button type="submit">Go</button>
</form>
I would think Spring is smart enough, on the controller side, to use its mapping techniques to map your fields to their proper command object, foo or bar.
i used a div tag to surround the form input for my second object and added a th:object..... the controller processed it and added it to the database.
<form method=post th:object="${object1}" >
<div th:object="${object2}" >
code......
</div>
<input type="submit" />
</form>

Do Spring MVC controller look for ids or names?

If I have the following HTML form:
<form id="myForm" action="/myFormHandler" method="post">
<input type="hidden" id="fizz-id" name="fizz" value="3" />
<input type="hidden" id="buzz-id" name="buzz" value="6" />
</form>
(Notice no submit button). And then I have the following jQuery:
$("#someButton").click(function() {
$("#myForm").submit();
});
Then on the server-side (Spring MVC controller), do the hidden field ids or names get sent to the handler method?
#RequestMapping(value = "/myFormHandler.html", method = RequestMethod.POST)
public ModelAndView handleMyForm(
#RequestParam("fizz-id") String fizz,
#RequestParam("buzz-id") String buzz) {
// Should I be looking for "fizz-id" or "fizz"???
}
Thanks in advance.
Its the name attribute that is sent to the server, so in this case you should look for "fizz".
The id attribute is just used for client side interaction, it is not sent in the request to the server.
with a post request ,it is the name attribute of a HTML element that is used to access it using request.getParameter.

Spring MVC 3 form binding

I have a simple HTML form:
<form id="marketplaceForm" enctype="multipart/form-data" method="post">
<select name="category">
<option selected ></option>
<option value="Sales">Sales</option>
<option value="Marketing" >Marketing</option>
</select>
<textarea type="text" id="marketplaceDesc" name="description" value="" class="creattbleArea"></textarea>
<input type="text" id="marketplaceName" name="templateName" >
<input type="file" id="marketplaceLogo" name="logo">
<input type="submit" value="Save" id="update" />
<input type="text" id="marketplacePrice" name="price">
</form>
I need to auto bind this form when I submit it. This works fine:
#RequestMapping(value = "/.....", method = RequestMethod.POST)
public String PublishForm() {
But this throws the following error:
HTTP Status 400 -
The request sent by the client was syntactically incorrect
#RequestMapping(value = "/PublishApplication.htm", method = RequestMethod.POST)
public String PublishForm(#RequestParam("templateName") String templateName,
#RequestParam("category") String category,
#RequestParam("price") String price,
#RequestParam("description") String description
) {
Can any one help me?
Update: I have found that if I remove enctype="multipart/form-data" from the HTML form, it works. Now my question is how to make it work with enctype="multipart/form-data".
I think you may be missing the Multipart resolver from your configuration.
do you have something like this in your configuration?
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="250000"/>
</bean>
see here for the offical spring documentation on the matter.
First of all, make sure the binding to PublishApplication.htm really works. You are using this mapping in your controller, but you haven't specified it in action param of <form> tag. So you may end up with posting the form to some different controller, and server rejects your request. Of course this will not happen if you are using the same controller for both - displaying form and submiting it, and you have aplied RequestMapping annotation at class level.
There is another issue with your controller though. You are not specifying logo as #RequestParam in PublishForm method. I'm not sure if this is not messing up form autobinding. If I recall correctly, those params are required by default.

Categories