Previously, I used jsonp to solve cross-domain problems, and now I used CORS to implement cross-domain requests to solve Java cross-domain problems:
The main code is as follows
package com.hy.fliter;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.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.httpclient.HttpStatus;/*** Created by WangShuai on 2016/7/30.*/public class CorsFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException { }@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletResponse response = (HttpServletResponse) servletResponse;HttpServletRequest request = (HttpServletRequest) servletRequest;// Specify that other domain names are allowed to access response.setHeader("Access-Control-Allow-Origin", "*");// Response type response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");// Response header set response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token"); if ("OPTIONS".equals(request.getMethod())){response.setStatus(HttpStatus.SC_NO_CONTENT);}filterChain.doFilter(servletRequest, servletResponse);}@Overridepublic void destroy() { }}The web.xml code is configured as follows
<filter><filter-name>cors</filter-name><filter-class>com.hy.fliter.CorsFilter</filter-class></filter><filter-mapping><filter-name>cors</filter-name><url-pattern>/*</url-pattern></filter-mapping>
The above is the method of using CORS to implement cross-domain requests for JavaWeb that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!