Okay, curerntly I am displaying some data on a html page. I have used jquery ajax call which get the data from the specific url on spring MVC application and return data and then use javascript to display data in the table.
@RequestMapping(value = "/students", method = RequestMethod.GET)
@ResponseBody
@JsonView(Views.PublicView.class)
public ArrayList<Student> getAdminsList(HttpSession session) {
//return data
}
Now, my question is, I get data as I required via ajax, but I do get data displayed in the browser if I just go through url: www.example.com/students - will display JSON data.
Is there anyway to avoid display this data not in browser but only in ajax call?
Anyway, I just found the answer for this after lots of googling and I thought sharing it would be good thing. So, basically what is the logic for this restriction is that, whenever a call is made from ajax a special header named X-Requested-With with a value of XMLHttpRequest is attached to the request. the only thing I have to do is check this parameter on my controller.
@RequestMapping(value = "/accounts", method = RequestMethod.GET)
@JsonView(View.Accounts.class)
public List<Account> getAccounts() throws JsonProcessingException {
if(!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
log.info("Request is from browser.");
return null;
}
List<Account> accounts = accountService.findAccounts();
return accounts;
}
you can read the full article on this blog. http://www.gmarwaha.com/blog/2009/06/27/is-it-an-ajax-request-or-a-normal-request/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With