I have a method in my controller annotated with @ResponseBody which produces JSON output. I've written a servlet filter (suggested by Jeremy Grelle) that gets called when requests are made ending in *.json. That filter also checks to see if there is a "callback" parameter with the request. If there is, it wraps the response output with the callback method.
The small issue I'm having now though is that the response still has a Content-Type of application/json, but it should be application/javascript. I've tried changing it in my filter before the chain.doFilter call, but my browser still shows a Content-Type header of application/json on the response.
This is my doFilter method:
Code:@SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Map<String, String[]> parms = httpRequest.getParameterMap(); /* * Check if parameter map contains a "callback" key indicating * a JSONP request is being made. If parameter map does not contain * a "callback" key, then filter will proceed without wrapping * JSON output with the callback method. */ if(parms.containsKey("callback")) { if(log.isDebugEnabled()) log.debug("Wrapping response with JSONP callback '" + parms.get("callback")[0] + "'"); OutputStream out = httpResponse.getOutputStream(); GenericResponseWrapper wrapper = new GenericResponseWrapper(httpResponse); wrapper.setContentType("application/javascript;charset=UTF-8"); chain.doFilter(request, wrapper); out.write(new String(parms.get("callback")[0] + "(").getBytes()); out.write(wrapper.getData()); out.write(new String(");").getBytes()); out.close(); } else { chain.doFilter(request, response); } }


Reply With Quote