I am trying to submit a spring form via ajax but the values within the form are always coming across as null (The actual form is not null).
This is how I send the form from the JSP:
$('#fSystemSave').click(function() {
$.post("/live-application/systemSave", {systemForm: $("#systemForm").serialize()}, displayModifiedSystemResults, "html");
});
This is the form:
<form:form id="systemForm"
method="post" action="/live-application/systemSave"
commandName="systemForm">
<tr>
<td colspan="1" align="left">
<strong>SYSTEM SETTINGS</strong>
</td>
</tr>
<tr>
<td valign="top">Name: </td>
<td valign="top"><form:input path="fName" size="20" /> </td>
</tr>
<tr>
<td valign="top" align="left">
<button type="button" id="fSystemSave">Save</button>
</td>
</tr>
</form:form>
And this is the Java controller side:
#RequestMapping(value = "/systemSave", method = RequestMethod.POST)
public void saveSystem(#ModelAttribute("systemForm") SystemForm systemForm, OutputStream outputStream) throws IOException {
logger.info("Save System1: " + systemForm);
logger.info("Save System2: " + systemForm.getfName());
}
So 'Save System1' returns an Object tostring and 'Save System2' returns null. Can anyone spot what I am doing wrong?
Thanks,
I don't know Spring but I think {systemForm: $("#systemForm").serialize()} should just be $("#systemForm").serialize().
Related
I have tried to send a parameter from this thymleaf page
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form style='float:left; padding:5px; height:0px' th:object="${p}" th:method="post" th:action="#{/dashboard/makeAndSendInvoice/{email}(email=${p.email})}">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
and then I tried to receive the parameter (email) using this code
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#PathVariable("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}
The problem is when the value of p.email is something like myemail#gmail.com
what I receive in the method makeAndSendInvoice is only myemail#gmail
and it does not send me the .com part
How can I fix it?
(email=${p.email}) means , you are passing a query parameter.
So, how can you be able to catch the query param value using path variable?
We can use #RequestParam to catch the queryparam value in Spring
Try the below java code :
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#RequestParam("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}
The period in ".com" will need to be encoded to be used in the url to prevent it being parsed as the suffix
Your HTML:
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form method="post" th:action="#{/dashboard/makeAndSendInvoice/__${p.email}__} ">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
Your controller
#RequestMapping(value = "/dashboard")
#Controller
public class testController {
...
#RequestMapping(value = "/makeAndSendInvoice/{email}", method = RequestMethod.POST)
public ModelAndView makeAndSendInvoice(#PathVariable String email, ModelAndView mav) {
return mav; // <- Break point, debug !!
}
}
I have a simple in my jsp with some input fields. It works perfectly fine in most browser and not so much in IE.
When the form is used in IE only the first submit will work. Every submit after that "fails" as some of the parameters from the form are missing. This is NOT an issue on Chrome or Firefox. If I reload the page between each submit it works fine on IE as well, but this is not an option.
form:
<form id="form1" method="post" action="receiver.htm">
<table>
<tr id="name">
<td>Name</td>
<td><input id="input_name" name="name"/></td>
</tr>
<tr>
<td>Amount</td>
<td><input id="amount" name="amount" type="text"/></td>
</tr>
<tr>
<td>Unit</td>
<td><input id="unit" name="unit" type="text"/></td>
</tr>
<tr>
<td colspan="2"><input id="submit_button" type="submit" value="submit"/></div>
</td>
</tr>
</table>
</form>
Controller:
#RequestMapping(value = "/receiver.htm", method = RequestMethod.POST)
#ResponseBody public String receive(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
String name = httpServletRequest.getParameter("name");
String amount = httpServletRequest.getParameter("amount");
UnitType unit = UnitType.getValue(httpServletRequest.getParameter("unit"));
}
UnitType is an enum I made. And it throws the following exception after 2nd submit with IE as some of the parameters return as null:
java.lang.NullPointerException: Name is null
Question is i have table in which i want to populate the values of file name and file size after user click the choose file button and select any number of files, Now the issue is if the user click choose files button second time i want to append the new values in the table and add the new file in the array so that it can uploaded.. my code is,
html form code:
<form id="simpleuploadform" method="post" action="upload" enctype="multipart/form-data">
<table class="span10" border="0">
<tr>
<td colspan="3">
<legend>Simple Upload</legend>
</td>
</tr>
<tr>
<td>
<input type="file" name="files[]" multiple="multiple" onchange="getFileSizeandName(this);"/>
<div id="successdiv" hidden="true" class="label label-success">Image uploaded successfully</div>
<div id="errordiv" hidden="true" class="label label-error">Image not successfully uploaded</div>
<div id="streamdiv" hidden="true" class="label label-warning">Issue while uploading try again</div>
</td>
<td id="renameFile" align="right"></td>
<td id="removeFile" align="right"></td>
</tr>
<tr>
<td colspan="3">
<div id="uploaddiv">
<table id="uploadTable" class="table table-striped table-bordered" width="200" height="200" scrolling="yes">
<thead>
<tr>
<th>Title</th>
<th>Size</th>
</tr>
</thead>
<tbody id="tbodyid">
<tr id="tr0">
<td id="filetd0" height="10px" width="50px"></td>
<td id="filesizetd0" height="10px" width="5px"></td>
</tr>
<tr id="tr1">
<td id="filetd1" height="10px" width="50px"></td>
<td id="filesizetd1" height="10px" width="5px"></td>
</tr>
<tr id="tr2">
<td id="filetd2" height="10px" width="50px"></td>
<td id="filesizetd2" height="10px" width="5px"></td>
</tr>
<tr id="tr3">
<td id="filetd3" height="10px" width="50px"></td>
<td id="filesizetd3" height="10px" width="5px"></td>
</tr>
<tr id="tr4">
<td id="filetd4" height="10px" width="50px"></td>
<td id="filesizetd4" height="10px" width="5px"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td id="filecount" height="10px" width="50px"></td>
<td id="totalsize" height="10px" width="5px"></td>
</tr>
</tfoot>
</table>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" class="btn btn-primary" onClick="CloseAndRefresh();" value="Start Upload" id="startButton" disabled>
<input type="reset" class="btn btn-primary" onClick="Clear();" value="Clear" id="clearButton" disabled>
<input type="button" class="btn" onClick="window.close();" value="Close">
</td>
</tr>
</table>
javascript code:
<script type="text/javascript">
var totalsizeOfUploadFiles = 0;
function getFileSizeandName(input)
{
var select = $('#uploadTable tbody');
$('#renameFile').empty();$('#removeFile').empty();
if(input.files.length > 0)
{
$('#renameFile').append($('<a id="renameRec">Rename Selected</a>'));
$('#removeFile').append($('<a id="removeRec">Remove Selected</a>'));
$('#startButton').removeAttr("disabled", "disabled");
$('#clearButton').removeAttr("disabled", "disabled");
}
//if(input.files.length <= 5)
//{
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size;
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2);
var filename = input.files[i].name;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
if(i<=4)
{
$('#filetd'+i+'').text(filename);
$('#filesizetd'+i+'').text(filesizeInMB);
}
else if(i>4)
select.append($('<tr id=tr'+i+'><td id=filetd'+i+'>'+filename+'</td><td id=filesizetd'+i+'>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles += parseFloat(filesizeInMB);
$('#totalsize').text(totalsizeOfUploadFiles.toFixed(2)+" MB");
if(i==0)
$('#filecount').text("1file");
else
{
var no = parseInt(i) + 1;
$('#filecount').text(no+"files");
}
}
//}
}
function CloseAndRefresh()
{
var daa = '<%=status%>';
if(daa == "true")
$('#successdiv').show();
else if(daa == "false")
$('#errordiv').show();
else
$('#streamdiv').show();
opener.location.reload(true);
self.close();
}
function Clear()
{
$('#uploadTable tbody tr td').each(function(){
$(this).text("");
});
$('#uploadTable tfoot tr td').each(function(){
$(this).text("");
});
}
i am trying to do as like this http://www.shutterfly.com/ image upload.
any help will be appreciated, thank you friends...
You are navigating away using javascript, function CloseAndRefresh on clicking submit button.
What actually happens is that the uploading request is being submitted while the CloseAndRefresh function is being executed at almost the same time using different thread. If the upload request is not fast enough, the web page will get refresh first and your upload request get terminated immediately. There is no easy way to prevent this using your existing code.
You should use advanced method of uploading like jQuery uploading plugin to send the request. The plugin provide an binder to execute function on successful/failed submittsion.
Thank you gigadot, i solve the issue as like below,
The html form have the same code as i posted earlier, in the previous js code i have the CloseAndRefresh() method i remove it now from js as well as from the submit button onclick event.
When the form action called the controller, in which i have the code
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String UploadReceipts(#RequestParam("files[]") List<MultipartFile> file, Model model) throws IOException {
boolean status = false;
try
{
for(int i=0; i< file.size(); i++)
{
if(!file.get(i).isEmpty())
{
CommonsMultipartFile cm = (CommonsMultipartFile) file.get(i);
status = simpleUploadService.uploadFileandSave(cm);
model.addAttribute("status", status);
}
}
}
catch (IOException e) {
status = false;
model.addAttribute("status", status);
}
return "pages/simpleUploadStatus";
}
Now i redirect it to another page in which i throws the appropriate messages for the user.
that's all...
I have a login page with form action of j_security_check. As of now this form just have two fields namely username
and password. I want to add a new dropdown to this form and collect the selected value in controller using
#RequestParam. For some reason I am not able to pass this dropdown value from JSP to my controller as its throwing the
exception: MissingServletRequestParameterException (Which occurs anytime a request param is missing).
In the code below I added the Visuals dropdown. Do I need to use Spring:Bind tag here?
Also on successful login, the control is directed to a controller with request mapping /controller1.html and this is where
I am trying to collect the dropdown value.
<form name="appLogin" action="j_security_check" method="POST">
<table width="100%">
<tr>
<td align="center">
<table>
<tr>
<td>Username: </td>
<td><input id="userName" name="j_username" value=""/></td>
</tr>
<tr>
<td>Password: </td>
<td><input name="j_password" type="password" value="" /></td>
</tr>
<tr>
<td>Visual: </td>
<td><Select name="visuals" id="visuals"/>
<option value="S1">S1</option>
<option value="S2">S2</option>
<option value="S3">S3</option>
<option value="S4">S4</option>
</Select>
</td>
</tr>
</table>
<table>
<tr>
<td>
<button type="submit" name="submit" value="Sign In">Sign In</button>
<input type="submit"/>
</td>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</form>
Controller Code:
#RequestMapping( value = " /controller1.html", method = RequestMethod.GET )
public String setupForm( #RequestParam(value = "visuals", required=false) String visuals,
ModelMap model )
{
List<String> studentNames = new ArrayList<String>();
List<String> teacherNames = new ArrayList<String>();
model.addAttribute("someData", teacherNames);
model.addAttribute("anotherData", studentNames);
model.addAttribute("visuals", visuals);
log.info("Role from Dropdown: " + visuals);
return "school/classTen";
}
You need to create yyour own Filter by extending AbstractAuthenticationProcessingFilter
I don't have the entire code in front of my eyes, but the following article could help you:
http://mark.koli.ch/2010/07/spring-3-and-spring-security-setting-your-own-custom-j-spring-security-check-filter-processes-url.html
I have a form which contains fields and file upload elements while submitting the form it is throwing a null pointer exception, when i logged the form object all fields are getting null and when i am removing the form enctype="multipart/form-data"1 then i get all fields but the file object is getting null.
Form Code :
<form:form method="post" id="form" name="frm" action="${action}" enctype="multipart/form-data">
<table>
<tr>
<td><form:label path="productName">Product Name: </form:label></td>
<td>
<form:input path="productName"/>
</td>
</tr>
<tr>
<td><form:label path="rfile">Receipt File</form:label></td>
<td><form:input path="rfile" id="receiptFile" type="file" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Upload Receipt" /></td>
</tr>
</table>
</form:form>
COntroller Code:
#RequestMapping(value="/test.do", method = RequestMethod.POST)
public ModelAndView testReceipt(#ModelAttribute("frm") ReceiptForm form, BindingResult result, HttpServletRequest request){
System.out.println("---"+form.getProductName());
System.out.println("---"+form.getRfile());
}
Please note file is a type of: CommonsMultipartFile
Use FileUpload library to parse the request from the client.