Does #RequestMapping(produces = "application/json;charset=utf-8") block jsonp requests? - java

I'm trying to debug a problem on production server where there's a method inside a controller that is annotated by:
#RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
And in javascript an ajax call is made to this endpoint:
$.ajax({
type: "GET",
async: true,
url: "<%=endpointUrl%>",
dataType: "jsonp",
success: function(data){
console.log("success!");
},
error: function(xhr, options, error){
console.log("fail!");
}
});
But in chrome I get warning for Cross-Origin Read Blocking (CORB) blocked cross-origin response ... with MIME type application/json.
I thought jsonp is used to 'bypass' same-origin-policy for get requests? Why is it getting blocked?
EDIT: additional info, these headers are set in the endpoint:
httpResponse.setHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval'");
httpResponse.setHeader("X-Content-Type-Options", "nosniff");
httpResponse.setHeader("X-XSS-Protection", "1");

Change jsonp to json as your server is returning content type JSON but not jsonp.

I figured it out..
#RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
change to
#RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "text/javascript;charset=utf-8")
The problem is caused by
httpResponse.setHeader("X-Content-Type-Options", "nosniff");
enforcing content-type

Related

Spring Rest Service throwing HTTP Status 415

Hi I am trying to call a Spring rest service from angular but I am getting the below error. Even from The Postman I am getting the same error.It looks like something is wrong with the rest service, which is not accepting the json request data
HTTP Status 415 : The server refused this request because the request entity is in a format not supported by the requested resource for the requested method. Thanking everyone in advance.
Below is the code
**Angular Code**
var req = {
method: 'POST',
url: 'http://localhost:9050/FastTrackALM/retrieveData/getEpicData',
headers: {
'Content-Type': 'application/json'
},
data: {'epicId': '1' }
}
$http(req).then(function(response){
console.log(response);
}, function(response){
console.log(response);
});
**REST SERVICE**
#RequestMapping(method=RequestMethod.POST,
value="/getEpicData",
consumes={"application/json"},
produces={"application/json"})
#ResponseBody
#ResponseStatus(code = HttpStatus.OK)
public DataActionObject insertStudentDetails(#RequestBody epicForm1 student){
DataActionObject dataActionObject = new DataActionObject();
dataActionObject=epicBusinessBean.getEpicData(student.getEpicId(), dataActionObject);
return dataActionObject;
}
DataActionObject is my custom class that holds the json date to be returned to client along with message an code

Send json object with another parmeter to the controller in spring mvc

1.- I want to recive this two paramters like this in my controller :
*/Controller
#RequestMapping(value = "/insertCatalogGeneric", method = RequestMethod.POST)
public #ResponseBody
String insertCatalogGeneric(#RequestBody CatalogGeneric catalogGeneric , String tableName) {
String table_name = tableName;
String catalogInserted = catalogGenericService.insertCatalogGeneric( table_name, catalogGeneric);
return catalogInserted;
}
2.- I send to the contoller in this way...
$.ajax({
url : 'insertCatalogGeneric',
type : 'POST',
data: {'catalogGeneric' : JSON.stringify(description_data) , 'tableName' : "fadsf"},
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success:function(data, textStatus, jqXHR) {
3.- In my debug I receive error 400 not found the direction .... i know that is for the way that i send the parameters , but what will be the correct form to do that ?
In your case, Ajax call having contentType: "application/json" format, So when your doing ajax call with JSON format, In your Controller your Request Mapping should have consumes = "application/json",
For the particular request mapping add like this in your controller,
#RequestMapping(value = "/insertCatalogGeneric", method = RequestMethod.POST,
consumes = "application/json")
public #ResponseBody
String insertCatalogGeneric(#RequestBody CatalogGeneric catalogGeneric , String tableName) {
[Additional]
For safe request body format
try to stringify the whole JavaScript Object.
$.ajax({
url : 'insertCatalogGeneric',
type : 'POST',
data: JSON.stringify({'catalogGeneric' : description_data , 'tableName' : "fadsf"}),
cache: false,
contentType: "application/json; charset=utf-8",
success:function(data, textStatus, jqXHR) {
}
});

Http status 404 (Not Found) on jquery ajax GET to spring controller?

My spring controller contains such get handler :
#RequestMapping(value = "/country", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Region> getRegionsFor(#RequestParam(value = "countryName") String countryName,
#RequestParam(value = "geonameId") Long geonameId) {
logger.debug("fetching regions for {}, with geonameId {}", countryName, geonameId);
RegionInfo regionInfo = restTemplate.getForObject(
"http://api.geonames.org/childrenJSON?geonameId={geonameId}&username=geonameUser2014",
RegionInfo.class, geonameId);
return regionInfo.getRegions();
}
#Controller is mapped to /hostel. So url is /hostel/country?countryName=%27&Albania%27&&geonameId=783754
When I type in chrome browser
http://localhost:8080/HostMe/hostel/country?countryName=%27Albania%27&geonameId=783754
It returns json response as expected!!!
But I want to access this url with the following ajax call made with jquery:
$.ajax({
headers : {
'Accept' : 'application/json'
},
url : '/hostel/country',
dataType : 'json',
data : {countryName:"Albania",geonameId:783754},
type : 'GET',
async : true,
success : function(response) {
console.log("response=" + response.join(','));
},
error : function(errorData) {
console.log("data on fail ");
printObject(errorData);
}
});
As you guess this doesn't work at all. Http status 404 (Not Found) is returned to error: handler .
How can I solve this?
The url in the ajax call is relative to the hostname. You need to add your web application context
url : '/HostMe/hostel/country',

Getting exception in JQuery file uploader

I am new to JQuery file uploader and I am implementing some part of that. When I select an image from JQuery file uploader, a call goes to server side (SpringController) but the API returns:
406 Not Acceptable
this my call to server:
$(this).fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: uploadSettings.upload_url,
type: 'POST',
maxNumberOfFiles: uploadSettings.maxNumberOfFiles,
maxFileSize: uploadSettings.maxFileSize,
acceptFileTypes: uploadSettings.fileSelection,
sequentialUploads: true,
paramName:'uploadfiles[]',
dataType: 'text'
});
and my Java Controller code is as:
#RequestMapping(value = { "/user/fileuploader" }, method = RequestMethod.POST,
produces = "text/plain")
#ResponseBody public String uploadFileHandler(
#RequestParam("uploadfiles[]") MultipartFile[] file,
HttpServletRequest request, HttpServletResponse response) {
Any advice?
Here is a project that uses a very similar stack to JHipster (I'm the author of both projects), and which does uploading with the same JQuery plugin:
https://github.com/ippontech/tatami/blob/master/src/main/java/fr/ippon/tatami/web/fileupload/FileController.java#L193
As you can see my return object is different. You can copy my code from:
https://github.com/ippontech/tatami/tree/master/src/main/java/fr/ippon/tatami/web/fileupload

Pass JSON as Java Class to Spring Controller by GET

I have the following code that works:
#RequestMapping(value = "/jsonasclass", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody
ContactVO jsonAsClassPost(#RequestBody ContactVO ct){
ct.setFirstName("This-property-is-changed-in-the-controller");
return ct;
}
and the corresponding ajax call by post:
$.ajax({
url: '/jsonasclass/',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
id:1,
userID:1.1,
login:'sample-login',
firstName:'sample-first-name'
}),
contentType: 'application/json',
mimeType: 'application/json',
success: _callBack,
error: _errorCallback
});
Now I want to achieve the same thing, but I want to do it by GET. Anyone knows how?
I have tried changing POST to GET (in both controller and ajax call) but it did not work.
The error I get: description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Thanks to RaulRene's comment here is how you would do it.
get rid of #RequestBody from the controller and change method to get.
send the properties of the class in the controller as browser variables and spring will automatically map them to the class.
Here is the solution:
#RequestMapping(value = "/jsonasclass", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody
ContactVO jsonAsClassGet(ContactVO ct){
ct.setFirstName("This-property-is-changed-in-the-controller");
return ct;
}
and corresponding ajax:
$.ajax({
url:'/jsonasclass/',
type: 'GET',
data: {
id:1,
userID:1.1,
login:'sample-login',
firstName:'sample-first-name'
},
success: _callBack,
error: _errorCallback
});

Categories