看到群里很多跨域问题,自己开发中也有此类需求,看到前人写了些介绍,按照提示做了实战,直接上代码参考:
public class CorsInterceptor implements Interceptor { @Override public void intercept(Invocation inv) { inv.invoke(); HttpServletResponse response = inv.getController().getResponse(); response.setContentType("application/json;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me"); } }
控制器中应用:
@Before(CorsInterceptor.class) public class TstController extends Controller { @Inject IteService srv; public void test() { String mUrlParam = getPara("Parameter"); Ret ret = null; if (getRequest().getMethod().equals("OPTIONS")) { ret = Ret.ok("result", "options"); renderJson(ret); return; } String jsonString = HttpKit.readData(getRequest()); if (jsonString != null && jsonString != "") { try { Kv kv = FastJson.getJson().parse(jsonString, Kv.class); ret = Ret.ok("result", mUrlParam); renderJson(ret); } catch (Exception e) { ret = Ret.fail("result", "失败"); renderJson(ret); return; } } else { ret = Ret.fail("result", mUrlParam); return; } } }