欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

dubbox跨域请求、Cookie

程序员文章站 2022-07-10 11:12:05
...

Dubbox配置CORS服务来解决跨域问题,这里不涉及jsonp跨域方式,一般服务端接口返回的数据都不是jsonp形式。

1、创建CorsResponseFilter类

package com.neusoft.filter;

import com.neusoft.util.PropertiesUtils;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.util.List;

/**
 * @author zhouzk
 * @ClassName: CorsResponseFilter
 * @Description: rest跨域
 * @date 2018/4/16 18:43
 */
public class CorsResponseFilter implements ContainerResponseFilter {

	public static final String ALLOWED_METHODS = "GET, POST, PUT, DELETE, OPTIONS, HEAD";
	public final static int MAX_AGE = 30 * 60;
	public final static String DEFAULT_ALLOWED_HEADERS = "origin,accept,content-type";

	public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
		String memberCrossDomain = PropertiesUtils.getProperty("member.cross.domain");
		final MultivaluedMap<String, Object> headers = responseContext.getHeaders();
		headers.add("Access-Control-Allow-Origin", memberCrossDomain);
		headers.add("Access-Control-Allow-Headers", getRequestedHeaders(requestContext));
		headers.add("Access-Control-Allow-Credentials", "true");
		headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
		headers.add("Access-Control-Max-Age", MAX_AGE);
		headers.add("x-responded-by", "cors-response-filter");
	}

	private String getRequestedHeaders(ContainerRequestContext responseContext) {
		List<String> headers = responseContext.getHeaders().get("Access-Control-Request-Headers");
		return createHeaderList(headers);
	}

	private String createHeaderList(List<String> headers) {
		if (headers == null || headers.isEmpty()) {
			return DEFAULT_ALLOWED_HEADERS;
		}
		StringBuilder retVal = new StringBuilder();
		for (int i = 0; i < headers.size(); i++) {
			String header = (String) headers.get(i);
			retVal.append(header);
			retVal.append(',');
		}
		retVal.append(DEFAULT_ALLOWED_HEADERS);
		return retVal.toString();
	}
}

2、在rest接口配置filter(cors)

<dubbo:protocol name="rest" port="8888" threads="1000" contextpath="services" server="tomcat" accepts="2000" extension="com.neusoft.filter.CorsResponseFilter"/>

3、response添加Cookie

	private static Boolean setCookie(String cookieKey, String cookieVal){
		HttpServletResponse httpServletResponse = (HttpServletResponse) RpcContext.getContext().getResponse();
		if(StringUtils.isBlank(cookieKey)){
			return false;
		}
		Cookie cookie = new Cookie(cookieKey,cookieVal);
		cookie.setPath("/");
		cookie.setMaxAge(3600*24*30);
		cookie.setDomain( "java.neusoft.com");
		cookie.setSecure(false);
		cookie.setHttpOnly(false);
		httpServletResponse.addCookie(cookie);
		return true;
	}

4、前端请求实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"></script>
    <script src="//cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
</head>
<body>
    <div class="container">
        <form>
            用户名:<input name="username" id="username" value="123">
            <br/>
            密码<input name="pwd" id="pwd" value="456">
            <br/>
            <button type="button" value="登录" onclick="doLogin()" >登录</button>
        </form>
    </div>
</body>
<script type="text/javascript">
    function doLogin() {
        var data = JSON.stringify({username:$('#username').val(),pwd:$('#pwd').val()});
        console.log(data)
        $.ajax({
            url:'http://java.neusoft.com:8888/services/member/doLoginByWeb',
            type:'POST',
            data:data,
            contentType: "application/json;charset=UTF-8",
            dataType:'json',    //返回的数据格式:json
            xhrFields:{withCredentials:true},
            crossDomain: true,
            success:function(data, status, xhr){
                console.log(data)
                var username = $.cookie('username'); // 读取 cookie
                if(username !='' && username!=undefined){
                    console.log('Cookie中的用户名:'+username)
                }
            },
            error:function(xhr,textStatus){
                console.log('错误')
                console.log(xhr)
                console.log(textStatus)
            },
            complete:function(){
                console.log('结束')
            }
        })
    }
</script>
</html>

5、本地host修改,没SwitchHost可以到系统盘下修改hosts文件,自行百度。

dubbox跨域请求、Cookie

6、测试结果

dubbox跨域请求、Cookie

7、完整案例代码已上传,点击下载。