Ajax Call Trouble with Accents - java

I have tried the following line in my ajax call as it was suggested all over internet:
contentType: "application/json; charset=ISO-8859-1"
but it did not change anything. Whenever I make a call from ajax with a string parameter which has an accent for example società, at my controller(I'm using Java, spring framework), i receive it as SocietÃ. I have tried first UTF-8 which is the default (as far as I know) but nothing. Here is my full function:
function foo(customer, society) {
$.ajax({
url: 'notMappedAcoStaffing.do',
type: "GET",
contentType: "application/json; charset=ISO-8859-1",
data: { customer: customer, society: society},
success: function(data) { $('#content').html(data); },
error: function(error) { alert("error" + error); }
});
}
And I take the values on my backend as
#RequestMapping(method = RequestMethod.GET)
public ModelAndView fooController(#RequestParam("customer") final String customerParam, #RequestParam(value="society",required=false) Integer societyParam) {...}
Is there a way to resolve this issue?
Thanks for your help in advance.
UPDATE: I have still no idea why I receive it distorted as parameter at my controller. But however when I convert it as follows: How do I convert between ISO-8859-1 and UTF-8 in Java? ,it comes out all good. Seeing that it works, I tried it again to set UTF-8 in my ajax call but no success... It resolved my issue but honestly I do not like this way. Please share with me if you have a better solution maybe on the ajax call side. Thanks

Part of your problem is that you're using HTTP GET, which basically means that your data will be embedded in the URL itself, in the query string ( http://example.org/?customer=foo&society=bar ). This can lead to problems when using special characters.
Especially, the contentType property concerns the body of the request which you do not have at all so currently it has little impact.
Consider sending the data with HTTP POST (and remove your custom contentType) which gives you more power over the encoding of your data - which is then sent in the request body instead of the URL. It might solve your problem outright, or you might need to configure your server to use the same encoding as the client
- I suggest UTF-8 for both parties.

Related

Redirect to another page with #RequestBody

I'm struggling with something.
i pass JSON data to my controller
$.ajax({
type:'POST',
url:'${pageContext.request.contextPath}/saveMovBienes2',
data: JSON.stringify({ dni:dni, table:table, tipoMov:tipoMov}),
dataType: "json",
contentType: 'application/json'
})
In my RestController, i handle this information like this
#PostMapping("/saveMovBienes2")
public String saveMovBienes2(#RequestBody Request myRequest)
saving the JSON elements into the object myRequest.
The thing is, having #RequestBody forces me to stay in that JSP, but i want to after processing this information, redirects to another page.
Tried with various ways to redirect but the view stays the same (in my console i see the info processing but the view is static)
I read people with the same problem, and their answer was "removing #RequestBody", but in my case i'm not able to make it work without the #RequestBody.
Is there any way to rediect? or i have to modify all my code?
I finnally find a workaround, thanks to the comments above:
.done(function() {
})
.fail(function(){
window.location = '${pageContext.request.contextPath}/nuevoMovimientoBU';
})
For some reason, its not entering to .done , but in .fail

Making cross domain jquery ajax calls to Restful webservice?

I am using Jquery Ajax calls to access REStful webservices as below. The webservice is hosted on different domain.
$.ajax({
type: "GET",
url: "some url hosted on differnt domain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(responseJson) {
alert("json"+responseJson);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
Am not sure whether it is not hitting the webservice.It is going to error block but no alert is displayed. Am i doing anything wrong here?
Thanks!
You got to change the Header at you server side http://www.w3.org/TR/cors/#access-control-allow-origin-response-header
Since it will cause forgery. For more of cors understanding http://enable-cors.org/server.html
You can't make cross domain request just like that. It might cause cross-site forgery. Check this-
http://en.wikipedia.org/wiki/Cross-site_request_forgery
Basically, to be able to do so, the server should allow you to do that. If you access some resource on a cross domain server. The server responds back with a list of allowed users for that resource. The browser reads that list. If you are not listed in that list then the browser won't show the resource to you.
Solutions:
1- You should have control of the server side.
2-you can try 'script' tags in HTML for your purpose. They are an exception to this. You can make cross-domain requests using 'script' tags and then parse the response as json.
3-Jsonp callbacks.
I haven't actually implemented in much detail because I have control over server side whenever I need. And, CDNs are open to all. So, you might want to do some reading now to figure out more.

Some information about how Spring MVC recive and use the Accept Header in these two case

I am studying on the Spring MVC showcase example dowlodable from the STS dashboard.
In this time I am studying on the Converters section of this example and I have some question for you.
To start, in my view I have the following two links:
<li>
<a id="writeJsonAccept" class="writeJsonLink" href="<c:url value="/messageconverters/json" />">Write JSON via Accept=application/json</a>
</li>
<li>
<a id="writeJsonExt" class="writeJsonLink" href="<c:url value="messageconverters/json" />">Write JSON via ".json"</a>
</li>
The first link generate an HTTP Request towards the URL: messageconverters/json
The second link generate an HTTP Request towards the URL: /messageconverters/json.json (differently from the first URL this one end with .json extension
Ok, both these links have class="writeJsonLink" and related to the click event of these links the following JQuery callback function is called:
$("a.writeJsonLink").click(function() {
var link = $(this);
$.ajax({
url: this.href,
beforeSend: function(req) {
if (!this.url.match(/\.json$/)) {
req.setRequestHeader("Accept", "application/json");
}
},
success: function(json) {
MvcUtil.showSuccessResponse(JSON.stringify(json), link);
},
error: function(xhr) {
MvcUtil.showErrorResponse(xhr.responseText, link);
}});
return false;
});
This function only execute an AJAX call and wait for an HTTP Response passing its content to an handler that will show the output in the view...ok...
Before sending the request, the function check if the URL don't end with .json extension
If this request don't end with .json extension the following header is added to my HTTP Request:
Accept = application/json
From what I know the Accept Header say which specific mediatype is considerable acceptable for the HTTP Response, in this case say that the only acceptable media type is a JavaScript object having JSON format, ok...
This Request is handled from the following method of my controller class that return a valorized object that will be converted in JSON forma using Jaxb2RootElementHttpMessageConverter
#RequestMapping(value="/json", method=RequestMethod.GET)
public ResponseEntity<JavaBean> writeJson() {
// Oggetto che rappresenta gli HTTP Header dell'HTTP Response
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<JavaBean>(new JavaBean("bar", "apple"), headers , HttpStatus.OK);
// return new JavaBean("bar", "apple");
}
Now, my question is about the differences from the two links.
The first one don't end with .json extension, so the Accept header is added and it is setted on application/json sayng that the browsers expects to receive a JSON object
The second one end with .json extension, so the Jquery method don't set the Accept Header
But, this thing what mean? that when an URL end with .json the Accept header is automatically setted? Or more generally, when I have an URL that end with some kind extension (for example like .xml) the relative Accept header is automatically setted?
Or simply in this second case, don't set the Accept Header mean don't handle the media type that I can recive in the body of the HTTP Response?
Ok, your english is not-so-hot, so let me try to help you the best I can.
In my understanding, which may very well be wrong, is that you want to know if the browser will set the Accept: header to be json when the URL ends in json? I do not believe this is the case. I may be greatly mistaken on this, but you can test this by using something like Firebug or Chrome's Developer Tools, or if you like IE get Fiddler, and see exactly what headers get sent from the browser.
Now, if you are asking if Spring will magically put the headers there, then again I think the answer is "no". The HTTP headers on the request come from the browser, and although you could put in a Servlet Filter or something to set the request filters, I think this would be dangerous to assume all browsers handle these request headers the same way.
No, if the question is "how are my requests all getting to my Controller's writeJson() method?", then the answer has nothing to do with the "Accept" header at all. Your method is matching on any URI pattern that ends in /json, and in both cases your URL ends in /json. If you want to filter on things that have an "Accept" header of JSON, then I think you want to do something like this:
#RequestMapping(value="/someUriPattern", headers = {"Accept=application/json"})
Please understand I typed the above from memory, so you may need to tweak it a tad.

Post JSON Data From Javascript To Java

I'm in need of some desperate help. I've been at this for 4 hours, and I'm getting pretty worn out. :/ Here's my situation:
I have a Javascript application that is making a POST request (using jQuery $.post) to an external site. On the external site I have Apache Camel running with Jetty to expose it to the web. The web services I wrote in Camel expect JSON data for all of the requests. For instance, one request needs an id, so I send it {"id": 10}.
Here's my issue: it doesn't work from Javascript. I have a few different tools that will send post requests for me (like the Poster extension for browsers). If I use Poster and set the body to {"id": 10}, it works just fine. I get that exact string in the service.
But, if I post from Javascript, I get something different. Posting the JSON object will give me the string "id=10" on my service side. (It's OK for this scenario, but I will need actual JSON objects eventually.) If I stringify the JSON object, I get the JSON string, only all of the characters are escaped. (Ex. "%7Bid%33...").
I swear I've tried every method possible for posting the data, but I either get the weird already parsed JSON, or the escaped string (or nothing at all). Is there some way I can have Javascript NOT parse the JSON object and just send it (like my posting tool does)? If not, is there a safe, efficient way to un-escape the JSON string that I get?
I really appreciate any help.
I feel like we need a little bit more information, but take a look at this javascript plugin. It may be your solution: https://github.com/flowersinthesand/jquery-stringifyJSON
Try using jQuery.ajax and setting processData to false (defaults to true):
$.ajax({
url: '/where/to/post',
type: 'POST',
data: {"id": 10},
processData: false
});
Usually, jQuery converts anything in data to query string format like id=10. The processData flag tells jQuery to interpret it literally as a json hashmap.
Posting the JSON object will give me the string "id=10" on my service side.
Javascript does not do your this conversion, so your server does it.
It is likely that your server reacts differently based on the content-type of your POST e.g. application/json vs text/plain or text/html, a common feature of REST based services.
The answers here gave me a few hints, but ultimately, it was a lot of tweaking before it would work correctly. I had to do 3 things:
Add processData: false.
Turn the JSON object into a JSON string. The request wouldn't fire if I left it as an object (even if I changed contentType to application/json).
Change the contentType to text/plain. This sent it as a raw string.
And that's what did the trick. I now get the JSON string I want on the server side.

Getting Session data in Ajax call

hi I am querying database to load all items based on some criteria and setting this result in session as
data = service.getData();
session.setAttribute("data", data);
now I am trying to access this data via an Ajax call and my Ajax call is served by a different servlet rather then which fetched the data from DB.
Ajax call using jquery
$.ajax({
type: "POST",
url: "/com/tp/AjaxXML.jsp",
data: ({cmd: "report"}),
dataType: "xml",
success: function(xml) {
$(xml).find('site').each(function(){
var url = $(this).attr('url');
});
}
});
in my AjaxXML.jsp
I am doing
if("report".equals(cmd)){
List<Object> data = (List<Object>)request.getSession().getAttribute("data");
if(data == null){
System.out.println("data is null ");
}
}
every time I am getting the data as null via the Ajax call how ever I try to access the session data normally from my first servlet it works.
could someone let me know if I am doing something wrong?
I noticed one more thing when we do session.getId(); and pageContext.getSession().getId();
both of them are returning different Id's? Is this expected to me they should be same anyone differ on that?
I noticed one more thing when we do session.getId(); and pageContext.getSession().getId(); both of them are returning different Id's? Is this expected to me they should be same anyone differ on that?
No, they should definitely not differ. I however assume that you have examined them within the same request. If you examined them in different requests, then the difference can be explained by the absence of the proper JSESSIONID cookie. Cookies are domain and context specific. You're apparently sending the ajax request to a different domain/context. The leading slash / in the ajax URL also confirms this less or more. Make sure that you're sending it to the same domain/context. Use a context-relative URL, something like as url: "AjaxXML.jsp" and move the code to the same domain/context, or turn on session sharing between different contexts at server level.
Unrelated to the concrete problem, doing the Ajax response handling in a JSP is a bad idea. Rather do it in a servlet.
Replace
url: "/com/tp/AjaxXML.jsp",
by
url: "/com/tp/AjaxXML",
and put the code in doPost() method of the servlet which is mapped on that URL pattern.
See also:
How to use Servlets and Ajax?

Categories