Ajax and Java web service strange error - java

I got a really weird error. I successfully run my code and consume the web service. The service return 200 code. But jquery ajax executes error function instead of success. I post the information (Nothing on console):
Javascript:
$(document).ready(
function () {
$.ajax({
url: 'Test/Service/hello',
dataType: 'json',
contentType: 'application/json',
data: {name: 'testing'},
error: function () {
$('#text').html('<p>An error has occurred</p>');
},
success: function (data) {
$("#text").html(data.d);
},
type: 'POST'
});
});
Java:
package com.morethansimplycode.webservice;
import javax.jws.WebParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/Service")
public class Service {
public Service() {
}
#POST
#Path("/hello")
#Consumes({MediaType.APPLICATION_JSON})
#Produces(MediaType.APPLICATION_JSON)
public String hello(#WebParam(name = "name") String txt) {
return "Hello " + txt + " !";
}
}
Chrome info:
Remote Address:[::1]:8080
Request URL:http://localhost:8080/WebService/Test/Service/hello
Request Method:POST
Status Code:200 OK
Response Headers
view source
Content-Length:17
Content-Type:application/json
Date:Tue, 01 Dec 2015 21:24:26 GMT
Server:GlassFish Server Open Source Edition 4.1
X-Powered-By:Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1 Java/Oracle Corporation/1.8)
Request Headers
view source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:es-ES,es;q=0.8,ca;q=0.6,en;q=0.4,pt;q=0.2,ru;q=0.2
Cache-Control:no-cache
Connection:keep-alive
Content-Length:9
Content-Type:application/json
Host:localhost:8080
Origin:http://localhost:8080
Pragma:no-cache
Referer:http://localhost:8080/WebService/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
name=paco
Preview:
Hello name=testing !
What's happening?
Edit 1:
Works with this call:
$(document).ready(
function () {
$.ajax({
url: 'Test/Service/hello',
dataType: 'text',
contentType: 'application/json',
data: {name: 'paco'},
error: function () {
$('#etiqueta').html('An error has occurred');
},
success: function (data) {
console.debug(data);
$("#etiqueta").html('<p>' + data + '</p>');
},
type: 'POST'
});
}
);
But i don't know how can i send an object from the Web Service to the JS as Json to use it with data.d, etc...
Edit 2:
Working correctly as follows:
JS:
$(document).ready(
function () {
$.ajax({
url: 'Test/Service/hello',
dataType: 'json',
contentType: 'application/json',
data: {name: 'paco'},
error: function () {
$('#etiqueta').html('An error has occurred');
},
success: function (data) {
console.debug(data);
$("#etiqueta").html('<p>' + data.d + '</p>');
},
type: 'POST'
});
}
);
Java:
#Path("/Service")
public class Service {
public Service() {
}
/**
* This is a sample web service operation
*
* #param txt
* #return
*/
#POST
#Path("/hello")
#Consumes({MediaType.APPLICATION_JSON})
#Produces(MediaType.APPLICATION_JSON)
public String hello(#WebParam(name = "name") String txt) {
return "{\"d\": \"Hello " + txt + " !\"}";
}
}

Instead of
public String hello(#WebParam(name = "name") String txt) {
return "Hello " + txt + " !";
}
try to use:
public String hello(#WebParam(name = "name") String txt) {
return "{\"d\" : \"Hello " + txt + " !\"}";
}
If you returns some complex class, for example Product, it's converted to json, but if you return String, lib can't convert it to {key=value} and think that you generated json manualy. See this question to more info.

Related

Edit files online using Office 365 using WOPI not working - Java

I have a requirement where from my application I have to edit files using office 365. I have used WOPI and it was working fine before, but now I'm getting the following error.
When I contacted the support team, they said WOPI CheckFileInfo is not called, so I explicitly called still the issue persists.
Below is my code,
function submit(docId, type) {
var WOPISrc = "WOPISrc=https://" + host +"/wopi/files/" + docId;
if (type == 'word') {
$('#office_form_online').attr('action', 'https://word-edit.officeapps.live.com/we/wordeditorframe.aspx?edit=1&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else if (type == 'excel') {
$('#office_form_online').attr('action', 'https://excel.officeapps.live.com/x/_layouts/xlviewerinternal.aspx?edit=1&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else if (type == 'powerpoint') {
$('#office_form_online').attr('action', 'https://powerpoint.officeapps.live.com/p/PowerPointFrame.aspx?PowerPointView=EditView&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else if (type == 'pdf') {
$('#office_form_online').attr('action', 'https://word-view.officeapps.live.com/wv/wordviewerframe.aspx?PdfMode=1&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else {
return false;
}
var promise = createWOPIToken(docId);
promise.success(function (data) {
$.ajax({
url: "https://" + host + "/wopi/files/" + docId,
type: "GET",
data: {
access_token: data.token
},
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
return '';
},
success: function (data1) {
console.log(data1);
$.ajax({
url: "https://" + host + "/wopi/files/" + docId + "/content",
type: "GET",
data: {
access_token: data.token
},
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
return -1;
},
success: function (contents) {
$('#office_access_token_online').val(data.token);
$('#office_access_token_ttl_online').val(0);
var frameholder = document.getElementById('frameholder_online');
$(frameholder).show();
closeiFrame();
var office_frame = document.createElement('iframe');
office_frame.src = 'https://"+ host + "/wopi/files/" ' + docId + "?access_token="+data.token;
office_frame.name = 'office_frame_online';
office_frame.id = 'office_frame_online';
office_frame.title = 'Office Online Frame';
office_frame.setAttribute('allowfullscreen', 'true');
office_frame.setAttribute('sandbox',
'allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox');
frameholder.appendChild(office_frame);
document.getElementById('office_form_online').submit();
showCloseButton();
}
});
}
});
});
}
Java Code
#Override
#GET
#Path("/files/{fileId}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response checkFileInfo(
#NotNull #PathParam("fileId") Integer fileId,
#NotNull #QueryParam("access_token") String access_token) {
return Response.ok().entity(fileInfo).build();
}
}
#Override
#GET
#Path("/files/{fileId}/content")
#Produces(MediaType.APPLICATION_JSON)
public Response getFile(
#NotEmpty #PathParam("fileId") Integer fileId,
#QueryParam("access_token") String access_token) {
byte[] data = new byte[(int) content().length()];
DataInputStream dataIs = new DataInputStream(content.getBinaryStream());
dataIs.readFully(data);
return Response.ok(new ByteArrayInputStream(data)).build();
}
#Override
#POST
#Path("/files/{fileId}/contents")
#Transactional
public Response putFile(#PathParam("fileId") Integer fileId,
#QueryParam("access_token") String access_token, byte[] bytes) {
save(BlobProxy.generateProxy(SecurityWrapper.encrypt(bytes)));
return Response.ok().build();
}
The API calls are returning responses but it's not opening files.
EDIT
When I try hitting the below URL (which is used to open files online), without any source, still it shows as Service Unavailable.
https://word-edit.officeapps.live.com/we/wordeditorframe.aspx?
Is it because of it, that my code isn't working? And in the test server, it's a different error, we ran into a problem.
And this is the console error
Any help is appreciated.
Thank you.

Send JSON data as multipart/form-data using axios POST Request

Below API works using postman:
Spring boot, backend code:
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#Slf4j
public class UploadFile {
#Autowired
private FTPClient con;
#PostMapping("/api/auth/uploadfiles")
public String handleFileUpload(#RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
try {
boolean result = con.storeFile(file.getOriginalFilename(), file.getInputStream());
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
} catch (Exception e) {
log.error(e.getMessage(), e);
redirectAttributes.addFlashAttribute("message",
"Could not upload " + file.getOriginalFilename() + "!");
}
return "redirect:/";
}
}
ReactJS, frontend code: I have array of objects in the this.state.ipData.
exportFTP = async () => {
const fromdata = this.state.ipData;
alert("Data Send to FTP server");
axios({
method: 'post',
url: 'http://localhost:8080/api/auth/uploadfiles',
data: fromdata,
header: {
'Accept': 'application/json ,text/plain, */*',
'Content-Type': 'multipart/form-data',
//'Authorization': 'Bearer '+JWTToken,
},
})
}
Button to trigger the function:
<button
style={{ marginRight: "2%", marginTop: "0.25%" }}
type="button"
className="btn btn-info"
onClick={() => this.exportFTP()}
>
Export to FTP
</button>
I need to change my frontend (ReactJS) code to as I did POST request using postman. The current JS code causes below error response:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause
Note that API works when using Postman. How to fix JS code?
You are sending JSON data as Blob in a multipart request. So, you need to use Blob API.
Create a function to create a blob from JSON data:
function jsonBlob(obj) {
return new Blob([JSON.stringify(obj)], {
type: "application/json",
});
}
And use this function in the request:
exportFTP = async () => {
const formData = new FormData();
formData.append("file", jsonBlob(this.state.ipData))
axios({
method: "post",
url: "http://localhost:8080/api/auth/uploadfiles",
data: formData,
/* You had a Typo: it is "headers" not "header".
And, multipart/form-data header should get set automatically
as we used FormData. You might not need to add that manually. */
// You may also not need Accept header; (should be set automatically).
headers: {
Accept: "application/json ,text/plain, */*",
"Content-Type": "multipart/form-data",
// 'Authorization': 'Bearer '+ JWTToken,
},
});
};
Try to remove the header and send the request
exportFTP = async () => {
const fromdata = this.state.ipData;
alert("Data Send to FTP server");
axios({
method: 'post',
url: 'http://localhost:8080/api/auth/uploadfiles',
data: fromdata
}).then(function (res) {
if (res.ok) {
alert("Perfect! ");
} else if (res.status == 401) {
alert("Oops! ");
}
}, function (e) {
alert("Error submitting form!");
});
}

Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) in Java RESTful web service call

I have the following javascript in my test html page to send ajax requests to a java restful web service I built with netbeans (mostly auto generated by using 'Restful web services from database' function).
Here is the ajax query from my test html page:
$(function(){
$('.message-button').on('click', function(e){
var resultDiv = $("#resultDivContainer");
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': 'http://localhost:8080/xxxAPI/api/activity',
'data': { "baseItemId": "2" },
'dataType':'json',
'success': function(data) {
var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
$("#resultDivContainer").text(xmlstr);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert(' Error in processing! '+textStatus + 'error: ' + errorThrown);
}
});
})
});
Also here is the part of my java code that accepts post requests:
#POST
#Override
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(XxxxxActivity entity) {
super.create(entity);
}
When I request from the test page (for this version of the test page), I get this error:
Failed to load resource: the server responded with a status of 415
(Unsupported Media Type)
or this error:
POST http://localhost:8080/xxxAPI/api/activity 415 (Unsupported
Media Type)
So far I have tried making various changes to the ajax request as advised on similar questions on stackoverflow, including changing type to jsonp, putting json data in double quotes, adding headers and changing data type to xml. None of them have worked.
Also since I manage to get a response from the server at times, I wonder if the issue is with xml parsing in the java code. I believe a potential fix would be to add the jackson jar files, but I have no idea how to add them on netbeans as there is no lib folder in WEB_INF.
I would also like to know if there is any issue with the jquery ajax request. This issue has been bugging me for days.
PS: Also note that GET requests from the browser work fine. I have not used maven in this project.
Replace
'data': { "baseItemId": "2" },
with
'data': JSON.stringify({ "baseItemId": "2" }),
Object JSON is available here.
EDIT
add attribute contentType: 'application/json; charset=UTF-8'
remove attribute headers from ajax call.
Frondend
$.ajax({
contentType: "application/json; charset=utf-8",
url: '/GetList',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ 'Name': 'mehmet erdoğdu'}),
beforeSend: function () {
}, success: function (data) {
}, complete: function () {
}, error: function (data) {
}
});
Backend
[HttpPost]
public JsonResult GetList([FromBody] NameRequest req)
{
var selectListItems = new List<SelectListItem>
{
new SelectListItem
{
Value = "",
Text = "Select Name"
}
};
//
return Json(selectListItems, new JsonSerializerSettings());
}

SpringMVC ajax request - java.io.EOFException: No content to map to Object due to end of input

I am working on a SpringMVC application i requested some data from the database using an ajax call the data came back as json object. I now have to send this data back to the server for some processing and return to the form.
However i am getting an error in the browser The server encountered an internal error that prevented it from fulfilling this request. on investigating the error logs i saw this:
Error Log
Controller [com.crimetrack.web.MapController]
Method [public com.crimetrack.business.Marker com.crimetrack.web.MapController.getNewCoordinates(com.crimetrack.business.Marker) throws java.lang.Exception]
java.io.EOFException: No content to map to Object due to end of input
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:1324)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1275)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:941)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:124)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:153)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:120)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:91)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:71)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:75)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
Ajax Call
$('#getCoordinates').on('click',function(){
$.each(global_citizens, function(i, gc){
$.ajax({
type:'GET',
url:'getNewCoordinatesForMarkers.htm',
contentType: 'application/json',
data:{citizens:JSON.stringify(global_citizens[i])},
dataType: 'json',
success:function(new_citizens){
$.each(new_citizens, function(i, c) {
console.log(c.name + ' | ' + c.socialSecurityNumber + ' | ' + c.lat+ ' | ' +c.lng);
});
}
});
});
});
Controller
#RequestMapping(value = "getNewCoordinatesForMarkers.htm", method = {RequestMethod.GET}, headers = {"content-type=application/json"})
public #ResponseBody Marker getNewCoordinates(#RequestBody Marker citizens)throws Exception{
logger.info("Getting Markers");
Marker citizenMarker = this.markerManager.getNextLocation(citizens);
return citizenMarker;
}
Marker.java
public class Marker implements Serializable{
private int socialSecurityNumber;
private String name;
private int citizenType;
private double lat;
private double lng;
//getters and setters
JSON DATA -taken from firebug console
citizens{"name":"Jessie Small","lat":10.670044,"lng":-61.515305,"socialSecurityNumber":1999020214,"citizenType":3}
FireBug - content is being passed
Connection close
Content-Length 3696
Content-Type text/html;charset=utf-8
Date Tue, 07 May 2013 05:52:09 GMT
Server Apache-Coyote/1.1
Request Headers
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type application/json
Cookie tinymcePasteText=1; JSESSIONID=CC4F12D00C836FE0DB86D2493556275C
Host localhost:8084
Referer http://localhost:8084/crimeTrack/crimeTrackMap.htm
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
X-Requested-With XMLHttpRequest
i did this code to preload getting allproduct for autocomplete function, maybe this example not fully fit with your code but i hope you can get something from this:
Controller function :
#RequestMapping(value = "allproduct", method = RequestMethod.GET, headers = "Accept=*/*")
public #ResponseBody
String productList() {
List<Product> products = ProductDAO.INSTANCE.listProduct();
String json = "[";
for (int i = 0; i < products.size(); i++) {
Product o = products.get(i);
if (i > 0) {
json += ",";
}
json += "{\"value\":\"" + o.getCode() + "\",\"label\":\""
+ o.getCode() + " - " + o.getProvider() + " - "
+ o.getNominal() + "\",\"price\":\""
+ o.getPrice() + "\",\"cost\":\"" + o.getCost() + "\"}";
}
json += "]";
System.out.println(json);
return json;
}
in my jsp, i use jquery to call that function :
$.getJSON('/product/allproduct', function(json) {
$("#product").autocomplete({
source : json,
select : function(event, ui) {
$("#product").val(ui.item.value);
$("#kredit").val(ui.item.cost);
$("#price").val(ui.item.price);
return false;
}
});
});
take a look for json format here. Example for an array :
[
{
"name": "Jason",
"number": "10"
},
{
"name": "Jimmy",
"number": "11"
}
]
This is the change to the controller that worked for me
#RequestMapping(value = "getNewCoordinatesForMarkers.htm", method = {RequestMethod.POST},produces = "application/json; charset=utf-8")
public #ResponseBody Marker getNewCoordinates(#RequestBody Marker json)throws Exception{
JSONObject jsonObj = JSONObject.fromObject(json);
ObjectMapper mapper = new ObjectMapper();
Marker citizen = mapper.readValue(jsonObj.toString(), new TypeReference<Marker>(){});
logger.info("Getting Markers");
Marker citizenMarker = this.markerManager.getNextLocation(citizen);
return citizenMarker;
}
You'll get that error if you don't include "Content-Length" in the header.

Issue with POST JSON to a Jersey REST service

I have a problem with posting JSON to a Jersey REST service - GET is working perfectly but POST seems tricky. I've been working on this problem for awhile now, with no solution so far. Any help is much appreciated!
It seems it cant find the U RL to send the json?Here is what FireBug console shows:
POST http://localhost:9998/data 400 Bad Request
Post source: name=Tony
**Response Headers**
Connection close
Content-Length 0
Content-Type text/html; charset=iso-8859-1
Date Fri, 20 Apr 2012 10:13:24 GMT
**Request Headers**
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language sv-se,sv;q=0.8,en-us;q=0.5,en;q=0.3
Connection keep-alive
Content-Length 9
Content-Type application/json; charset=UTF-8
Host localhost:9998
Referer http://localhost:9998/static/page.html
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0
X-Requested-With XMLHttpRequest
I'm doing the POST as follows:
<button id='btn' value="knapp" name="knapp" />
<script type="text/javascript">
$('#btn').click(function(){
$.ajax({
url: '/data',
type: 'POST',
contentType: 'application/json',
data: {name:"Tony"},
dataType: 'json'
});
})
</script>
Javabean class with #XmlRootElement:
#XmlRootElement
public class StatusBean {
private String name;
public StatusBean() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Resource method:
#Path("/data")
public class PostData {
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public StatusBean post(StatusBean sb) {
System.out.println(sb);
return sb;
}
}
The server, set up with Grizzly:
public class Main {
public static final URI BASE_URI = getBaseURI();
public static void main(String[] args) throws IOException {
HttpServer httpServer = startServer();
Map<String,String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages", "server");
SelectorThread selector = GrizzlyWebContainerFactory.create("http://localhost:9998/", initParams );
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\nTry out %shelloworld\nHit enter to stop it...",
BASE_URI, BASE_URI));
System.in.read();
httpServer.stop();
}
protected static HttpServer startServer() throws IOException {
System.out.println("Starting grizzly...");
ClassNamesResourceConfig rc = new ClassNamesResourceConfig(PostData.class);
// rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
HttpServer server = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
server.getServerConfiguration().addHttpHandler(new StaticHttpHandler(new File(".").getAbsolutePath()), "/static");
return server;
}
private static int getPort(int defaultPort) {
String port = System.getProperty("jersey.test.port");
if (null != port) {
try {
return Integer.parseInt(port);
} catch (NumberFormatException e) {
}
}
return defaultPort;
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(getPort(9998)).build();
}
}
Try making your bean serializable.
#XmlRootElement
public class StatusBean implements Serializable {
....
}
Check your POST url. It should be `
http://localhost:9998/{projectname}/{restservletmapping}/data
For example, if my web.xml looks like this and my project name is SampleProject
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
URL would be : http://localhost:9998/SampleProject/rest/data
You can use tools for testing REST services like SOAP UI or browser addons like POSTMAN, REST CONSOLE, etc.
If above things are fine and REST service is giving response with testing tools.
Then it could be problem of Cross Origin Policy in ajax.
I had the same problem. The issue is that your data is not converted to JSON string automatically.
So you just need to call JSON.stringify(...) on your data before posting it:
<button id='btn' value="knapp" name="knapp" />
<script type="text/javascript">
$('#btn').click(function(){
$.ajax({
url: '/data',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({name:"Tony"}),
dataType: 'json'
});
})
</script>
This should work.
From your server config I see that you haven't configured JAX-RS with Grizzly. On the base of that example you should somehow pass such property
Map<String,String> initParams = new HashMap<String, String>();
initParams.put( "com.sun.jersey.config.property.packages", "package.with.your.StatusBean.class" );
Another configuration option is to use
ResourceConfig rc = new PackagesResourceConfig("your.package.with.resources");
and start grizzly server:
GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
See details: http://jersey.java.net/nonav/documentation/latest/user-guide.html (Chapter "Deploying the root resource"). Try to run first example they have.
Are you sure that the path you're posting to is complete? You should define another Path annotation on the post method and use that in the URL you're posting to:
#Path("/data")
public class PostData {
#Path("/postStatus")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public StatusBean post(StatusBean sb) {
System.out.println(sb);
return sb;
}
}
Then use the /data/postStatus path to post your request to:
<button id='btn' value="knapp" name="knapp" />
<script type="text/javascript">
$('#btn').click(function(){
$.ajax({
url: '/data/postStatus',
type: 'POST',
contentType: 'application/json',
data: {name:"Tony"},
dataType: 'json'
});
})
</script>
You have probably forgotten to register the JSON mapper, i.e. Jackson (or whatever mapper you use). The feature is not enabled automatically, you have to load the class in your ResourceConfig:
org.glassfish.jersey.jackson.JacksonFeature.class
sample
also, see JSON howto

Categories