设置请求头解决浏览器同源问题,ajx跨域获取cookie问题

思想: 添加过滤器 设置请求头 代码如下 

 

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.HttpServletResponse;


public class CorsFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        String []  allowDomain= {"http://localhost:8082","http://localhost:8081","http://localhost:8181","http://localhost:8180"};
        Set<String> allowedOrigins= new HashSet<String>(Arrays.asList(allowDomain));
        String originHeader=((HttpServletRequest) req).getHeader("Origin");
        if (allowedOrigins.contains(originHeader)){
            ((HttpServletResponse) res).setHeader("Access-Control-Allow-Origin", originHeader);
            ((HttpServletResponse) res).setContentType("application/json;charset=UTF-8");
            ((HttpServletResponse) res).setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            ((HttpServletResponse) res).setHeader("Access-Control-Max-Age", "3600");
            //表明服务器支持的所有头信息字段
            ((HttpServletResponse) res).setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
            //如果要把Cookie发到服务器,需要指定Access-Control-Allow-Credentials字段为true;
            ((HttpServletResponse) res).setHeader("Access-Control-Allow-Credentials", "true"); 
            ((HttpServletResponse) res).setHeader("XDomainRequestAllowed","1");
            
        }
        chain.doFilter(req, res);

 


    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

}

web.xml设置拦截器

<!-- CORS拦截器 -->
    <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.deppon.vas.common.framework.cors.CorsFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

解决同源问题之后,接下来就是解决访问的cookie问题

思路 从shiro获取登陆成功的session 然后防止缓存 如jedis 之后将sessionid放入cookie 添加至response 返回页面 ,然后设置ajax跨域,这样同一域名下就可以获取到redis中的session信息

代码如下

  @Override
    protected boolean onLoginSuccess(AuthenticationToken token,Subject subject, ServletRequest request, ServletResponse response)throws Exception {

      HttpServletRequest httpRequest = (HttpServletRequest) request;
      HttpServletResponse httpResponse = (HttpServletResponse) response;
    // 不是ajax请求
    if (!AJAX_HEADER_MATH.equalsIgnoreCase(httpRequest.getHeader(AJAX_HEADER))) {
           //执行重定向操作
           issueSuccessRedirect(request, response);
    } else {
        
        /**用于跨域session传递start*/
        //获取session
        Session session = subject.getSession();
        //获取sessionId
        String sessionId =  session.getId().toString();
        Cookie cookied = CookieUtil.getCookie(sessionId, httpRequest);
        if (cookied != null) {
            // 修改cookie时间戳
            cookied.setValue(sessionId);
        } else {
            // 重新new一个Cookie
            cookied = new Cookie(Constance.VAS_SESSIONID, sessionId);
        }
        //默认值是-1,表示关闭浏览器,cookie就会消失。
//        cookied.setMaxAge(-1);
        cookied.setPath("/");// 同一个域名所有url cookie共享
        cookied.setDomain("");
        //30分钟失效
        cookied.setMaxAge(NumConstance.EXPIRE_TIME);//不写入磁盘,只写入内存,只有在当前页面有用,浏览器关闭立即失效
        httpResponse.addCookie(cookied);
        /**用于跨域session传递end*/
        httpResponse.setCharacterEncoding("UTF-8");
        PrintWriter out = httpResponse.getWriter();
        out.println("{success:true,message:'loginSuccess'}");//登录成功
        out.flush();
        out.close();

    }
public class CookieUtil {
    
    /**
     * 获取HttpCookie对象,根据传入的cookie的name值获取, 参数可以通过
     * @param name
     * @param request
     * @return
     */
    public static Cookie getCookie(String name,HttpServletRequest request) {
        if (StringUtils.isBlank(name)) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (int i=cookies.length-1; i >=0; i--) {
                if (name.equals(cookies[i].getName())) {
                    return cookies[i];
                }
            }
        }
        return null;
    }

}
$.ajax({
                           type:"POST",
                         data:formData,
                         processData:false,
                         contentType:false,
                         //设置可跨域
                         xhrFields: {
                            withCredentials: true
                          },
                        crossDomain: true,
                        url:
                        success:function(data,textStatus){
                           swal("上传成功");
                        },
                        exception:function(data,textStatus){

                            }
                    });
注意标红部分

这样在当前域的任何端口都能获取到session

完毕

posted on 2017-04-25 11:37  zzz初见  阅读(1552)  评论(0编辑  收藏  举报

导航