Spring MVC Ajax Request not active in controller class - java

I am new at spring MVC .I am trying to do ajax request on spring MVC. This seem when ajax call act controller method doesnt response.But I didnt understand why it is.
But I am getting this error on browser console:
Failed to load resource: the server responded with a status of http://localhost:8080/spapp/ajaxtest.html 404 (Not Found)
Here My method in controller class:
#RequestMapping(value = "/ajaxtest", method = RequestMethod.POST)
public #ResponseBody String ajaxtest() {
String result = "This is Ajax text from ajaxTest Method";
return result;
}
Here My Ajax call in index.jsp:
$(function(){
$(document).on("click","button#save",function(){
$.ajax({
type:"POST",
url:"ajaxtest.html",
data:{test:"test"},
success:function(response){
$("div#response").html(response);
}
});
});
});
What can I do fix this error?
Thanks

Try with url:"ajaxtest" you don't have to put .html at the end because you have declared your endpoint value = "/ajaxtest".

I found the solution.I removed type="POST" in ajax call.after it runs.

Related

GET Method Is Not Calling In IE

I am new to AngularJs & Spring. I am calling Spring MVC GET Method from AngularJs function. Sometime GET method is not called up and giving old session values. If i use POST its working fine.
Please comment if need more details about it.
Spring MVC method :
#RequestMapping(value="/getAccessDetails", method=RequestMethod.GET)
public #ResponseBody ProcessDO getAccessDetFromSession(HttpServletRequest request){
AccessDO accessDO = null;
HttpSession session=request.getSession();
if(session.getAttribute("accessDetail")!=null) {
accessDO =(AccessDO) session.getAttribute("accessDetail");
}
return accessDO ;
}
AngularJS Function :
$scope.loadDetails = function(){
$http.get(CONTEXT+'/getAccessDetails').then(function(resp){
alert(resp.data); // Getting old value
});
};
Targets of caching operations
I think this explains your issue.
This is happening because your response is getting cached and when you are trying again you are getting cached response in case of GET.
While post method doesn't get cached neither it get saved in browser history.
you can also referhttp_methods_get_post_difference this link

JQuery stringify not working

Simply, I'm trying to parse a List of composite objects passed from Spring controller via ModelAndView object as the following
Spring part
ModelAndView view = new ModelAndView("my view");
List<ActionHistory> histories = myService.getListData();
view.addObject("histories", histories);
return view;
In Jquery i tried couple of alternatives, first used the below line to construct JSON from List:
var list = JSON.stringify('${histories}');
console.log(histories);
the console is returning
"[com.companyname.projectname.domains.ActionHistory#48126327]"
TypeError: invalid 'in' operand a
I also tried from jquery-json by including "jquery.json.min.js" as a suggestion from this topic discussed but getting the same error above Serializing to JSON in jQuery
var histories = $.toJSON('${histories}');
console.log(histories);
Check you contentType in ajax function it should be.
contentType: "application/json"
Also your Spring controller which is handling this mvc call should configure be configired with
produces=MediaType.APPLICATION_JSON_VALUE
e.g. something like
#RequestMapping(value ="/getList", method= RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)

Play framework: redirect to a different domain

I am using Play 2 with Java and one of my controller methods returns a redirect:
return redirect(<some other domain>);
The client side call happens from an angular controller through $http:
$http.get("/signin").
...
This does not work; Firefox tells me to enable CORS. So I tried to enable CORS as suggested by the answers to this StackOverflow question. But I still get the same error. However that answer seems to be directed towards JSON responses. Do I need to do anything different for a redirect?
I would have thought that setting Access-Control-Allow-Origin to * would do the trick, but that doesn't seem to work.
Http 3xx redirection responses are transparent to AJAX calls. One possible solution for this problem is to return something else than 303 which can be resolved by AJAX. For example you can assume that all responses from your application with code 280 are intended for an AJAX redirection. Then your controller would look like this:
public class Application extends Controller {
public static Result signin() {
// ...
return status(280, "https://api.twitter.com/oauth/authenticate?oauth_token=" + requestToken.getToken());
}
}
On the client side you could check a result status code and react for code 280. Below there's a simple example with a page redirect but you can do anything you like with that response.
<script>
$(function() {
$.ajax({'url': '/signin', statusCode: {
280: function(response) {
window.location = response;
}
}});
});
</script>

Spring MVC controller view

Hey guys, I have a list to be displayed on a view JSP page from the controller side. What do I return from the modelandview function if I want the list to be displayed in the same view page I am calling it from?
Here is the jQuery which i use to call the controller
$("#customerList").on("keydown",function(){
$.ajax({
url: '/omp/customer',
type: 'GET'
});
});
});
Here is the controller code
#RequestMapping(method= RequestMethod.GET)
public ModelAndView getlist(Model mod)
{
System.out.println("I am here");
CustomerDetails details = new CustomerDetails();
details.setAl();
mod.addAttribute("lists",details.getAl());
return new ModelAndView("dashboard/home");
}
It looks like you want to make an Ajax call to the server and retrieve a list.
Ajax calls are asynchronous and don't require to load a new page.
My advise is that the controller should return the list in JSON format and some
javascript should parse and display it.
Have a look at #ResponseBody annotation in the Spring MVC documentation.

Returning ModelAndView in ajax spring mvc

Hi am using spring mvc + ajax. I made a ajax call by passing a userid. And everything goes fine successfully returned to ajax but when i alert the response its simple showing the html page code. Please help me to sort out this prob.
I think i didnt coded my ajax well.Help me to in correct way
Controller code:
public #ResponseBody ModelAndView abc(HttpServletRequest httpServletRequest,
HttpSession session, ModelMap map){
ModelAndView modelAndView = new ModelAndView("abcd.page",
"commandName", object);
return modelAndView;
Ajax code :
$(".userDetails").click(function() {
alert("clicked");
var userId=$(this).parent().parent(). parent().find(".userId").
text().trim();
alert("userId :"+userId);
$.ajax({
url : 'ABC.htm',
type : 'GET',
data: {userId:userId},
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success : function(response) {
alert("success");
alert(response);
},
error : function(res) {
alert("error");
},
});
return false;
});
The output for the alert(response); is
EDIT: Can any one please tell why ajax giving html content on success... After many changes i made getting the same alert.
Edited Again : I think i dont have any problem in controller. Please suggest me solution to code my ajax correctly. It seems error here. How to get a ModelAndView object in ajax
You don't get a ModelAndView object in AJAX. Spring uses HandlerMethodReturnValueHandler instances to handle your handler method's return value. For ModelAndView, it uses ModelAndViewResolverMethodReturnValueHandler. For #ResponseBody, it uses RequestResponseBodyMethodProcessor. These are checked in a specific order and the one for ModelAndView has higher priority. Therefore, when you return a ModelAndView, Spring will add the model attributes to the full Model and then resolve your view name to, probably, a jsp and write the response from that jsp, giving you some HTML. Since AJAX just sees the response from the request, it will see HTML.
If you want to return JSON, don't return a ModelAndView, return the model object directly or write JSON directly to the response yourself.

Categories

Resources