RequestMapping with POST in Spring not working? - java

Hi I have the following ajax call in my client side.
var arr = JSON.stringify(JSON_Array);
$.ajax({
url: 'http://localhost:8080/',
type: 'POST',
data: arr,
dataType: 'text',
contentType: 'application/json',
success: function () {
console.log("Success!");
},
error: function() {
console.log("error");
},
});
Server side:
#Controller
public class Controller{
#RequestMapping("/")
public String start() {
System.out.println("works"); //prints
return "index";
}
#RequestMapping(value = "/", method = RequestMethod.POST, consumes = "text/plain")
public void process(#RequestBody String payload) throws Exception {
System.out.println("payload " + payload); //does not print
}
}
The ajax call is successfully sent off, however nothing is received in the server side. The process method is not being used. I am not too sure why. Help would be appreciated.
edit:
Changes made following #Toofy's comment
In Ajax call:
dataType: 'text',
contentType: "text/plain;",
process method kept the same.
I also tried changing the Ajax call to the following
dataType: 'json',
contentType: "application/json;",
and the server side changes:
#RequestMapping(value = "/", method = RequestMethod.POST, consumes = "application/json")
public void process(#RequestBody String payload) throws Exception {
System.out.println("payload " + payload);
}
in both these cases the ajax calls stop working

Got it to work by doing the following:
In Ajax call I got rid of dataType
$.ajax({
url: 'http://localhost:8080/',
type: 'POST',
data: arr,
contentType: "application/json; charset=utf-8",
});
In the server side I changed the process method to
#RequestMapping(value = "/", method = RequestMethod.POST)
#ResponseBody
public void process(#RequestBody String payload) throws Exception {
System.out.println(payload);
}

Related

Jsp File upload returns empty Input Stream for file upload

I am working on a jsp file upload using ajax call and I am able to hit the java controller in the HttpServletRequest I see the multipart file received but when I do request.getInputStream.readAllBytes(), I get an empty byte array
The ajax call in javascript
function saveFileUpload() {
var data = new FormData()
data.append("file", document.getElementById(fileName).files[0])
$.ajax({
type: 'POST',
data: data,
url: pageContext + "/upload",
processData: false,
contentType: false,
success: function(data) {},
error: function(e) {}
});
}
}
In Java controller
#RequestMapping(value = {"/upload"}, method = RequestMethod.POST)
public void fileUpload (
HttpServletRequest request, HttpServletResponse response){
byte[] arr = request.getInputStream().readAllBytes();
System.out.println(arr.length);
}
The above code prints arr.length as 0. Can someone tell me the reason for this issue?
I assume that you are using Springboot and your application supports multipart/form-data. After version 3.0 the Servlet API natively support it.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public void fileUpload(#RequestParam("file") MultipartFile file) throws IOException
{
if (!file.isEmpty())
{
byte[] bytes = file.getBytes();
// and so on
}
}
JQuery's Ajax:
function saveFileUpload() {
let data = new FormData()
data.append("file", document.getElementById(fileName).files[0])
$.ajax({
type: 'POST',
data: data,
url: pageContext + "/upload",
processData: false,
contentType: false,
success: function(data) {},
error: function(e) {}
});
}

return new ModelAndView doesnt work

My controller :
#RequestMapping(value="/testAdmin", method = RequestMethod.POST,consumes = "application/json")
public ModelAndView testAdmin(#RequestBody Student student) {
System.out.println(student.getName()+" "+student.getId()+" "+student.getLogin()+" "+student.getPassword());
return new ModelAndView("showString","student",student.getName());
}
My ajax function:
function test2(a,ob) {
var student={
id:ob[a].id,
login:ob[a].login,
password:ob[a].password,
name:ob[a].name
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
url: "testAdmin",
data: JSON.stringify(student),
success: function (response)
{
alert("success");
},
error : function(xhr, status, errorThrown) {
alert(status+" "+errorThrown.toString());
}
});
}
Controller method works, but it doesnt go to other page.
I dont know how to fix it, give an example or information to read

how can I send and retrieve params in spring?

I am triyng to do a simple thing, with ajax, send a request (using a GET, or POST).
I will be sending 2 parameters in a json format , and I just want to get them back and send a response, still, I always get an error 400 and others that I dont know whats wrong, any idea how?
I started based on this article: http://fruzenshtein.com/spring-mvc-ajax-jquery/
I am using spring mvc.
So far I have this:
$(".update_agent").live('click', function(){
var agent = { "agentId" : agentID, "hostAGent" : hostID};
//send ajax
$.ajax({
url: url,
data: JSON.stringify(agent),
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
})
and at my java controller I have this
#RequestMapping(value = "/update", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public int updateAgent(HttpServletRequest req, HttpServletResponse res) throws IOException{
req.getParameterValues("agentId");
return AGENT_UPDATE_SUCCESS;
}
But I cant get it back, have no idea how to make the request of the params, any idea?
Thanks.
=====================UPDATE============================
Ive changed the code and this how it looks like...
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: 'POST',
url: url,
data: JSON.stringify(agent),
dataType: 'json',
success:function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
And at my controller
#RequestMapping(value = "/update", method = RequestMethod.POST)
public #ResponseBody Integer updateAgent(#RequestBody String param) throws IOException{
System.out.println(param);
//do something...
return 1;
}
the problem is that I am getting an error 415, unsupported media type, any advice?
GET-request can not have 'data'-field. You need to send your data as part of the url:
$.ajax({
url: url + "?agent=" + JSON.stringify(agent),
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
now you can get the data in your controller as:
#ResponseBody public ResponseEntity<String> updateAgent(#RequestParam(value = "agent") String agentJson){
...
}
or you can send a POST-request. With a POST-request you can send your data as requestBody:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestBody String agentJson){
...
}
EDIT:
create a new Agent-class:
public class Agent {
private long agentId;
private long hostAgent;
...
getter and setter
...
}
now update the controller to:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestBody Agent agent){
System.out.println(agent.getAgentId());
}
and change the "Content-Type" of ajax-call to "application/json".
EDIT2:
change your ajax-call data to:
data: { agentId: agentID, hostAgent : hostAgentID} ,
or even
data: agent ,
Don't forget to change "hostAGent" to "hostAgent" in your agent object, or you will get 400!!!
now ajax will send the data as request parameters, you can get the data in your controller by:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestParam(value = "agentId") long agentId, #RequestParam(value = "hostAgent") long hostAgentId){
System.out.println(agentId);
}

I got 404 error after sending POST method from ajax (#ResponseStatus & ResponseEntity)

I ma using Spring MVC and trying to use jQuery. I have this on my web page:
$(document).ready(function () {
var entity = {mag: "status_key", paper: "View10"};
$("#btn").click(function () {
$.ajax({
url: "ajaxJsonPost",
type: 'post',
dataType: 'json',
data: JSON.stringify(entity),
contentType: 'application/json',
});
});
});
Spring server has this:
#RequestMapping(value = "ajaxJsonPost", method = RequestMethod.POST)
public void postJson(#RequestBody Entity en) throws IOException {
System.out.println("writing entity: " + en.toString());
}
OK, Entity cames to server. BUT browser console prints 404 not found. I know that my POST request needs any response. In the Internet I've found solution which recommends me to return ResponseEntity object, OR use annotation #ResponseStatus. They both return HttpStatus well, but I don't know in which cases I should use them. What is the best way?
#Controller
#RequestMapping("/apipath")
public class SomeController {
#RequestMapping(value = "/ajaxJsonPost", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String postJson(#RequestBody final Entity en) {
System.out.println(en.toString());
//assuming you have a class "EntityService" and
//it has a method postData
//which takes Entity object as parameter and pushes into database.
EntityService.postData(en);
System.out.println("added");
return "success";
}
}
Entity object on the Server side
#JsonAutoDetect
public class Entity {
private String mag;
private String paper;
public String getMag() {
return mag;
}
public void setMag(final String mag) {
this.mag = mag;
}
public String getPaper() {
return paper;
}
public void setPaper(final String paper)
this.paper = paper;
}
}
ajax
$(document).ready(function () {
var entity = {mag: "status_key", paper: "View10"};
$("#btn").click(function () {
$.ajax({
url: "/apipath/ajaxJsonPost",
type: 'post',
dataType: 'json',
data: JSON.stringify(entity),
contentType: 'application/json',
success : function(response) {
alert(response);
},
error : function() {
alert('error');
}
});
});
});
And as far as why and when to use #ResponseStatus and #ResponseEntity, there is already a short and simple answer here by #Sotirios Delimanolis. When use #ResponseEntity .
It says :
ResponseEntity is meant to represent the entire HTTP response. You can
control anything that goes into it: status code, headers, and body.
#ResponseBody is a marker for the HTTP response body and
#ResponseStatus declares the status code of the HTTP response.
#ResponseStatus isn't very flexible. It marks the entire method so you
have to be sure that your handler method will always behave the same
way. And you still can't set the headers. You'd need the
HttpServletResponse or a HttpHeaders parameter.
Basically, ResponseEntity lets you do more.

JQuery, AJAX, POST request, parameters lost

My web application is basen on Spring MVC (4.0.5).
I'm trying to send a POST request through AJAX, using jQuery (v. 2.1.1):
function deleteItem(id) {
alert("Deleting " + id);
$.ajax({
url: "ajax/delete_item",
type: 'POST',
dataType: 'html',
data: {"id": id},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
var txt = data;
$('#message').html(txt);
},
error: function(data, status, err) {
$('#message').html(err);
}
});
}
The Controller's method is called successfully but there are no parameters in the request:
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST)
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String pname = en.nextElement();
System.out.println("//// " + pname); // just for test
}
String idStr = request.getParameter("id");
Integer id = Integer.parseInt(idStr);
//...
Why the request parameter is lost? Not just the value, the parameter itself is also lost.
What's wrong here?
If you are passing content type contentType: 'application/json' from ajax then add that settings in Spring method declaration as below: ( add produces = "application/json" in definition)
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST , produces = "application/json")
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
also there's one more caveat that,
You are mentioning both datatype and mimeType but it is not uniform.
mimeType: 'application/json' should be written with dataType: 'json' and not html.
I am not 100% sure what is wrong with your solution but I can give you an example that works for me
The AJAX request using Jquery :
// Do AJAX
$(function () {
$.post(mobileUrl + "/leave/requestLeave",
{ startDate: startDate, endDate: endDate, leaveTypeId: leaveTypeId,
notes: notes, isStartDayHalfDay: isStartDayHalfDay, isHalfDayEndDay: isHalfDayEndDay },
function (response) {
$('#feedbackTextArea').show();
}
);
});
And the controller method
#RequestMapping(value = "/requestLeave", method = RequestMethod.POST)
#ResponseBody
public String createOrUpdateNewForm(String startDate, String endDate, String leaveTypeText, String leaveTypeId,
String notes, String isStartDayHalfDay, String isHalfDayEndDay) {
startDate = new DateTime(startDate).toDate() etc
}
}
One thing to remember is that the parameter names in the ajax request should match the names of the variables in the controller method implementation
$("#drpop").change(function () {
var code = $(this).val();
$.ajax({
url: '/Ordering/OrderingTable',
type: 'post',
datatype: 'json',
data: { OperCode: code },
success:function(msg){
alert(msg);
} }); });
[HttpPost]
public ActionResult OrderingTable(string OperCode)
{
Orderingbll order = new Orderingbll();
var result = order.ListCategory(OperCode);//here you write your code
return Json(result,JsonRequestBehavior.AllowGet);
}

Categories