Spring MVC 3 form binding - java

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.

Related

Send POST request from Spring controller

I have a question to you. Let me explain the situation. We have a jsp page, there is a post form here with some inputs. When user enter some data and submit the form, my spring controller handles this request, transforms income data and then I should send it's trasformed data with post request to another site with the client redirection. In other words I want to know is it some oppotunity to use response.sendRedirect("some other website url") with post request in my controller? Or how I can do it another way?
For example simple form:
<form action="myServerSideUrl" method="post>
<input type="text" name="Input1"/>
<input type="text" name="Input1"/>
<input type="submit" value="submit"/>
</form>
When user submit it, it comes to server, then for example I sum Input1 and Input2 (Input3), and then I want to redirect user to another site with Input3 POST request.
You may use Spring's own RestTemplate or a simple java.net.URLConnection (but you have to write a bit more code) to make a POST request in your controller.
So upon receiving the request in your #Controller you can just forward it wherever you want.
<html:form action="changePassword" method="POST"
commandName="changePasswordForm">
<label> <html:password path="password" id="oldPassword"
maxlength="128" class="input" required="required"
placeholder="Current Password" />
</label>
<label> <html:password path="newPassword" id="password"
maxlength="15" required="required" class="input"
placeholder="New Password" />
</label>
<label> <html:password path="confirmPassword"
id="confirmNewPassword" maxlength="15" required="required"
class="input" placeholder="Confirm Password" />
</label>
<label> <html:input path="" type="submit" value="SAVE"
/>
</label>
</html:form>
Spring Controller is below :
#RequestMapping(value = "changePassword", method = RequestMethod.POST)
public String changePassword( #ModelAttribute(value = "searchForm") SearchForm searchForm,
Model inModel,
HttpServletRequest inRequest )
{
String viewName ="changePassPage";
// do something logic related to change password.
return viewName ;
}
Form Bean Or POJO Model in spring:
public class SearchForm
{
private String password;
private String newPassword;
private String confirmPassword;
//setter & getter;
}
You can try with Spring Post Example

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).

Get value from jsp via spring controller

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";
}
}

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.

form values not submitted to the servlet

I am trying to submit the text field value and print it using the servlet. The index.jsp is my main page and I am using jsp:include to include the form which reside in another page which is login.html.
here is the code i have for login.html
<form id="f1" action="ControllerServlet" method="GET">
<p>username
<input class ="text-input" type="text" id="txtusername" />
</p>
<p>
<input type="submit" value="submit" />
</p>
the index.jsp
<div id="col3_content" class="clearfix">
<h1>H1 Heading</h1>
<jsp:include page="login.html"></jsp:include>
</div>
the controller servlet
String usrname = request.getParameter("txtusername").toString();
out.print(usrname);
The problem is this is throwing a null pointer exception. what am I doing wrong here ? any help appreciated. thanks
Please use name not id
<input class ="text-input" type="text" name="txtusername" />
The id is not used to identify the name of the input parameter. The right attribute for the parameter is name, currently you are using an input without a name. So use
<input class ="text-input" type="text" name="txtusername" id="txtusername" />
You need to define name attribute of input tag to get it in Servlet by name.
<input class ="text-input" type="text" id="txtusername" name="txtusername" />
Also make sure you are writing code in doGet or service method of servlet as you have GET as action in form tag.
Code for Login.html
<form action="ControllerServlet" method="GET">
<p>username :
<input type ="text" name="txtusername" /></p>
<p><input type="submit" value="submit" /> </p>
</form>
ControllerServlet.java
public void service(ServletRequest request, ServletResponse response)
{
String username = request.getParameter("txtusername");
PrintWriter out = response.getWriter();
out.println("User Name " + username)
I faced a similar situation, when I checked front end, the form seems to have all the value populated correctly. However, after form.submit, from server side using request.getParameter("the parameter") does not return the value populated. After tuning on the network traffic tab in browser, I see the parameter was there, but there was a typo.
Hopefully could save you some time if same thing happens to you.

Categories