0

Hello I have been using Spring 3 for my project, I have been stuck in on point.

if(ajax){

        User user = userTemplate.getUser(form.getCreator_id());
        int isPremium = user.getPremium();
        if ( isPremium == 1 ){
            Map<String,String> resultMap = new HashMap<String,String>();
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.addHeader("Access-Control-Allow-Origin", "*");
            resultMap.put("result", "success");
            return new Gson().toJson(resultMap);
        }else{
            return "redirect:/f/redirectedUrl?url="+form.getWeb_page();
        }
    }

redirectedUrl controller is just for redirecting, but if the request is ajax request then i want to response the request as json.

How can I achieve this, thanks.

Edit : I can understand if request is ajax or not. My problem is if it is ajax i want to response json, if it is not then i want to redirect.

Sahin Yanlık
  • 1,171
  • 2
  • 11
  • 21
  • Many javascript frameworks inject "X-Requested-With" header. Refer to http://stackoverflow.com/questions/7042865/what-is-the-common-http-header-for-request-by-js-libs/7067675 – Sanj Mar 08 '16 at 07:21
  • I can understand if it is ajax or not. – Sahin Yanlık Mar 08 '16 at 07:23

2 Answers2

0

Use this code in your controller to identify if request is ajax or not and based on that you can add your logic.

boolean ajax = "XMLHttpRequest".equals(
                      getRequest().getHeader("X-Requested-With"));

You can decide it from header("X-Requested-With") of your httpRequest object.

Mitul Sanghani
  • 230
  • 1
  • 11
0
public ModelAndView getDetails(HttpServletRequest request, HttpServletRespone response) {


       if(ajax) {
        try {

new MappingJacksonHttpMessageConverter().write(object, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
        } catch(Exception e) {
              logger.error("Error when converting to json");
        }

        return null;
    } else {
        return new ModelAndView("viewName");
    }  
}
Sanj
  • 3,879
  • 2
  • 23
  • 26