Send file to MVC Controller - ajax

I have refer the below link to upload the file but I keep getting
https://www.baeldung.com/spring-file-upload
This I have in my Thymeleaf file:
<div>
<form method="POST" action="esubmission/submitter/uploadFile" enctype="multipart/form-data" onclick="disableOnBeforeUnload()" >
<table>
<tr>
<td><label path="file">Select a file to upload</label></td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
</div>
This is my javascript function
function disableOnBeforeUnload() {
window.removeEventListener("beforeunload", windowClosedOrReloaded);
}
This is my controller:
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String submit(#RequestParam("file") MultipartFile file, ModelMap modelMap) {
modelMap.addAttribute("file", file);
return "fileUploadView";
}
As you can see I have the call to function in controller but I am getting 404 error
2020-09-07 16:19:05.332 DEBUG 81932 --- [nio-8080-exec-3] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
[2020-09-07 16:19:05,332] DEBUG o.s.w.s.r.ResourceHttpRequestHandler - Resource not found
2020-09-07 16:19:05.332 DEBUG 81932 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
What I am missing??
I also tried using ajax call like below:
function uploadDocument(){
$.ajax({
type: "POST",
contentType: "application/json",
url: "/appName/role/uploadFile/",
timeout: 100000,
success: function (result) {
console.log("SUCCESS");
},
error: function (e) {
console.log("ERROR: ", e);
},
done: function (e) {
console.log("DONE");
}
});
}

Verify that your path url /appName/role/uploadFile/ is correct
Because server returning 404 that means path is not correct.
If you are using this script on that same page no need to put /appname/role/
you can simply pass that method name as you are on same controller.

Related

Spring Thymealef Ajax update fragmenet

I'm using spring boot MVC, and have a part that I make an ajax request to update a collection of products for merchandise shipment, but when I post it is displaying json on the screen instead of updating the fragment:
<th:block th:if="${expedicao.tipoRegistro eq 'A' or expedicao.tipoRegistro eq 'X'}">
<form action="#" th:action="#{/expedicao/buscaprod}" method="post"
name="formBusca">
<input type="hidden" th:name="${_csrf.parameterName}"
th:value="${_csrf.token}" /> <label th:text="Ean13">Ean13</label>
<input type="radio" name="tipoCod" id="tipoCod" value="ean13" /> <label
th:text="Dun14">Dun14</label> <input type="radio" name="tipoCod"
id="tipoCod" value="dun14" /> <input type="text"
name="FieldCodigo" class="form-control" placeholder="Codigo Barras"
id="FieldCodigo" value="" autofocus="autofocus" required="required" />
<input type="hidden" name="id_expedicao" id="id_expedicao"
th:value="${expedicao.id}" />
<button type="submit" value="Buscar">Buscar</button>
</form>
</th:block>
<div th:fragment="info-success" xmlns:th="http://www.thymeleaf.org" th:remove="tag">
<div class="modal-body row" id="coleta">
<div th:replace="expedicao/coleta::coleta"></div>
</div>
</div>
</div>
this is my ajax
<th:block layout:fragment="scripts">
<script th:inline="javascript">
/*<![CDATA[*/
$(function() {
$.ajaxSetup({
headers : {
'X-CSRF-Token' : $('meta[name=_token]').attr('content')
}
});
$('form#formBusca').submit(
function(e) {
e.preventDefault();
$.ajax({
type : "POST",
contentType : "application/json",
url : 'expedicao/buscaprod',
data : $('form#formBusca').serialize(),
dataType : 'json',
success : function(result) {
if(result.status == "Done"){
carregarColeta(result.data.id);
if (result.data.situacao == 'B'
|| result.data.situacao == 'C') {
$('form#formBusca').remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error:" + textStatus + ' : '
+ errorThrown);
}
});
$('input[name=FieldCodigo]').val('');
});
});
function carregarColeta(idexpedicao) {
$.ajax({
method : 'POST',
url : 'expedicao/detalhe',
data : {
'id_expedicao' : idexpedicao
},
success : function(retorno) {
$('#coleta').empty().html(retorno);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error:" + textStatus + ' : '
+ errorThrown);
}
});
}
when a execute the post method it go to my controller execute the logic and return the json of the object updated, and instead of update the fragment calling the JS function carregaExpedicao.. its dislpay the json on the screen, and change the url
this is my controller
#Controller
public class ExpedicaoController {
#RequestMapping(value = "/expedicao/buscaprod", method = RequestMethod.POST)
#ResponseBody
public Response updateProdutoColetado(
#RequestParam(name = "id_expedicao") String id_expedicao,
#RequestParam(name = "FieldCodigo") String FieldCodigo,
Model model, HttpSession session) {
//Minhas regras
model.addAttribute("expedicao", expedAndamento);
return new Response("Done", expedAndamento);
}
#RequestMapping(value = "/expedicao/detalhe")
public String detalhe(#RequestParam(name = "id_expedicao") String id_expedicao, Model model, HttpSession session) {
model.addAttribute("expedicao", expedAndamento);
return "expedicao/coleta";
}
}
Fixed:
error 1 => id on the form
error 2 => missing csrf param on ajax

Fetching name based on id in ajax

In the console,I am getting name based on id.How to bind that name into the html page.
Here is my code..
function getEventname(){
var clid=$('#eventid').val();
console.log("i am ok" + clid);
$.ajax({
type: "GET",
url: "EduManage.jsp",
data: {
control:'ajax',
ch:'1',
key:'1_0a1m_1',
eventid:clid
},
success: function(data) {
console.log("i am ok" + data);
(what to do to bind the name in the html page)
}
});
}
Now the HTML is;
<td class="bg1">
Event Id :
</td>
<td class="bg1" width="25%">
<input name="eventid" type="text" id="eventid" size="10" maxlength="10" onblur="getEventname()"/>
</td>
<td class="bg1" width="40%">
Event Name :
</td>
<td class="bg1" width="25%">
<input type="text" name="eventname" id="eventname">
</td>
In the console,I am getting name as i am ok seminar .How to bind that name in the HTML page automatically when id is given.
Can anyone help?
So your Javascript function should be;
function getEventname(){
var clid=$('#eventid').val();
console.log("i am ok"+clid);
$.ajax({
type: "GET",
url: "EduManage.jsp",
data: {
control:'ajax',
ch:'1',
key:'1_0a1m_1',
eventid:clid
},
success: function(data) {
console.log("i am ok"+data);
//The one line change
$("#eventname").val(data);
}
});
}
So you had already implemented everything. All you need to do is add data in some element. If you want to add it in td then use this:
$.ajax({type: "GET",url: "EduManage.jsp",data: {control:'ajax', ch:'1', key:'1_0a1m_1', eventid:clid},
success: function(data) {
console.log("i am ok"+data);
$("td.last").append(data);
(what to do to bind the name in the hmtl page)
}
});
and add a new html tag:
<td class="last"></td>
You can also update the html using jquery but its not a practice to do so.
Hope this works.

Internal Server Error on ajax GET request in Spring MVC

Hi everyone i'm new to spring MVC so i have little idea about the framework. All I'm trying to do is refresh a div in my view with items filtered by a hibernate query, which prints correctly to standard out.
For some reason I'm not aware of I get a 500; Internal server error when i try a get request via ajax.
I changed the return type in the controller, my original idea was to use the default index controller with an optional parameter.
View:
<div id="itemListContainer">
<c:if test="${!empty items}">
<c:forEach items="${items}" var="item">
<c:url value="/showImage.htm" var="url">
<c:param name="id" value="${item.id}" />
</c:url>
<div id="${item.id}" class="col-lg-2 col-md-3 col-xs-6 thumb">
<img class="img-responsive" src="${url}" alt="${item.name}">
</div>
<input id="name_${item.id}" type="hidden" value="${item.name}">
<input id="name_${item.id}" type="hidden" value="${item.review}">
</c:forEach>
</c:if>
<c:if test="${!empty itemList}">
<h1>Nothing found</h1>
</c:if>
</div>
JS File
function filterItems(value) {
$("#itemListContainer").empty();
$.ajax({
method: "GET",
//dataType: "json",
url: "filterItems.htm",
data: {
type: value
},
success: function (data) {
if (data) {
$("#itemListContainer").html(data);
} else {
console.log(xhr.responseText);
alert("failure");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
Controller:
#RequestMapping(value = "/filterItems", method = RequestMethod.GET)
public #ResponseBody List<Item> filterItems(#RequestParam(value = "type", required = false) String type) {
List<Item> items = new ArrayList<Item>();
try {
items = itemDao.getItems(type);
} catch (Exception e) {
e.printStackTrace();
}
return items;
}
Any help will be greatly appreciated. Thanks in advance!!
Once again, when it comes my little experience with hibernate, the error has nothing to do with Javascript, controller o DAO but with entity mapping.
My Item entity had an association with a User entity, and had to specify between lazy and eager loading of the association. In my case it was solved by adding lazy="true" to my xml file.

BadRequest Error in ajax with Spring MVC

I am trying post a request to my controller and everytime when I hit submit button it gives an error of bad request.
I am not able to find out what is wrong with the code.
Home.jsp
<div id="setReminder">
<label class="generalReminder" style="text-decoration: none;">General
Reminder</label>
<table>
<tr>
<td>Date</td>
<td><input type="text" readonly="readonly"
id="birthdayDate"></td>
</tr>
<tr>
<td>Time</td>
<td><input type="text" readonly="readonly" id="callTime"
></td>
</tr>
<tr>
<td>Message</td>
<td><textarea id="reminderTag" rows="5"></textarea></td>
</tr>
</table>
</div>
<div id="reminderDot" style="margin-top: 24%; position: relative;">
<button class="submitReminder" onclick="saveReminderDetails();">Submit</button>
</div>
Home.js
function saveReminderDetails(){
var x="";
x=scheduleBirthdayReminder();
if(x){
$.ajax({
type:"POST",
url:"submitBirthdayRequest.do",
data : {
birthdayDate :$("#birthdayDate").val(),
birthdayTime : $("#callTime").val(),
birthdayReminder : $("#reminderTag").val()
},
success : function(data) {
alert('data is'+data);
$("#birthdayDate").val('');
$("#callTime").val('');
$("#reminderTag").val('');
}
});
}
}
Controller.java
#RequestMapping(value="submitBirthdayRequest.do",method=RequestMethod.POST)
public #ResponseBody String submitSchedulerDetails(#RequestParam("birthdayDate")String birthdayDate,#RequestParam("callTime")String birthdayTime,#RequestParam("reminderTag")String reminderTag,HttpServletRequest request ){
System.out.println("adding reminder details with birthdayDate "+birthdayDate+"and time"+birthdayTime);
String userIdentity=((UserDetails)request.getSession(false).getAttribute("loginDetails")).getName();
try{
boolean schedulerObj= schedulerService.addSchedulerBirthdayDetails(userIdentity,birthdayDate, birthdayTime,reminderTag);
}catch(Exception e){
e.printStackTrace();
}
return birthdayTime;
}
Error
http://localhost:8083/Testing/submitBirthdayRequest.do 400 (Bad Request)
the names of the parameters in the request don't match the expected. Try changing the
#RequestParam("birthdayTime") String birthdayTime
#RequestParam("birthdayReminder") String reminderTag
or change the param names on the client side

Ajax return form modelattribute

I have the following situation. In controller in method viewUserReminders I pass remindersListWrapper to my uReminder.jsp page.
#RequestMapping(value = "/user/reminders", method = RequestMethod.GET)
public ModelAndView viewUserReminders(Model model, #ModelAttribute("id_users") Long id_users) throws Exception {
ModelAndView mv = new ModelAndView();
mv.setViewName("user/uReminders");
List<Reminders> remindersList=userService.getUserReminders(id_users);
RemindersListWrapper remindersListWrapper=new RemindersListWrapper();
remindersListWrapper.setRemindersList(remindersList);
mv.addObject("remindersListWrapper", remindersListWrapper);
return mv;
}
In my uReminders.jsp file I have a form with modelattribute remindersListWrapper. This jsp page displays table of reminders. Next to every reminder there is a checkbox. The user can check several checkboxes, click button("Mark as read") and using Ajax I submit form and go to controller method
readReminders().
uReminders.jsp
<form:form action="/user/ajax/reminders/readReminders" method="POST" modelAttribute="remindersListWrapper" id="remindersForm">
<div id="main">
<table class="table">
<thead>
<tr>
<th></th>
<th></th>
<th>Reminder</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<c:forEach items="${remindersListWrapper.remindersList}" varStatus="status" var="reminders">
<tr id="row">
<td><form:hidden path="remindersList[${status.index}].idCalendar"/></td>
<td><form:checkbox path="remindersList[${status.index}].isRead"/></td>
<td><form:input path="remindersList[${status.index}].endDate"/></td>
</tr>
</c:forEach>
</c:when>
<c:when test="${empty remindersListWrapper.remindersList}">
<tr>
<td colspan="3">You have no reminders.</td>
</tr>
</c:when>
</c:choose>
</tbody>
</table>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<input type="button" id="reminders" value="Mark as read"/>
</c:when>
</c:choose>
</div>
</form:form>
$(window).load(function () {
$("#reminders").click(function () {
sendAjax('readReminders', $("#remindersForm").serialize());
});
});
In this method I save read reminders and I build newRemindersListWrapper with the new list of reminders(I want to delete checked reminders and display only unchecked). My first question is: How to return to the page newRemindersListWrapper itself.
#RequestMapping(value = "/user/ajax/reminders/readReminders", method = RequestMethod.POST)
#ResponseBody
public String readReminders(#ModelAttribute("remindersListWrapper") RemindersListWrapper remindersListWrapper, #ModelAttribute("id_users") Long id_users) throws Exception {
for(Reminders reminders:remindersListWrapper.getRemindersList()){
if(reminders.getIsRead()){
userDao.saveReadReminders(reminders);
}
}
RemindersListWrapper newRemindersListWrapper=new RemindersListWrapper();
///////////////////
here I want to return the newRemindersListWrapper itself
//////////////////
}
And my second question is: How I can set newRemindersListWrapper as modelattribute in my form.
function sendAjax(ref, data) {
console.log(data);
$.ajax({
url: 'ajax/reminders/' + ref,
type: 'POST',
data: data,
success: function (response) {
////////////////////////////////
I want to get newRemindersListWrapper and set it as modelattribute in form.
////////////////////////////////
console.log("success");
},
error: function (request, status, error) {
console.log('error ' + ref + ' text=' + request.responseText + ' status = ' + status + ' error = ' + error);
}
});
}
Question 1: just change the return type to RemindersListWrapper and return it
Question 2: Since you are using ajax, you can't. You need to use javascript to parse the returned list and update the page as needed.

Resources