title: how to handle both XmlHttpRequest(AJAX) and regular http requests in one spring mvc method?
body: <p>currently my solution is </p>
  
  <p>For AJAX:</p>
  
  <pre><code>@RequestMapping(value = "/verify", method = {RequestMethod.GET},
      headers = "x-requested-with=XMLHttpRequest")
      public 
      @ResponseBody userTO
      void verifyForXHR(@RequestParam(required = true) String code,
              HttpServletRequest request, HttpServletResponse response) {
          try {
              UserTO userTO = new SomeService().verifyEmail(code);
              return userTO;
          } catch (ExceptionABC ex) {
              response.setStatus(response.SC_BAD_REQUEST);
              return null;
          } catch (RuntimeException ex) {
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                return null;
          }
  
      }
  </code></pre>
  
  <p>For regular http requests:</p>
  
  <pre><code>@RequestMapping(value = "/verify", method = {RequestMethod.GET})
      public ModelAndView verify(@RequestParam(required = true) String code) {
          //get user to
          try {
              ModelAndView mav = new ModelAndView();
              UserTO userTO = new SomeService().verifyEmail code);
  
              mav.setViewName("somegoodpage");
              mav.addObject("user", userTO);
              return mav;
          } catch (ExceptionABC ex) {
                  logger.error(ex, ex);
                  ModelAndView mav = new ModelAndView("error page);
                  return mav;
              }
  
          } catch (RuntimeException ex) {
              logger.error(ex.toString(), ex);
              ModelAndView mav = new ModelAndView("another error page");
              return mav;
          }
  
      }
  </code></pre>
  
  <p>It would be super if I can merge them into one method. Please note they have different return type. The caller for AJAX requests are JavaScript so it needs JSON as http response body media type. For regular http requests, it needs a view(page) to be returned. Any suggestions would be greatly appreciated!</p>