On Using JS to Solve Cross-domain Problems
Server resolves cross-domain requests, intercepts requests and resets response headers
Server-side interceptor
package com.silence.util; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; 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.slf4j.Logger; import org.slf4j.LoggerFactory; public class CrossOriginFilter implements Filter { private String allowDomain = ""; private static final Logger logger = LoggerFactory.getLogger(CrossOriginFilter.class); public void init(FilterConfig filterConfig) throws ServletException { allowDomain = filterConfig.getInitParameter("domain"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { logger.info("CrossOriginFilter Cross-domain request interception " + new SimpleDateFormat("YYYY-DD-MM").format(new Date())); HttpServletResponse httpResponse = (HttpServletResponse) response; setAccessControl(httpResponse); chain.doFilter(request, response); } public void destroy() { } /** *Using Ajax to request data from pages in one domain name to pages in another domain name will encounter cross-domain problems. Another domain name must be added in response *Access-Control-Allow-Origin Only by header can the former get the data successfully. *Only when the header Access-Control-Allow-Origin is included in the response of the target page and its value has our own domain name, *The browser allows us to get the data on its page for further processing. *If its value is set to *, it means that anyone can use it. */ private void setAccessControl(HttpServletResponse response) { response.setHeader("Access-Control-Allow-Origin", allowDomain); response.setHeader("Access-Control-Allow-Credentials", "true"); String headers = "Origin, Accept-Language, Accept-Encoding,X-Forwarded-For, Connection, Accept, User-Agent, Host, Referer,Cookie, Content-Type, Cache-Control"; response.setHeader("Access-Control-Allow-Headers", headers); response.setHeader("Access-Control-Request-Method", "GET,POST"); } }
Configuration in web.xml
<filter> <filter-name>CrossOriginFilter</filter-name> <filter-class>com.silence.util.CrossOriginFilter</filter-class> <init-param> <param-name>domain</param-name> <param-value>*</param-value> </init-param> </filter> <filter-mapping> <filter-name>CrossOriginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
By default, all requests are intercepted, allowing requests from any link
** If you are interested in discussing with us, please join our group. Remember to write my name ID: Big MoreKT: 984370849 when you join the group.