使用拦截器去做跨域访问
在验证时,需要在header里面传入token和userId来进行验证,所以需要特别注意的就是要在代码中将这两个参数加入,否则会出现异常
package com.xw.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author 12561 */ public class CrossDomainInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.addHeader("Access-Control-Allow-Origin","*"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS"); response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization,userId,token"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * @param request * @param response * @param handler 拦截的对象 * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
<mvc:interceptors> <!--登录拦截器--> <mvc:interceptor> <!-- 需拦截的地址 --> <!-- 拦截所有/manage --> <mvc:mapping path="/manage/**" /> <!--登录和退出登录的方法不需要拦截--> <mvc:exclude-mapping path="/manage/user/tologin"/> <mvc:exclude-mapping path="/manage/user/login"/> <mvc:exclude-mapping path="/manage/user/exit"/> <bean class="com.xw.interceptor.LoginInterceptor"/> </mvc:interceptor> <!--跨域拦截器--> <mvc:interceptor> <!-- 需拦截的地址 --> <mvc:mapping path="/api*/**" /> <bean class="com.xw.interceptor.CrossDomainInterceptor"/> </mvc:interceptor> </mvc:interceptors>
拦截的是所有以api开头的接口,设置完之后就完成啦