|
| 1 | +package org.nutz.mvc.filter; |
| 2 | + |
| 3 | +import org.nutz.lang.Strings; |
| 4 | +import org.nutz.log.Log; |
| 5 | +import org.nutz.log.Logs; |
| 6 | +import org.nutz.mvc.ActionContext; |
| 7 | +import org.nutz.mvc.ActionFilter; |
| 8 | +import org.nutz.mvc.View; |
| 9 | +import org.nutz.mvc.view.HttpServerResponse; |
| 10 | +import org.nutz.mvc.view.VoidView; |
| 11 | + |
| 12 | +import javax.servlet.http.HttpServletResponse; |
| 13 | + |
| 14 | +/** |
| 15 | + * 如果是OPTIONS请求,那么返回自定义的Access-Control-Allow-*头部 |
| 16 | + */ |
| 17 | +public class CrossOriginFilter implements ActionFilter { |
| 18 | + |
| 19 | + private static final Log log = Logs.get(); |
| 20 | + |
| 21 | + protected String origin; |
| 22 | + protected String methods; |
| 23 | + protected String headers; |
| 24 | + protected String credentials; |
| 25 | + |
| 26 | + public CrossOriginFilter() { |
| 27 | + this("*", "get, post, put, delete, options", "origin, content-type, accept", "true"); |
| 28 | + } |
| 29 | + |
| 30 | + public CrossOriginFilter(String origin, String methods, String headers, String credentials) { |
| 31 | + this.origin = origin; |
| 32 | + this.methods = methods; |
| 33 | + this.headers = headers; |
| 34 | + this.credentials = credentials; |
| 35 | + } |
| 36 | + |
| 37 | + public View match(ActionContext ac) { |
| 38 | + if ("OPTIONS".equals(ac.getRequest().getMethod())) { |
| 39 | + if (log.isDebugEnabled()) |
| 40 | + log.debugf("Feedback -- [%s] [%s] [%s] [%s]", origin, methods, headers, credentials); |
| 41 | + HttpServletResponse resp = ac.getResponse(); |
| 42 | + if (!Strings.isBlank(origin)) |
| 43 | + resp.addHeader("Access-Control-Allow-Origin", origin); |
| 44 | + if (!Strings.isBlank(methods)) |
| 45 | + resp.addHeader("Access-Control-Allow-Methods", methods); |
| 46 | + if (!Strings.isBlank(headers)) |
| 47 | + resp.addHeader("Access-Control-Allow-Headers", headers); |
| 48 | + if (!Strings.isBlank(credentials)) |
| 49 | + resp.addHeader("Access-Control-Allow-Credentials", credentials); |
| 50 | + return new VoidView(); |
| 51 | + } |
| 52 | + return null; |
| 53 | + } |
| 54 | +} |
0 commit comments