Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid displaying returned data from Spring @ResponseBody on browser

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?

like image 294
Ra Ka Avatar asked Feb 01 '26 06:02

Ra Ka


1 Answers

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/

like image 183
Ra Ka Avatar answered Feb 02 '26 18:02

Ra Ka