vendredi 27 février 2015

JQuery invoking Spring Rest service: Cross-Origin issue vs ParseError

I am trying to invoke a REST service with jquery, but either I get a Cross Origin Problem (when I do not specify the datatype in jquery invocation) or a parseerror (when I do).


JQuery use:



function requestData() {
$.ajax({
url: 'http://ift.tt/1DeUCtn',
type: 'GET',
dataType:"jsonp",
success: function(json) {
console.log("OK");
console.log(json);
},
error: function(xhr, status, error) {
console.log("NO");
console.log("STATUS:" + status);
}
});
}


Server side, I am using Spring REST this way:



@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody List<Entity> getEntities() {
List<Entity> found = controller.findEntities();

return found;
}


The serialized data are correct, as invoking the REST API in the browser produces correct JSON.


I also added the following CORS filter, which does NOT seem to be executed, as "AA" is not printed:



@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {

System.out.println("AA");

HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods",
"POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}
public void destroy() { }
}


My web.xml:



<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
<filter-name>simpleCORSFilter</filter-name>
<filter-class>org.lh.xxx.web.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>simpleCORSFilter</filter-name>
<servlet-name>/*</servlet-name>
</filter-mapping>
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>


What's wrong with it?


Aucun commentaire:

Enregistrer un commentaire