精华内容
下载资源
问答
  • Tomcat7 CORS(资源跨域) 解决方案一

    千次阅读 2016-05-18 09:17:08
     它在维基百科上的定义是:跨域资源共享(CORS )是一种网络浏览器的技术规范,它为Web服务器定义了一种方式,允许网页从不同的域访问其资源。而这种访问是被同源策略所禁止的。CORS系统定义了一种浏览器和服务器...

    本文转载自:http://www.360doc.com/content/14/0920/14/7909375_411017244.shtml

    CORS介绍

       它在维基百科上的定义是:跨域资源共享(CORS )是一种网络浏览器的技术规范,它为Web服务器定义了一种方式,允许网页从不同的域访问其资源。而这种访问是被同源策略所禁止的。CORS系统定义了一种浏览器和服务器交互的方式来确定是否允许跨域请求。 它是一个妥协,有更大的灵活性,但比起简单地允许所有这些的要求来说更加安全。

       而W3C的官方文档目前还是工作草案,但是正在朝着W3C推荐的方向前进。

       简言之,CORS就是为了让AJAX可以实现可控的跨域访问而生的。


    Tomcat下的配置

       下载cors-filter-1.7.jar,java-property-utils-1.9.jar这两个库文件,放到lib目录下。(可在

    http://search.maven.org上查询并下载。)工程项目(如:geoserver)中web.xml中的配置如下:  


       <filter>

           <filter-name>CORS</filter-name>

           <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>

           <init-param>

            <param-name>cors.allowOrigin</param-name>

               <param-value>*</param-value>

           </init-param>

           <init-param>

            <param-name>cors.supportedMethods</param-name>

               <param-value>GET, POST, HEAD, PUT, DELETE</param-value>

           </init-param>

           <init-param>

            <param-name>cors.supportedHeaders</param-name>

               <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>

           </init-param>

           <init-param>

               <param-name>cors.exposedHeaders</param-name>

               <param-value>Set-Cookie</param-value>

           </init-param>

           <init-param>

               <param-name>cors.supportsCredentials</param-name>

               <param-value>true</param-value>

           </init-param>

       </filter>


       <filter-mapping>

           <filter-name>CORS</filter-name>

           <url-pattern>/*</url-pattern>

       </filter-mapping>

    展开全文
  • tomcat应用CORS跨域支持

    千次阅读 2018-10-19 16:06:07
    本次使用CORS支持跨域,支持cookie传递(用户登录认证) 后台过滤器代码:(借鉴:D:\apache-tomcat-7.0.54\lib\catalina.jar!\org\apache\catalina\filters\CorsFilter.class) jar包下载:...

    本次使用CORS支持跨域,支持cookie传递(用户登录认证)

    后台过滤器代码:(借鉴:D:\apache-tomcat-7.0.54\lib\catalina.jar!\org\apache\catalina\filters\CorsFilter.class)

    jar包下载:https://pan.baidu.com/s/1n6Ol7Hq1Tfzh-bUcv6nxAw

    package MyCorsFilter;
    
    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.HashSet;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Set;
    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.juli.logging.Log;
    import org.apache.juli.logging.LogFactory;
    import org.apache.tomcat.util.res.StringManager;
    
    /**
     * 处理跨域请求,支持cookie 
     * 来源:org.apache.catalina.filters.CorsFilter tomcat下lib catalina.jar
     * lib下的jar包是拷贝的tomcat下的lib目录中的
     * @author hqj
     */
    public final class MyCorsFilter implements Filter {
    	private static final Log log = LogFactory.getLog(MyCorsFilter.class);
    	private static final StringManager sm = StringManager.getManager("org.apache.catalina.filters");
    	private final Collection<String> allowedOrigins;
    	private boolean anyOriginAllowed;
    	private final Collection<String> allowedHttpMethods;
    	private final Collection<String> allowedHttpHeaders;
    	private final Collection<String> exposedHeaders;
    	private boolean supportsCredentials;
    	private long preflightMaxAge;
    	private boolean decorateRequest;
    	public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
    	public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
    	public static final String RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
    	public static final String RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
    	public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
    	public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
    	public static final String REQUEST_HEADER_ORIGIN = "Origin";
    	public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
    	public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
    	public static final String HTTP_REQUEST_ATTRIBUTE_PREFIX = "cors.";
    	public static final String HTTP_REQUEST_ATTRIBUTE_ORIGIN = "cors.request.origin";
    	public static final String HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST = "cors.isCorsRequest";
    	public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE = "cors.request.type";
    	public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS = "cors.request.headers";
    
    	public MyCorsFilter() {
    		this.allowedOrigins = new HashSet();
    		this.allowedHttpMethods = new HashSet();
    		this.allowedHttpHeaders = new HashSet();
    		this.exposedHeaders = new HashSet();
    	}
    
    	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    			throws IOException, ServletException {
    		if ((!(servletRequest instanceof HttpServletRequest)) || (!(servletResponse instanceof HttpServletResponse))) {
    			throw new ServletException(sm.getString("corsFilter.onlyHttp"));
    		}
    		HttpServletRequest request = (HttpServletRequest) servletRequest;
    		HttpServletResponse response = (HttpServletResponse) servletResponse;
    
    		CORSRequestType requestType = checkRequestType(request);
    		if (this.decorateRequest) {
    			decorateCORSProperties(request, requestType);
    		}
    		switch (requestType) {
    		case SIMPLE:
    			handleSimpleCORS(request, response, filterChain);
    			break;
    		case ACTUAL:
    			handleSimpleCORS(request, response, filterChain);
    			break;
    		case PRE_FLIGHT:
    			handlePreflightCORS(request, response, filterChain);
    			break;
    		case NOT_CORS:
    			handleNonCORS(request, response, filterChain);
    			break;
    		default:
    			handleInvalidCORS(request, response, filterChain);
    		}
    	}
    
    	public void init(FilterConfig filterConfig) throws ServletException {
    		parseAndStore("*", "GET,POST,HEAD,OPTIONS",
    				"Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers",
    				"", "true", "1800", "true");
    		if (filterConfig != null) {
    			String configAllowedOrigins = filterConfig.getInitParameter("cors.allowed.origins");
    
    			String configAllowedHttpMethods = filterConfig.getInitParameter("cors.allowed.methods");
    
    			String configAllowedHttpHeaders = filterConfig.getInitParameter("cors.allowed.headers");
    
    			String configExposedHeaders = filterConfig.getInitParameter("cors.exposed.headers");
    
    			String configSupportsCredentials = filterConfig.getInitParameter("cors.support.credentials");
    
    			String configPreflightMaxAge = filterConfig.getInitParameter("cors.preflight.maxage");
    
    			String configDecorateRequest = filterConfig.getInitParameter("cors.request.decorate");
    
    			parseAndStore(configAllowedOrigins, configAllowedHttpMethods, configAllowedHttpHeaders,
    					configExposedHeaders, configSupportsCredentials, configPreflightMaxAge, configDecorateRequest);
    		}
    	}
    
    	protected void handleSimpleCORS(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    			throws IOException, ServletException {
    		CORSRequestType requestType = checkRequestType(request);
    		if ((requestType != CORSRequestType.SIMPLE) && (requestType != CORSRequestType.ACTUAL)) {
    			throw new IllegalArgumentException(sm.getString("corsFilter.wrongType2",
    					new Object[] { CORSRequestType.SIMPLE, CORSRequestType.ACTUAL }));
    		}
    		String origin = request.getHeader("Origin");
    
    		String method = request.getMethod();
    		if (!isOriginAllowed(origin)) {
    			handleInvalidCORS(request, response, filterChain);
    			return;
    		}
    		if (!this.allowedHttpMethods.contains(method)) {
    			handleInvalidCORS(request, response, filterChain);
    			return;
    		}
    		if ((this.anyOriginAllowed) && (!this.supportsCredentials)) {
    			response.addHeader("Access-Control-Allow-Origin", "*");
    		} else {
    			response.addHeader("Access-Control-Allow-Origin", origin);
    		}
    		if (this.supportsCredentials) {
    			response.addHeader("Access-Control-Allow-Credentials", "true");
    		}
    		if ((this.exposedHeaders != null) && (this.exposedHeaders.size() > 0)) {
    			String exposedHeadersString = join(this.exposedHeaders, ",");
    			response.addHeader("Access-Control-Expose-Headers", exposedHeadersString);
    		}
    		filterChain.doFilter(request, response);
    	}
    
    	protected void handlePreflightCORS(HttpServletRequest request, HttpServletResponse response,
    			FilterChain filterChain) throws IOException, ServletException {
    		CORSRequestType requestType = checkRequestType(request);
    		if (requestType != CORSRequestType.PRE_FLIGHT) {
    			throw new IllegalArgumentException(sm.getString("corsFilter.wrongType1",
    					new Object[] { CORSRequestType.PRE_FLIGHT.name().toLowerCase() }));
    		}
    		String origin = request.getHeader("Origin");
    		if (!isOriginAllowed(origin)) {
    			handleInvalidCORS(request, response, filterChain);
    			return;
    		}
    		String accessControlRequestMethod = request.getHeader("Access-Control-Request-Method");
    		if ((accessControlRequestMethod == null) || (!HTTP_METHODS.contains(accessControlRequestMethod.trim()))) {
    			handleInvalidCORS(request, response, filterChain);
    			return;
    		}
    		accessControlRequestMethod = accessControlRequestMethod.trim();
    
    		String accessControlRequestHeadersHeader = request.getHeader("Access-Control-Request-Headers");
    
    		List<String> accessControlRequestHeaders = new LinkedList();
    		if ((accessControlRequestHeadersHeader != null) && (!accessControlRequestHeadersHeader.trim().isEmpty())) {
    			String[] headers = accessControlRequestHeadersHeader.trim().split(",");
    			for (String header : headers) {
    				accessControlRequestHeaders.add(header.trim().toLowerCase());
    			}
    		}
    		if (!this.allowedHttpMethods.contains(accessControlRequestMethod)) {
    			handleInvalidCORS(request, response, filterChain);
    			return;
    		}
    		if (!accessControlRequestHeaders.isEmpty()) {
    			for (String header : accessControlRequestHeaders) {
    				if (!this.allowedHttpHeaders.contains(header)) {
    					handleInvalidCORS(request, response, filterChain);
    					return;
    				}
    			}
    		}
    		if (this.supportsCredentials) {
    			response.addHeader("Access-Control-Allow-Origin", origin);
    
    			response.addHeader("Access-Control-Allow-Credentials", "true");
    		} else if (this.anyOriginAllowed) {
    			response.addHeader("Access-Control-Allow-Origin", "*");
    		} else {
    			response.addHeader("Access-Control-Allow-Origin", origin);
    		}
    		if (this.preflightMaxAge > 0L) {
    			response.addHeader("Access-Control-Max-Age", String.valueOf(this.preflightMaxAge));
    		}
    		response.addHeader("Access-Control-Allow-Methods", accessControlRequestMethod);
    		if ((this.allowedHttpHeaders != null) && (!this.allowedHttpHeaders.isEmpty())) {
    			response.addHeader("Access-Control-Allow-Headers", join(this.allowedHttpHeaders, ","));
    		}
    	}
    
    	private void handleNonCORS(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    			throws IOException, ServletException {
    		filterChain.doFilter(request, response);
    	}
    
    	private void handleInvalidCORS(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
    		String origin = request.getHeader("Origin");
    		String method = request.getMethod();
    		String accessControlRequestHeaders = request.getHeader("Access-Control-Request-Headers");
    
    		response.setContentType("text/plain");
    		response.setStatus(403);
    		response.resetBuffer();
    		if (log.isDebugEnabled()) {
    			StringBuilder message = new StringBuilder("Invalid CORS request; Origin=");
    
    			message.append(origin);
    			message.append(";Method=");
    			message.append(method);
    			if (accessControlRequestHeaders != null) {
    				message.append(";Access-Control-Request-Headers=");
    				message.append(accessControlRequestHeaders);
    			}
    			log.debug(message.toString());
    		}
    	}
    
    	public void destroy() {
    	}
    
    	protected static void decorateCORSProperties(HttpServletRequest request, CORSRequestType corsRequestType) {
    		if (request == null) {
    			throw new IllegalArgumentException(sm.getString("corsFilter.nullRequest"));
    		}
    		if (corsRequestType == null) {
    			throw new IllegalArgumentException(sm.getString("corsFilter.nullRequestType"));
    		}
    		switch (corsRequestType) {
    		case SIMPLE:
    			request.setAttribute("cors.isCorsRequest", Boolean.TRUE);
    
    			request.setAttribute("cors.request.origin", request.getHeader("Origin"));
    
    			request.setAttribute("cors.request.type", corsRequestType.name().toLowerCase());
    
    			break;
    		case ACTUAL:
    			request.setAttribute("cors.isCorsRequest", Boolean.TRUE);
    
    			request.setAttribute("cors.request.origin", request.getHeader("Origin"));
    
    			request.setAttribute("cors.request.type", corsRequestType.name().toLowerCase());
    
    			break;
    		case PRE_FLIGHT:
    			request.setAttribute("cors.isCorsRequest", Boolean.TRUE);
    
    			request.setAttribute("cors.request.origin", request.getHeader("Origin"));
    
    			request.setAttribute("cors.request.type", corsRequestType.name().toLowerCase());
    
    			String headers = request.getHeader("Access-Control-Request-Headers");
    			if (headers == null) {
    				headers = "";
    			}
    			request.setAttribute("cors.request.headers", headers);
    
    			break;
    		case NOT_CORS:
    			request.setAttribute("cors.isCorsRequest", Boolean.FALSE);
    
    			break;
    		}
    	}
    
    	protected static String join(Collection<String> elements, String joinSeparator) {
    		String separator = ",";
    		if (elements == null) {
    			return null;
    		}
    		if (joinSeparator != null) {
    			separator = joinSeparator;
    		}
    		StringBuilder buffer = new StringBuilder();
    		boolean isFirst = true;
    		for (String element : elements) {
    			if (!isFirst) {
    				buffer.append(separator);
    			} else {
    				isFirst = false;
    			}
    			if (element != null) {
    				buffer.append(element);
    			}
    		}
    		return buffer.toString();
    	}
    
    	protected CORSRequestType checkRequestType(HttpServletRequest request) {
    		CORSRequestType requestType = CORSRequestType.INVALID_CORS;
    		if (request == null) {
    			throw new IllegalArgumentException(sm.getString("corsFilter.nullRequest"));
    		}
    		String originHeader = request.getHeader("Origin");
    		if (originHeader != null) {
    			if (originHeader.isEmpty()) {
    				requestType = CORSRequestType.INVALID_CORS;
    			} else if (!isValidOrigin(originHeader)) {
    				requestType = CORSRequestType.INVALID_CORS;
    			} else {
    				String method = request.getMethod();
    				if ((method != null) && (HTTP_METHODS.contains(method))) {
    					if ("OPTIONS".equals(method)) {
    						String accessControlRequestMethodHeader = request.getHeader("Access-Control-Request-Method");
    						if ((accessControlRequestMethodHeader != null)
    								&& (!accessControlRequestMethodHeader.isEmpty())) {
    							requestType = CORSRequestType.PRE_FLIGHT;
    						} else if ((accessControlRequestMethodHeader != null)
    								&& (accessControlRequestMethodHeader.isEmpty())) {
    							requestType = CORSRequestType.INVALID_CORS;
    						} else {
    							requestType = CORSRequestType.ACTUAL;
    						}
    					} else if (("GET".equals(method)) || ("HEAD".equals(method))) {
    						requestType = CORSRequestType.SIMPLE;
    					} else if ("POST".equals(method)) {
    						String contentType = request.getContentType();
    						if (contentType != null) {
    							contentType = contentType.toLowerCase().trim();
    							if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES.contains(contentType)) {
    								requestType = CORSRequestType.SIMPLE;
    							} else {
    								requestType = CORSRequestType.ACTUAL;
    							}
    						}
    						// 如果contentType字段为可空就默认为是简单跨域,防止这个字段的缺失导出跨域失败 hqj 2018.10.19
    						else {
    							requestType = CORSRequestType.SIMPLE;
    						}
    					} else if (COMPLEX_HTTP_METHODS.contains(method)) {
    						requestType = CORSRequestType.ACTUAL;
    					}
    				}
    			}
    		} else {
    			requestType = CORSRequestType.NOT_CORS;
    		}
    		return requestType;
    	}
    
    	private boolean isOriginAllowed(String origin) {
    		if (this.anyOriginAllowed) {
    			return true;
    		}
    		return this.allowedOrigins.contains(origin);
    	}
    
    	private void parseAndStore(String allowedOrigins, String allowedHttpMethods, String allowedHttpHeaders,
    			String exposedHeaders, String supportsCredentials, String preflightMaxAge, String decorateRequest)
    			throws ServletException {
    		if (allowedOrigins != null) {
    			if (allowedOrigins.trim().equals("*")) {
    				this.anyOriginAllowed = true;
    			} else {
    				this.anyOriginAllowed = false;
    				Set<String> setAllowedOrigins = parseStringToSet(allowedOrigins);
    
    				this.allowedOrigins.clear();
    				this.allowedOrigins.addAll(setAllowedOrigins);
    			}
    		}
    		if (allowedHttpMethods != null) {
    			Set<String> setAllowedHttpMethods = parseStringToSet(allowedHttpMethods);
    
    			this.allowedHttpMethods.clear();
    			this.allowedHttpMethods.addAll(setAllowedHttpMethods);
    		}
    		if (allowedHttpHeaders != null) {
    			Set<String> setAllowedHttpHeaders = parseStringToSet(allowedHttpHeaders);
    
    			Set<String> lowerCaseHeaders = new HashSet();
    			for (String header : setAllowedHttpHeaders) {
    				String lowerCase = header.toLowerCase();
    				lowerCaseHeaders.add(lowerCase);
    			}
    			this.allowedHttpHeaders.clear();
    			this.allowedHttpHeaders.addAll(lowerCaseHeaders);
    		}
    		if (exposedHeaders != null) {
    			Set<String> setExposedHeaders = parseStringToSet(exposedHeaders);
    			this.exposedHeaders.clear();
    			this.exposedHeaders.addAll(setExposedHeaders);
    		}
    		if (supportsCredentials != null) {
    			this.supportsCredentials = Boolean.parseBoolean(supportsCredentials);
    		}
    		if (preflightMaxAge != null) {
    			try {
    				if (!preflightMaxAge.isEmpty()) {
    					this.preflightMaxAge = Long.parseLong(preflightMaxAge);
    				} else {
    					this.preflightMaxAge = 0L;
    				}
    			} catch (NumberFormatException e) {
    				throw new ServletException(sm.getString("corsFilter.invalidPreflightMaxAge"), e);
    			}
    		}
    		if (decorateRequest != null) {
    			this.decorateRequest = Boolean.parseBoolean(decorateRequest);
    		}
    	}
    
    	private Set<String> parseStringToSet(String data) {
    		String[] splits;
    		if ((data != null) && (data.length() > 0)) {
    			splits = data.split(",");
    		} else {
    			splits = new String[0];
    		}
    		Set<String> set = new HashSet();
    		if (splits.length > 0) {
    			for (String split : splits) {
    				set.add(split.trim());
    			}
    		}
    		return set;
    	}
    
    	protected static boolean isValidOrigin(String origin) {
    		// 去掉协议名称验证,防止 "192.168.2.225:8080"不通过 hqj 2018-10-19
    		return true;
    		/*
    		 * if (origin.contains("%")) { return false; } URI originURI; try { originURI =
    		 * new URI(origin); } catch (URISyntaxException e) { return false; } return
    		 * originURI.getScheme() != null;
    		 */
    	}
    
    	public boolean isAnyOriginAllowed() {
    		return this.anyOriginAllowed;
    	}
    
    	public Collection<String> getExposedHeaders() {
    		return this.exposedHeaders;
    	}
    
    	public boolean isSupportsCredentials() {
    		return this.supportsCredentials;
    	}
    
    	public long getPreflightMaxAge() {
    		return this.preflightMaxAge;
    	}
    
    	public Collection<String> getAllowedOrigins() {
    		return this.allowedOrigins;
    	}
    
    	public Collection<String> getAllowedHttpMethods() {
    		return this.allowedHttpMethods;
    	}
    
    	public Collection<String> getAllowedHttpHeaders() {
    		return this.allowedHttpHeaders;
    	}
    
    	protected static enum CORSRequestType {
    		SIMPLE, ACTUAL, PRE_FLIGHT, NOT_CORS, INVALID_CORS;
    
    		private CORSRequestType() {
    		}
    	}
    
    	public static final Collection<String> HTTP_METHODS = new HashSet(
    			Arrays.asList(new String[] { "OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT" }));
    	public static final Collection<String> COMPLEX_HTTP_METHODS = new HashSet(
    			Arrays.asList(new String[] { "PUT", "DELETE", "TRACE", "CONNECT" }));
    	public static final Collection<String> SIMPLE_HTTP_METHODS = new HashSet(
    			Arrays.asList(new String[] { "GET", "POST", "HEAD" }));
    	public static final Collection<String> SIMPLE_HTTP_REQUEST_HEADERS = new HashSet(
    			Arrays.asList(new String[] { "Accept", "Accept-Language", "Content-Language" }));
    	public static final Collection<String> SIMPLE_HTTP_RESPONSE_HEADERS = new HashSet(Arrays.asList(new String[] {
    			"Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma" }));
    	public static final Collection<String> SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES = new HashSet(
    			Arrays.asList(new String[] { "application/x-www-form-urlencoded", "multipart/form-data", "text/plain" }));
    	public static final String DEFAULT_ALLOWED_ORIGINS = "*";
    	public static final String DEFAULT_ALLOWED_HTTP_METHODS = "GET,POST,HEAD,OPTIONS";
    	public static final String DEFAULT_PREFLIGHT_MAXAGE = "1800";
    	public static final String DEFAULT_SUPPORTS_CREDENTIALS = "true";
    	public static final String DEFAULT_ALLOWED_HTTP_HEADERS = "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers";
    	public static final String DEFAULT_EXPOSED_HEADERS = "";
    	public static final String DEFAULT_DECORATE_REQUEST = "true";
    	public static final String PARAM_CORS_ALLOWED_ORIGINS = "cors.allowed.origins";
    	public static final String PARAM_CORS_SUPPORT_CREDENTIALS = "cors.support.credentials";
    	public static final String PARAM_CORS_EXPOSED_HEADERS = "cors.exposed.headers";
    	public static final String PARAM_CORS_ALLOWED_HEADERS = "cors.allowed.headers";
    	public static final String PARAM_CORS_ALLOWED_METHODS = "cors.allowed.methods";
    	public static final String PARAM_CORS_PREFLIGHT_MAXAGE = "cors.preflight.maxage";
    	public static final String PARAM_CORS_REQUEST_DECORATE = "cors.request.decorate";
    }
    

    应用web.xml配置这个过滤器(如果想实现tomcat下所有应用跨域,可配置到 D:\apache-tomcat-7.0.54\conf\web.xml):

    <!--跨域过滤器,支持cookie传递-->
    	<filter>
    		<filter-name>CorsFilter</filter-name>
    		<filter-class>MyCorsFilter.MyCorsFilter</filter-class>
    		<init-param>
    		  <param-name>cors.allowed.origins</param-name>
    		  <param-value>*</param-value>
    		</init-param>
    		<init-param>
    		  <param-name>cors.allowed.methods</param-name>
    		  <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    		</init-param>
    		<init-param>
    		  <param-name>cors.allowed.headers</param-name>
    		  <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
    		</init-param>
    		<init-param>
    		  <param-name>cors.exposed.headers</param-name>
    		  <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    		</init-param>
    		<init-param>
    		  <param-name>cors.support.credentials</param-name>
    		  <param-value>true</param-value>
    		</init-param>
    		<init-param>
    		  <param-name>cors.preflight.maxage</param-name>
    		  <param-value>100</param-value>
    		</init-param>
      </filter>
      <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>

    前端脚本代码:

    $.ajax({
                type: 'post',
                url: "http://192.168.3.125:8080/test/query",
                contentType: "application/json",
                data: JSON.stringify({
                    "paras": { "name": "xiaoming" } }
                }),
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (res) {
                    console.log("成功了", arguments);
                },
                error: function () {
                    console.error("失败了", arguments);
                }
            })

     

    展开全文
  • 由于应用需要跨域请求数据,所以特别查了一下,Tomcat7.0的cors可以配置Access-Control-Allow-Origin:"*", 但是我按照文档配置以后却没有生效,一下是代码和效果,求高手指导下~小弟感激不尽 首先是在conf/...
  • tomcat 默认安装目录 C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib)。 java web 工程项目中web.xml中的配置 <filter-name>CORS <filter-class>...

    首先我们先看下什么是 CORS(跨来源资源共享/跨域资源共享)

    跨域资源共享(CORS )是一种网络浏览器的技术规范,它为Web服务器定义了一种方式,允许网页从不同的域访问其资源。简单来说就是可让 A 网域向 B 网域发出跨网域的 AJAX 请求。而这种访问是被同源策略所禁止的。

    举个例子,假设我们有两个网址,且来自两台不同的主机,分别为:http://www.website1.com http://www.website2.com 也因为他们来自于不同的主机,它们会被浏览器认定为来自不同的来源,

    或是在这种情况下: http://www.website.comhttps://www.website.com 这两个网址还是属于不同的来源,因为他们的协议是不同的。

    其次我们看下如何使Tomcat下的 java web 项目支持跨域请求。

    Tomcat下的配置

    下载cors-filter-1.7.jar,java-property-utils-1.9.jar这两个库文件,(下载链接:http://www.oschina.net/code/piece_full?code=58292&piece=86852#86852)放到lib目录下。(tomcat 默认安装目录 C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib)。

    java web 工程项目中web.xml中的配置

     <filter>
           <filter-name>CORS</filter-name>
           <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
           <init-param>
            <param-name>cors.allowOrigin</param-name>
               <param-value>*</param-value>
           </init-param>
           <init-param>
            <param-name>cors.supportedMethods</param-name>
               <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
           </init-param>
           <init-param>
            <param-name>cors.supportedHeaders</param-name>
               <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
           </init-param>
           <init-param>
               <param-name>cors.exposedHeaders</param-name>
               <param-value>Set-Cookie</param-value>
           </init-param>
           <init-param>
               <param-name>cors.supportsCredentials</param-name>
               <param-value>true</param-value>
           </init-param>
       </filter>
    
       <filter-mapping>
           <filter-name>CORS</filter-name>
           <url-pattern>/*</url-pattern>
       </filter-mapping>
    
    

    转载于:https://my.oschina.net/fltsp/blog/719590

    展开全文
  • All these contents are provided by a Tomcat Container, on port 8080. When i browse with http://localhost:8080/shaka-player-master/demo/index1.html (browser Firefox 50.1.0, Chrome Version 55.0.2883.75...
  • Tomcat6、tomcat7 跨域设置

    千次阅读 2015-11-18 16:16:06
    需要下载两个jar文件,cors-filter-1.7.jar,java-property-utils-1.9.jar这两...放到tomcat lib目录下面,不是项目的lib目录,然后配置项目的web.xml,添加如下内容,注意filter位置,应该放在第一位<!-- 实现跨域 -->

    需要下载两个jar文件,cors-filter-1.7.jar,java-property-utils-1.9.jar这两个库文件,http://download.csdn.net/detail/csr0312/9280097
    放到tomcat lib目录下面,不是项目的lib目录,然后配置项目的web.xml,添加如下内容,注意filter位置,应该放在第一位

    <!-- 实现跨域 -->
        <filter>
            <filter-name>CORS</filter-name>
            <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
            <init-param>
                <param-name>cors.allowOrigin</param-name>
                <param-value>*</param-value>
            </init-param>
            <init-param>
                <param-name>cors.supportedMethods</param-name>
                <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
            </init-param>
            <init-param>
                <param-name>cors.supportedHeaders</param-name>
                <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
            </init-param>
            <init-param>
                <param-name>cors.exposedHeaders</param-name>
                <param-value>Set-Cookie</param-value>
            </init-param>
            <init-param>
                <param-name>cors.supportsCredentials</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>CORS</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    展开全文
  • 05:06:00.491 | INFO | host-startStop-1 | o.a.c.AtmosphereFramework | Atmosphere is using async support: org.atmosphere.container.Tomcat7AsyncSupportWithWebSocket running under container: Apache Tomcat...
  • cors-filter 2.4 com.thetransactioncompany java-property-utils 1.9.1 1.导入maven的两个jar包 2.在文件服务器的配置文件中,修改web.xml,加入拦截 CORS com.thetr
  • 大约十年前,Firesheep制造了一个大新闻。多年来,安全人员已经了解了公共WiFi网络的危害,但直到有人创建了这个用户友好的Firefox扩展插件之后,这个安全...但是,使用CORS,postMessage和其他一些很酷的东西,有时...
  • cors解决跨域问题

    2016-12-09 10:54:12
    cors跨域: 什么是跨域: ...第一步:tomcat7支持 Tomcat下的配置  下载cors-filter-1.7.jar,java-property-utils-1.9.jar这两个库文件,放到lib目录下。 第二步:在web.xml文件中添加filter,这
  • Enable CORS for RESTful API

    2021-01-08 12:55:59
    [ERROR] Failed to execute goal org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:redeploy (default-cli) on project opengrok-web: Cannot invoke Tomcat manager: Connection reset -> [Help 1] [ERROR] ...
  • 因项目需要,今天研究了下cors跨域post请求登录操作,参考了官方及网上案例,实现过程如下:1、环境:java web(ssm)项目+tomcat7/8。2、服务端配置:下载并载入cors-filter-2.2.1.jar包(路径:项目lib文件夹中),...
  • <p>Filter implementation has advantage to be compatible with Tomcat and WildFly. Otherwise, maybe with JAX-RS ContainerResponseFilter.</p><p>该提问来源于开源项目:apiman/apiman</p></div>
  • Tomcat 6 跨域的支持

    2016-11-08 16:36:00
    1.添加2个jar包 这个我是自己保存在云端的 cors-filter-1.7.jar ...tomcat7以后自动支持 2.tomcat 下面的web.xml 在最前面添加下面的filter <filter> <filter-name>CORS</filter-name> ...
  • tomcat7CORS(跨域资源共享) 的配置 CORS介绍  它在维基百科上的定义是:跨域资源共享(CORS )是一种网络浏览器的技术规范,它为Web服务器定义了一种方式,允许网页从不同的域访问其资源。而这种访问...
  • tomcat7发布的webservice接口在被用户跨域访问的时候报错 (No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://xcx1.winhui.net' is therefore not allowed access....
  • tomcat7发布的webservice接口在被用户跨域访问的时候报错(No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://xcx1.winhui.net' is therefore not allowed access.)...
  • 项目编译后可直接部署于tomcat7,mysql5.x中运行,支持jdk7/jdk8,如要使用tomcat8及以上版本可能会有报错,请自行修正(所以建议第一次运行在tomcat7中) 注意事项 建议tomcat7,tomcat8或以上版本可能会有报错...
  • rest 风格架构,拥有token用户验证,cors跨域处理,完善的异常处理,直接导入eclipse,启动命令:tomcat7:run rom采用hibernate
  • js资源跨域访问的问题

    千次阅读 2017-01-05 17:14:41
    1.Tomcat6、Tomcat7发布的资源跨域设置: 需要下载cors-filter-1.7.jar、Java-property-utils-1.9.jar这两个库文件,放到tomcat的lib目录下,然后配置项目的web.xml文件,在web.xml中添加如下内容:(注
  • 环境:Java7+Tomcat8.0.20+Geoserver2.7.6(war版)解决步骤:1、修改%CATALINA_HOME%/webapps/geoserver/WEB-INF/web.xml文件内容: 在filter标签部分添加代码:&lt;filter&gt; &lt;filter-name&...
  • - Change cors.support.credentials to false, so CorsFilter works on tomcat 8 <h1>Checks <ul><li>[ ] Runs on Heroku.</li><li>[ ] Follows <a href="http://chris.beams.io/posts/git-commit/">7 rules of ...
  • GeoServer WFS Error

    2020-12-29 09:02:07
    CORS enabled on Tomcat8, JSONP enabled on GeoServer <p>Thank you very much for all your work and any help. <p><img alt="image" src=...
  • 7. Logout from My Account 8. Go to forgot password on the login screen 9. Enter username for an account to recover the password, select "Recover with Security Questions" and click submit 10....
  • Create ImagingStudy Error

    2020-11-26 08:24:57
    <div><p>Hi, Jamesagnew: ...2014-11-14 12:48:59.378 [http-8000-6] [192.168.100.7] [Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36] INFO o.h.e.i....
  • Cross-Origin Request Blocked

    2020-12-05 11:29:45
    -Bimserver1.3.1 with tomcat7 -MyWebApplication with apache <p>My main operating system where i try to connect is windows, and i use a bridge connexion (i can connect to Bimserver and to my web ...
  • React学习笔记_利用cors实现ajax跨域_Tomcat 获取跨域Authorization React学习笔记_ReactRedux应用使用AsyncAwait React学习笔记_动态注入reducer React学习笔记_export和import总结 React学习笔记_安装...
  • HttpOnly}{X-Content-Type-Options: nosniff}{X-Frame-Options: DENY}{X-Request-Id: 7fd4f409-0bd5-420c-932e-77f5cec8e4b7}{X-Runtime: 0.071366}{X-Ua-Compatible: IE=edge}{X-Xss-Protection: 1; mode=...
  • -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true' - '-Dorg.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH=true' - '-Dcom.datastax.driver.FORCE_NIO=...
  • [INFO] Keycloak Tomcat 7 SAML Integration ................. SUCCESS [ 0.079 s] [INFO] Keycloak Wildfly SAML Adapter ...................... SUCCESS [ 0.167 s] [INFO] KeyCloak Authz: Client API ...........

空空如也

空空如也

1 2 3
收藏数 55
精华内容 22
关键字:

tomcat7cors