When we request a RESTful Web service with JS, there is usually a cross-domain unreachable problem, that is, the value we want is not normal. Jsonp is a way to solve the problem. However, we want to access the RESTful Web service just like the usual Ajax approach, without having to do a JSONP and callback each. This requires us to make some settings on the server, below I use a simple filter to explain, other more complex situation according to their own needs to change.
Import java.io.IOException;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.http.HttpServletResponse;
Import org.springframework.stereotype.Component; public class Simplecorsfilter implements Filter { public void Dofilter (ServletRequest req, Servletresp Onse Res, Filterchain chain) throws IOException, servletexception {
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 de Stroy () {}}
- Access-control-allow-origin to allow which Origin to initiate cross-domain requests. This is set to "*" to indicate that all is allowed, usually set to all unsafe, preferably specified.
- Access-control-allow-methods is the method that allows the request.
- Access-control-max-age indicates that no further pre-inspection requests are required in the number of seconds to cache the result
- Access-control-allow-headers indicates that it allows cross-domain requests to contain Content-type headers, the X-requested-with set here to represent AJAX requests