I have an ajax call:
what happens is that I click on an Image that clicks on "input file" that I don't want it to be shown. when the input val() is changed method uploadListener() is invoked which is basically an ajax method that get the file to the server "upload it to server"
code goes like this:
html:
<img id="${assayAssessRequest.id}" src="[#spring.url '/images/buttons/upload.jpg'/]" onclick="uploadFile(this);" title="Upload File" />
<form id="uploadForm" action="[#spring.url '/assay/designability/uploadFile.htm'/]" method="POST" enctype="multipart/form-data">
<div style="display: none;">
[#spring.formInput path="multiPartBean.file" fieldType="file" attributes="title='path' class='upload' accept='.txt,.csv,.zip'" /]
[#spring.formHiddenInput path="multiPartBean.fileName" attributes=" onchange='uploadListener();'class='uploadFileName'" /]
[#spring.bind "multiPartBean"/]
</div>
<input type="submit" id="uploadButton" value="upload" />
</form>
javaScript:
function uploadFile(){
document.getElementById('inputFile').click();
}
function uploadListener(){
$('#uploadForm').attr("action","[#spring.url '/assay/designability/uploadFile.htm'/]");
alert($('#uploadForm').attr('action'));
this.document.getElementById("uploadForm").submit = true;
alert("After Submit");
return false;
}
server controller:
#Controller
#PreAuthorize("isAuthenticated()")
#RequestMapping("/assay/designability")
#SessionAttributes({"assayAssessmentsInitializersBean","assayAssessmentsRequestsDetailsBean"})
public class AssayDesignabilityController extends AssayBaseController {
#RequestMapping(value = "/uploadFile",method= RequestMethod.GET)
public String uploadFile(#RequestParam(value = "file")Object file){
MultipartFile multipartFile=(MultipartFile)file;
logger.info(multipartFile.getName());
return multipartFile.getName();
}
}
now when I do all that, the response give me nonsense and when I try to debug I never get to the controller method. any help??
EDIT:
now I try to submit it I've updated code and I have the same behavior no response.
I've solved my problem by avoiding ajax call and re implement my code thanks to #Ian.
here is the code:
Html plus Freemarker
<form id="uploadForm" action="#" method="POST" enctype="multipart/form-data">
<div class="instruction popup_inst">
<span class="popup_logo">[#spring.message "pandaLogo"/]</span>
<div class="float_right">
<input type="button" id="cancelBtn" class="btn" onclick="refreshParentTable();closePopup();" value="[#spring.message "cancelButton"/]" />
<input class="btn" type="submit" id="submit" onclick="validateFileInput();" value="[#spring.message "uploadButton"/]" />
</div>
</div>
<span class="popup_title">[#spring.message "uploadFile"/]</span>
<div class="popup_container">
[#spring.bind "assayAssessmentsRequestBean"/]
[#spring.formInput path="assayAssessmentsRequestBean.designabilityFile.file" fieldType="file" attributes="title='path' class='upload' accept='.txt,.csv,.zip'" /]
[#spring.formHiddenInput path="assayAssessmentsRequestBean.designabilityFile.fileName" attributes="class='uploadFileName'" /]
[#spring.formHiddenInput path="assayAssessmentsRequestBean.dateOfAssessment" attributes="" /]
[#spring.formHiddenInput path="assayAssessmentsRequestBean.id" attributes="" /]
</div>
<input id="uploadfile" type="hidden" value="${uploadfile}"/>
</form>
controller:
#RequestMapping(value = "/uploadFile",method= RequestMethod.POST)
public ModelAndView uploadFile(#ModelAttribute(value = "assayAssessmentsRequestBean")AssayAssessmentsRequestBean assayAssessmentsRequestBean,HttpSession session) throws PanDaApplicationException {
//mycode
}
from this experience I would advice evreyone to avoid sending files via ajax calls for me
I used a popup window to create form and submit upload operation.
Thanks for everyone tried to help
If i see correctly, the submit action points to "uploadfile.HTM"
$('#uploadForm').attr("action","[#spring.url '/assay/designability/uploadFile.htm'/]");
but the method in your controller is mapped only to uploadFile (without .htm)
#RequestMapping(value = "/uploadFile",method= RequestMethod.GET)
Maybe you have another configuration on your web.xml / servlet-spring.xml that makes this possible, but otherwise, this could be the problem.
Hope this helps
Regards
Related
Below is code from a controller that I'm aiming to make sure it's receiving two input parameters (name and code) from a front-end interface.
It's a page that takes two parameters within a submit form, "name" and "code".
#RequestMapping(method = RequestMethod.POST)
public String transfer(#RequestParam(name = "name") String name,
#RequestParam(name = "code") String code,
Errors errors, RedirectAttributes redirectAttributes) {
try {
User userToBeTransferred = usersRepository.findByName(name);
userToBeTransferred.setTransferred(true);
Region regionOfTransference = regionsRepository.findByCode(code);
regionOfTransference.setPopulationNumber(regionOfTransference.getPopulationNumber() + 1);
userToBeTransferred.setRegion(regionOfTransference);
usersRepository.save(userToBeTransferred);
regionsRepository.save(regionOfTransference);
return "redirect:/section/users/new";
} catch (IllegalArgumentException e) {
return "htmlPageOne";
}
}
The front-page form :
<form class="form-horizontal" method="POST" action="/section/users/new" th:object="${user}">
<input type="hidden" th:field="*{id}"/>
<div class="form-group row">
<label for="name" class="col-form-label">User name</label>
<input type="text" class="form-control" id="name" th:field="*{name}" name="name"/></div>
<div class="form-group row">
<label for="code" class="col-form-label">Code</label>
<input type="text" class="form-control" id="code" th:field="*{region.code}" name="code"/></div>
<button type="submit" class="btn btn-primary col-sm-6 ">Save</button>
</form>
For some reason, I'm getting the following error after I click to submit the form :
There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'code' is not present
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'code' is not present
I'm not sure if I'm using the requestparams correctly, so maybe it's got something to do with this? I don't know, I've been stuck on this for a few hours now, so would appreciate if someone could help me.
The problem is that th:field="*{region.code}" overrides your name attribute into name="region.code". You can tell by inspecting the rendered <input> element using dev tools of your browser.
You can change following
th:field="*{region.code}"
...into:
th:value="${user.region.code}"
Hi guys hope you can help me, because i cant get further at the moment
I have my Controller.
#RequestMapping(value="/kundenseite", method= RequestMethod.GET)
public String kundenLogin(ModelMap model) {
if(kundeComponent.getKunde() != null) {
List<Restaurant> restaurants = restaurantService.alleRestaurants();
model.addAttribute("restaurants", restaurants);
return "kundenseite";
}else {
return "redirect:/kunde/login";
}
}
#RequestMapping(value="/kundenseite", method= RequestMethod.POST)
public String kundenLoginAnswer(ModelMap model, #ModelAttribute Restaurant restaurant) {
System.out.println(restaurant.toString());
return "kundenseite";
And my jsp file
<%# include file="common/header.jspf" %>
<div class="jumbotron text-center">
<h1>MiMiMi Lieferservice</h1>
<p>Der schnellste Lieferservice von Passpick</p>
</div>
<div style="margin-right:auto; margin-left:auto; width: 33%">
<h2 style="text-align: center">Restaurant wählen</h2>
<div class="well">
<c:forEach items="${restaurants}" var="restaurant">
<form:form modelAttribute="${restaurant}" method="post">
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.name}</div>
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.restaurantTyp}</div>
<button type="submit">Bestellen</button>
</form:form>
<br style="clear:both;" />
</c:forEach>
</div>
</div>
</body>
</html>
If the user presses a button i want to return a restaurant.
But i don't know how to make that happen, my thought was to use a form but i cant get it to send a complete restaurant object back
If there is no solution for this i have to write the id with the button.
You need input hidden inside the form tab as below input hidden:
<input type="hidden" name="name" value="${restaurant.name}">
<input type="hidden" name="restaurantTyp" value="${restaurant.restaurantTyp}">
I am trying to upload the file, it is working on my local system, but not working in the server.
<form class="form-group row" style="height:100px;" id="uploading" method="post" enctype="multipart/form-data">
<div class="col-md-10" align="center">
<div class="form-group row" align="center">
<label class="col-md-2 form-control-label"> File to upload:</label>
<div class="col-md-10" >
<div class="input-group">
<input type="file" class="filestyle" data-buttonName="btn-primary" name="upload" id="upload" accept="*"/>
</div>
</div>
</div>
<div class="form-group row" id="buttonzone">
<div class="col-sm-14">
<div class="input-group">
<button type="submit" class="btn btn-success" id="upload" style="margin-left: 96px;">
<i class="fa fa-cloud-upload"></i> Upload</button>
<button type="button" class="btn btn-danger" id="cancel" ><i class="fa fa-ban"></i> Cancel</button>
</div>
</div>
</div>
</div>
</form>
$("form#uploading").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url : '/uploadController/upload',
type: 'POST',
data: formData,
async: false,
beforeSend: beforeSendHandler,
success: function (data){
var msg=data.msg;
var obj=data.obj;
if(data.success == true){
$('#successmsg').html(msg);
$('.alert-success').show();
$('.alert-danger').hide();
setTimeout(function(){
$(".alert-success").alert('close');
}, 10000);
}else{
$('#errmsg').html(msg);
$('.alert-danger').show();
$('.alert-success').hide();
setTimeout(function(){
$(".alert-danger").alert('close');
}, 10000);
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Java code:
#RequestMapping(value = "/uploadController/upload",headers=("content-type=multipart/*"), method = RequestMethod.POST)
public #ResponseBody StatusResponse totxnsUpload(#RequestParam("upload") MultipartFile upload, HttpServletRequest request, HttpServletResponse response) throws IOException, NoSuchFieldException, SecurityException{
logger.debug(" file upload controller");
//my logic here
}
I am getting this in browser console:
{
"timestamp":1495781126083,
"status":400,
"error":"Bad Request",
"exception":"org.springframework.web.bind.MissingServletRequestParameterException",
"message":"Required MultipartFile parameter 'upload' is not present",
"path":"/uploadController/upload"
}
But it is working on out of server, I don't what is the problem.
the parameter "upload" as seen in #RequestParam("upload") MultipartFile upload
is a required parameter. If it is working in some systems it means that it is getting a parameter named "upload". In your case it fails because it is not present in the request.
You do have an input named upload in your form though. But I can see you are trying to send form data using ajax. Can you see the request in browser dev tools network tab?
Also place a breakpoint in your totxnsUpload method and see if you are getting two form submit requests (one standard and one with ajax)
for debugging purposes you can set upload parameter to optional in your Java code with this replacement #RequestParam(value = "upload", required = false) MultipartFile upload
With that being said. If the exact same code is working on your machine but not working on the server, you might need to configure your context. Take a look at this How to use HttpServletRequest#getParts() in a servlet filter running on Tomcat?
I have a problem in my form action in Spring MVC.
My code:
<form method="POST" action="j_acegi_security_check" name="frmLogin">
<input type='hidden' autocomplete="off" name='_schema' id="_schema"/>
<input type='hidden' id='j_username' name='j_username' autocomplete="off" />
<input type='hidden' id='j_password' name='j_password' autocomplete="off" />
</form>
I can't understand what kind of action is j_acegi_security_check perfoming.
For Form Action, you need to land your request to the controller you created for. Specify your request name for example
This is HTML part <form:form method = "POST"action="/addUser">...</form:form>
For your controller class
#Controller
public class UserController {
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")User user,
ModelMap model) {
}
Your request will be landed to this controller where you can perform any desired action.
Hope this will help.
Hello I'm tryin to developpe a page that can delete users but when I click on submit I have an error Etat HTTP 400 - La requête envoyée par le client était syntaxiquement incorrecte.
Jsp file
</div>
<form method="POST" action="Users">
User ID
<input type="text" name="idUser" /><br><br>
<input type="submit" name="Supprimer" value="Supprimer"/>
</form>
Controller
#RequestMapping(value = "/Users")
public String goUsers(Model model)
{
model.addAttribute("AllUsers", UserS.getAllUsers());
return "Users";
}
#RequestMapping(value = "/Users", method = RequestMethod.POST)
public String goUsers(#ModelAttribute User user,BindingResult result,#RequestParam int id, Map<String, Object> model)
{
UserS.deleteUser(id);
return "Users";
}
thank you
Your controller wrong. You expect oen User and one param with name id but you send one param with name idUser.
Eliminate ModelAttribute and force de name of RequestParam:
#RequestMapping(value = "/Users", method = RequestMethod.POST)
public String goUsers(BindingResult result,#RequestParam(name="idUser") int id, Map<String, Object> model)
{
UserS.deleteUser(id);
return "Users";
}
1.first you need to add modelattribute to your form like this :
Notice how i am using spring forms. You can use them by adding
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
before DOCTYPE html>
Then you need to add hidden path to attribute "id" so when you controller gets the request you will know which user you will need to delete or edit.
This is example form :
`<form:form method="POST" modelAttribute="User" action="Users">
<form:hidden path="id"/>
<div class="form-group">
<label for="usernameId">Username</label>
<form:input path="username" id="usernameId" class="form-control" />
<form:errors path="username" style="color:red;"></form:errors>
</div>
<div class="form-group">
<label for="fullNameId">Full Name</label>
<form:input path="firstLastName" id="firstLastName" class="form-control"/>
<form:errors path="firstLastName" style="color:red;"></form:errors>
</div>
<div class="form-group">
<label for="passwordId">Password</label>
<form:password path="password" id="passwordId" class="form-control"/>
<form:errors path="password" style="color:red;"></form:errors>
</div>
<div class="form-group">
<label for="emailId">Email</label>
<form:input path="email" id="emailId" class="form-control"/>
<form:errors path="email" style="color:red;"></form:errors>
</div>
<input type="submit" class="btn btn-default" value="Register"/>
</form:form>`
finally you will add to your controller class.
#ModelAttribute("User")
public User getUser(){
return new User();
}
Then you will need to adjust your controller like this :
#RequestMapping(value="/Users", method=RequestMethod.POST)
public String deleteUser(User user){
getRegisterService().deleteUser(user.getId());
return "home";
}
Note : You will have to create class = User : with id attribute(and all others you need). You will also need to create a method for deleting user in your service and repository layer.
P.S. User user in your deleteUser method is actually the same user you created with #modelAttribute annotation.
If you have any additional questions feel free to ask!
I have given you almost exact form i use for register/editing or deleting Users. When you submit form, everything will be saved into object User with annotation #modelAttribute. Hidden id field is crucial here. When you have id, which is primary key you can just create method in repository (something like this)
public void deleteUser(UserJPA userJPA){
getEntityManager().remove(UserJPA);
}
Hope you find this post helpful.