加一个类, 然后把它配到web.xml, 放在其他filter之前
package org.nutz.mvc.filter;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.View;
import org.nutz.mvc.view.VoidView;
import java.io.FileFilter;
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;
/**
* 如果是OPTIONS请求,那么返回自定义的Access-Control-Allow-*头部
*/
public class WebCrossOriginFilter implements Filter {
private static final Log log = Logs.get();
protected String origin;
protected String methods;
protected String headers;
protected String credentials;
public WebCrossOriginFilter() {
this("*", "GET, POST, PUT, DELETE, OPTIONS, PATCH", "Origin, Content-Type, Accept, X-Requested-With", "true");
}
public WebCrossOriginFilter(String origin, String methods, String headers, String credentials) {
this.origin = origin;
this.methods = methods;
this.headers = headers;
this.credentials = credentials;
}
public View match(ActionContext ac) {
HttpServletResponse resp = ac.getResponse();
if (!Strings.isBlank(origin))
resp.setHeader("Access-Control-Allow-Origin", origin);
if (!Strings.isBlank(methods))
resp.setHeader("Access-Control-Allow-Methods", methods);
if (!Strings.isBlank(headers))
resp.setHeader("Access-Control-Allow-Headers", headers);
if (!Strings.isBlank(credentials))
resp.setHeader("Access-Control-Allow-Credentials", credentials);
if ("OPTIONS".equals(ac.getRequest().getMethod())) {
if (log.isDebugEnabled())
log.debugf("Feedback -- [%s] [%s] [%s] [%s]", origin, methods, headers, credentials);
return new VoidView();
}
return null;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse)response;
if (!Strings.isBlank(origin))
resp.setHeader("Access-Control-Allow-Origin", origin);
if (!Strings.isBlank(methods))
resp.setHeader("Access-Control-Allow-Methods", methods);
if (!Strings.isBlank(headers))
resp.setHeader("Access-Control-Allow-Headers", headers);
if (!Strings.isBlank(credentials))
resp.setHeader("Access-Control-Allow-Credentials", credentials);
if ("OPTIONS".equals(((HttpServletRequest)request).getMethod())) {
if (log.isDebugEnabled())
log.debugf("Feedback -- [%s] [%s] [%s] [%s]", origin, methods, headers, credentials);
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}