JSP ajax跨域问题 怎么处理 原因:CORS 头缺少 'Access-Control-Allow-Origin')。 ajax http 415

时间:2022-08-17 05:58:48

/**
* Project Name:cm2mManage
* File Name:CrossSiteFilter.java
* Package Name:com.yoxnet.serverframework.base
* Date:2016年4月27日下午4:52:51
* Copyright (c) 2016, chenzhou1025@126.com All Rights Reserved.
*
*/

package com.zhl.sms.filter;

import java.io.IOException;
import java.util.Enumeration;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* ClassName:CrossSiteFilter <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2016年4月27日 下午4:52:51 <br/>
* @author YYC
* @version
* @since JDK 1.6
* @see
*/
public class CrossSiteFilter implements Filter{

private Logger logs = LoggerFactory.getLogger(this.getClass());

@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
Enumeration e = req.getHeaderNames();
// String headValue = "";
// while(e.hasMoreElements()){
// headValue = (String) e.nextElement();
// String value = req.getHeader(headValue);
// System.out.println(headValue+"="+value);
// }
logs.debug(">>>>>>>>>>>>>>>本次请求的header信息如下:");
while(e.hasMoreElements()){
String name = (String) e.nextElement();
String value = req.getHeader(name);
logs.debug(name+"="+value);
}
logs.debug(">>>>>>>>>>>>>>>本次请求的header信息结束");
HttpServletResponse resp = (HttpServletResponse) response;
// HttpSession session = req.getSession();
resp.addHeader("Access-Control-Allow-Origin", "*");
// resp.addHeader("Access-Control-Allow-Origin", "http://192.168.1.170");
resp.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
resp.addHeader("Access-Control-Allow-Credentials","true");
resp.addHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
resp.addHeader("Access-Control-Max-Age", "1800");//30 min
if (req.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(req.getMethod())) {

}
chain.doFilter(request, response);
}

@Override
public void destroy() {

}

}

xml配置中:

<filter>
<filter-name>crossSiteFilter</filter-name>
<filter-class>com.zhl.sms.filter.CrossSiteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>crossSiteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>