Redirect to another page with #RequestBody - java

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

Related

Ajax Call Trouble with Accents

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.

Not fetching dynamic dropdown using jquery spring mvc and hibernate

While click on an add button i have given the jquery code to navigate next page.
Here is my jQuery code:
$("#id-add-mer").click(function(){
location.href="../ecom/addMer";
});
here is my controller:
#RequestMapping(value = "/addMer", method = RequestMethod.GET)
public String addMerchant() {
return "merchantRegistration";
}
here it redirects to that page, but i have 3 dynamically fetching dropdown inside this page. i'm trying to fetch the values by adding an onload event in the body tag. here is my ajax code
function loadDropDown(){
$.ajax({
type: 'POST',
url: "ecom/loadInd",
data: {},
dataType: "json",
success: function(data) {
count = Object.keys(data).length;
$("#id-industry").empty();
for(i=0;i<count;i++){
$("#id-industry").append('<option value="'+data[i].id+'">'+data[i].type+'</option>');
}
loadBank();
},
error: function(jqXHR, textStatus, errorThrown) {
alert("1Server Exception");
}
});
}
i'm making an ajax call to fetch 2nd dropdown at the success of 1st call. while loading this page as welcome file displays the fetched dropdowns, i'm using spring mvc and hibernate to retrieve the records. But here i'm getting the error. Can anyone tell me how can i fix this issue..Thanks in advance...
Its better if you can mention here, what you get as error message in your code. Otherwise try to follow below steps to identify the issue.
First of all you better check whether your http request can access your server. you can use third party tools as well as built-in element viewer for that.
if there is no issue with communication with controller then check the what will return from "/loadInd". Simply you can debug or you can use alert box to inside success block.
Happy Coding....

Extracting information from XML File

I have been trying to extract the information from this file for the past couple of hours and have run out of options.
http://www.nationalbanken.dk/dndk/valuta.nsf/valuta-hist.xml
Currently I have the information stored as a string in a Java servlet.
When I try to send it as a response to an AJAX request, I can't seem to extract any of the attributes through jQuery (mainly the time, currency, etc.)
I don't have a whole lot of experience with XML, actually none, so after trying various methods here on StackOverflow I have come to the conclusion that I simply can't find anything that'll work for me.
$("#btn").click(function() {
$.ajax({
url: "AjaxController?command=currency",
cache: false,
dataType: "xml",
success: processXML
});
});
This is my AJAX call to the servlet, in return it gives back the file linked above loaded into a string, which then needs to be processed and extracted by the jQuery function "processXML".

Jquery ajax call returns error when the rest service is returning a string

Trying to send a simple text from my rest service and read it using ajax call. Found many answers about jsonp and cross browser compatibility, tried crossdomain too.
Here is the rest service:
Trimmed everything down to send only a simple string.
#GET
#Path("/getcontents2")
#Produces({MediaType.TEXT_PLAIN})
public String getContents2(#QueryParam("name") String msg) {
return "abc";
}
The ajax call:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://metrics/getcontents2?name=Work/loc.txt',
crossDomain: true,
async: false,
dataType:'html',
success: function (data) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(xhr.responseText);
console.log(xhr);
},
});
});
The browsers opens up the string as is. I guess something is really wrong in the jquery script.
Error on Firebug:
GET http://metrics/getcontents2?name=Work/loc.txt 200 OK 4ms
0
(an empty string)
(an empty string)
Object { readyState=0, status=0, statusText="error"}
Fixed it!
It was because my server was not supporting cross-domain. Configured it will corsfilter and it worked like a charm!
try setting your datatype to text jsonp
dataType: 'jsonp',
http://api.jquery.com/jQuery.ajax/
You will have to do one of two things to go with this to resolve the error further;
making changes on the server side to pass the data back as json and not as text
retun the string encoded in json return "{"text":"abc"}"; //or something like this
Why?
jquery cross-domain requests are only allowed for dataTypes "script" and "jsonp".
I have updated your fiddle it still throws an error but that is related to a parse json error

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.

Categories