spring mvc post refuses json - json

I am using Spring-boot 1.1.7.RELEASE and trying to get my POST to work for my controllers. However, when I submit the html I get the exception:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:152)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:183)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:98)
I believe that Spring-Boot will pickup the HttpMediaType automatically and handle the json requests/reponse. Certainly all my GET's seem to be working.
Here is my Controller:
#Controller
#Transactional
#RequestMapping("/{officeName}/office")
public class OfficeController extends BaseController {
#RequestMapping( method = RequestMethod.GET)
#ResponseBody
public OfficeDTO get(#PathVariable String officeName) {
return officeDTOConverter.convert( officeService.findByURL( officeName ) );
}
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public OfficeDTO addOffice(#RequestBody Office office) {
return officeDTOConverter.convert( officeService.save( office ) );
}
}
And here is my post:
headers:
Content-Type application/json;charset=UTF-8
Accept application/json, text/javascript, */*; q=0.01
json:
{"address":{"addressTypeRefDto":{},"status":"ACTIVE","city":"Glenwood Springs","addressId":2,"seqId":null,"addressLine1":"123 Somewhere Lane","zip":"12345-789","addressLine2":"Suite 100","zipLong":"12345-789","addressLine3":"line 3","state":"CO","addressType":"OFFICE"},"contacts":[{"contactTypeRef":{"contactDescriptionShort":"Office Phone"},"contactId":1,"contactInfo":"555-555-1234","status":0},{"contactTypeRef":{"contactDescriptionShort":"Office Email"},"contactId":2,"contactInfo":"","status":0},{"contactTypeRef":{"contactDescriptionShort":"Office Fax"},"contactId":3,"contactInfo":"","status":0},{"contactTypeRef":{"contactDescriptionShort":"Office Emergency"},"contactId":4,"contactInfo":"","status":0}],"workDays":[{"dayOfWeek":"MONDAY","active":"true","startTime":"7:00","endTime":"7:00","breakStartTime":"7:00","breakEndTime":"7:00"},{"dayOfWeek":"TUESDAY","active":"true","startTime":"7:00","endTime":"7:00","breakStartTime":"7:00","breakEndTime":"7:00"},{"dayOfWeek":"WEDNESDAY","active":"true","startTime":"7:00","endTime":"7:00","breakStartTime":"7:00","breakEndTime":"7:00"},{"dayOfWeek":"THURSDAY","active":"true","startTime":"7:00","endTime":"7:00","breakStartTime":"7:00","breakEndTime":"7:00"},{"dayOfWeek":"FRIDAY","active":"true","startTime":"7:00","endTime":"7:00","breakStartTime":"7:00","breakEndTime":"7:00"},{"dayOfWeek":"SATURDAY","active":"true","startTime":"7:00","endTime":"7:00","breakStartTime":"7:00","breakEndTime":"7:00"},{"dayOfWeek":"SUNDAY","active":"true","startTime":"7:00","endTime":"7:00","breakStartTime":"7:00","breakEndTime":"7:00"}],"officeType":"GENERAL","officePhone":"555-555-1234","name":"Office Name","uRL":"test","status":"ACTIVE","servicePackageType":"BASIC","languageId":"English","ein":"123"}
and the response:
{"timestamp":1417717964314,"status":500,"error":"Internal Server Error","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'application/json;charset=UTF-8' not supported","path":"/mycompany/office"}
I am using the GET json to populate the html, and then taking those values to build a json string to submit via KendoUI:
transport : {
read : {
type : "POST",
beforeSend: function(req) {
req.setRequestHeader('Accept', "application/json");
},
url : function(options) {
return "/" + officeURL + "/office"
},
beforeSend: function(xhr){
xhr.setRequestHeader(header, token);
},
contentType : "application/json",
dataType : 'json'
},
parameterMap : function(data, type) {
if (type == "read") {
return createOfficeJSON();
}
}
If anyone sees any reason why the media type is being rejected, or if I have a mistake somewhere I would appreciate any help you can offer.

Related

Why instead of json-object answer I get a "404 not found" response?

Please help me. Why instead of json-object answer I get a "404 not found" response?
I am sending a following json-object to the server:
let dayEvent = { "dateEvent": "someEvent" };
$.ajax({
url: "/day",
type: 'post',
data: JSON.stringify(dayEvent),
contentType: 'application/json',
dataType: 'json'
}).done(function (data) {
console.log(data);
$("#response").text("Success: " + data);
}).fail(function (e) {
$("#response").text("Error: " + e); });
Further this controller processes the json-object:
#RestController
public class TaskExistController {
#RequestMapping(method=RequestMethod.POST, produces="application/json", value="/day")
public String dayEvent(#RequestBody TaskDataModel day) {
System.out.println(day.getDateEvent());
ObjectMapper objectMapper = new ObjectMapper();
String json = null;
try {
json = objectMapper.writeValueAsString(day.getDateEvent());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
}
TaskDataModel code:
public class TaskDataModel {
String dateEvent;
public void setDateEvent(String dateEvent) {
this.dateEvent = dateEvent;
}
public String getDateEvent() {
return dateEvent;
}
#Override
public String toString() {
return "TaskDataModel [dateEvent=" + dateEvent + "]";
}}
My assumption is that your Spring server application is running on http://localhost:8080.
Therefore, try:
url: "http://localhost:8080/day"
I also see that you use contentType application/json, and on serverside you declare:
produces="application/json" but not consumes="application/json"
However, this is not the reason of the 404, but something you could consider to add.
It's also good to know that instantiating an ObjectMapper is relatively expensive. So it is better to declare one on class level, instead of each time your endpoint is being called.
Add consumes to your end point to accept JSON
consumes = "application/json"
Isn't your REST url wrong?
Maybe change your server url to (http://localhost:8080):
$.ajax({
url: "http://localhost:8080/day",
type: 'post',
data: JSON.stringify(dayEvent),
contentType: 'application/json',
dataType: 'json'
})

405 Method not allowed using Resteasy and ajax

I am facing an issue while login . Registration is working fine.
Tech stack - HTML/AJAX/JQuery->Resteasy (Wildfly 10.1.0 Final)
I have the url - https://www.test.com/login.html - (actual URL name is modified)
When I am submitting the form with method type = "POST", it always throws, 405 Method not allowed.
Below is the section of the code:
submitHandler: function(form) { // fires only when form is valid
var loginData = formJSONLoginData();
$.ajax({
url:"https://"+getUrl()+"/curAuthService/curAuth/authenticateUser/v1",
type : "POST",
dataType : "json",
contentType: "application/json",
data: loginData,
success : function(response) {
},
error: function( xhr, status, error ){
}
});
return false;
},
And the Rest API is below:
#Path("/curAuth")
public class FHAuthResource {
#POST
#Path("/authenticateUser/v1")
#Produces("application/json")
#Consumes("application/json")
public String authenticateUser( AuthVO authVO ) {
}
}
It would be great help if someone can help/advice on where I am going wrong.
Registration is in similar format and it works fine.
Ultimate stupid mistake. Missed out "extends Application" for the Application file which is required for resteasy.

Spring MVC to send responsebody object to ajax post gives 406 error

There are similar links but I haven't found any solution to work for me, so I was wondering if someone could give me a working example for my scenario. I am doing an ajax get to retrieve data from the server side, so I can create charts dynamically on the client side. Do I need to include MappingJacksonHttpMessageConverter? If that's the answer can someone provide an example i can follow for that?
Java:
#RequestMapping(value="/getReportData.html", method=RequestMethod.GET, produces="application/json")
public #ResponseBody Reports getReport1Data(HttpServletRequest request)
{
System.out.println("Report 1 Page GET Method");
ModelAndView mv = new ModelAndView("report1");
if((Reports)request.getSession().getAttribute(USER_SESSION_REPORTS) != null){
reports = (Reports)request.getSession().getAttribute(USER_SESSION_REPORTS);
System.out.println("--------> Report 1 Page with session data");
return reports;
}
else{
System.out.println("--------> Report 1 Page with NO session data");
}
mv.addObject("report1", reports.getReport1());
return null;
}
Javascript:
function getData(){
$.ajax({
url: "getReportData.html",
type: "GET",
contentType: "application/json",
dataType: JSON,
success: function(report1){
console.log("success: " + report1.utilRatio.decRatio);
},
error: function(report1){
console.log("error: " + report1.utilRatio.decRatio);
}
});
}
Response Headers:
Content-Language: "en",
Content-Length: "1110"
Content-Type: "text/html;charset=utf-8"
Server: "Apache-Coyote/1.1"
Request Headers:
Accept: "/"
Accept-Language: "en-US,en;q=0.5"
Accept-Encoding: "gzip,deflate"
Content-Type: "application/json"
X-Requested-With: "XMLHttpRequest"
It looks like your request headers are wrong. You can remove the contentType setting since you are not sending data to the server and change dataType to the string value "json" instead of the variable JSON.
Also, your response headers are wrong. Just make sure you are always returning a Reports object. And you probably want to remove the html extension from that endpoint since you're just returning an object.
spring uses #ResponseBody annotaion for returning data as json .it will implicitly call the MappingJacksonHttpMessageConverter .so you need to use it.
#RequestMapping(value = "/getjson", method = RequestMethod.POST, produces = "application/json")
#Transactional
public void getJson(HttpServletRequest request, HttpServletResponse response, #RequestParam("type") String type)
throws DatatypeConfigurationException, IOException, JSONException {
JSONObject json = new JSONObject();
Map<String, String[]> parameterMap = request.getParameterMap();
List<Chart> chart=myService.getChart();
if (Chart.size()>0) {
json.put("status", "SUCCESS");
JSONArray array = new JSONArray();
for (Chart chartData: chart) {
JSONObject object = new JSONObject();
object.put("id", chartData.getRaasiId());
object.put("name", chartData.getName());
array.put(object);
}
json.put("options", array);
}
}
}
response.setContentType("application/json");
System.out.println("response======" + json.toString());
PrintWriter out = response.getWriter();
out.write(json.toString());
}
============
on the html
jQuery
.ajax({
url : controllerUrl,
dataType : 'text',
processData : false,
contentType : false,
type : 'GET',
success : function(response) {
success : function(response) {
marker = JSON.stringify(response);
json = jQuery.parseJSON(marker);
json = JSON.parse(json);
alert(json.status);
}
});
for reference:
https://rwehner.wordpress.com/2010/06/09/2-ways-to-create-json-response-for-ajax-request-in-spring3/

Passing in JSON array to spring MVC Controller

I am trying to pass a JSON array into spring MVC Controller like such:
var myList = new Array();
data._children.forEach( function (d) {
myList.push( {NAME: d.name, TYPE: d.TYPE, FDATE: d.FDATE } );
});
$.post("/ListRequest", {myList: myList});
The controller looks as such:
#RequestMapping(value="/ListRequest", method = RequestMethod.POST)
public void ListRequest(#RequestParam("myList") myList tempmyList )
{
System.out.println(tempmyList);
}
The class myList defined as such:
public class MyList {
private List<ListT> ListT;
public List<ListT> getListT() {
return ListT;
}
public void setListT(List<ListT> listT) {
ListT = listT;
}
}
ListT class:
public class ListT {
private String NAME;
private String TYPE;
private Long FDATE; ...
I keep getting this error:
HTTP Status 400 - Required myList parameter 'myList' is not present
Also tried this request:
$.ajax({
type: "post",
url: "ListRequest", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(myList), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(e){
alert('failure');
}
but get this error: JBWEB000120: The request sent by the client was syntactically incorrect.
try to add this to you ajax call it should fix the unsupported response :
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
this is a full example of ajax call that is working for me :
$.ajax({
dataType : "json",
url : this.baseurl + "/dataList",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
data : JSON.stringify(params),
type : 'POST',
success : function(data) {
self.displayResults(data);
},
error : function(jqXHR,textStatus,errorThrown ){
showPopupError('Error','error : ' + textStatus, 'ok');
}
});
Even I was facing same problem.
My client request was right and generated proper json file.
but still i was getting same error.
I solved this error using #JsonIgnoreProperties(ignoreUnknown = true) in pojo class.
refer this link.
Spring MVC : The request sent by the client was syntactically incorrect
You can try
#RequestParam("myList") myList tempmyList
#Param myList tempmyList
in addition, class names must begin with a capital letter.

Call Web Service method that insert an object from jquery ajax

I have a web service method similiar to this:
#Path("/insert_update")
#POST
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_JSON })
public Object insert(User obj) {
...(insert and return object)
}
And I want to call this method from jquery, using ajax. I've tried something like this:
var rootURL = "http://Path/to/my/web/service";
function insertUpdate() {
var user = {'name' : $("#name").val(),
'surname' : $("#surname").val(),
'surname1' : $("#surname1").val(),
'usertxt' : $("#usertxt").val(),
'password' : $("#password").val() };
$.ajax({
url : rootURL + "/insert_update",
type : "POST",
contentType: 'json',
dataType : "json",
data : user,
success : function(data) {
alert(JSON.stringify(data));
},
error : function(data) {
}
});
}
Is this code correct? When I try to use it I get this response:
Failed to load resource: Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
XMLHttpRequest cannot load ... . Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
I hope you can help me.
Greetings.
UPDATE
The web service is in the same machine, but in other port. I run the web service project on a WebSphere Application Server and then I only open the HTML file to test my code.
I have other method I don't have problem with, like this:
#Path("/all")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Object all() {
...(get all users)
}
And the JQuery method for this code:
function all() {
$.ajax({
url : rootURL + "/all",
type : "GET",
dataType : "json",
success : function(data) {
$("#tabla tbody:last").empty();
$.each(data.data, function(i, item) {
$("#tabla tbody:last").append("<tr><td>"+item.id+"</td><td>"+item.name+
"</td><td>"+item.surname+"</td><td>"+item.surname1+"</td><td>"
+item.usertxt+"</td><td>"+item.password+"</td></tr>");
});
},
error : function(data) {
}
});
}
This works fine, I have no problem...but I had to donwload an extension for Chrome to test locally, Allow-Control-Allow-Origin.
Why with GET method I have no problem and with POST method yes???
Greetings.