NutzCN Logo
问答 接口自定义响应头丢失问题
发布于 1401天前 作者 阿强 1886 次浏览 复制 上一个帖子 下一个帖子
标签: nutzwk

暂时不清楚那一层导致的
问题如下:
因为后台需要做到H5又懒得改session为token机制so...
cookie不能用的情况下需要换个headerKey即下文中的sessionId
当访问页面时(无cookie)响应头中设置了setCookie 且有sessionId
而访问接口doLogin时响应头中仅有setCookie无sessionId,代码setHeader("sessionId",sessionId)有执行

package cn.wizzer.framework.filter.processor;

import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.impl.processor.AbstractProcessor;

import javax.servlet.ServletRequestWrapper;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 实现header取值设值以便于client端调用
 */
public class RespHeaderShiroProcessor extends AbstractProcessor {

    private static final Log log = Logs.get();

    @Override
    public void process(ActionContext ac) throws Throwable {
        preShiro(ac);
        doNext(ac);
        sufShiro(ac);
    }

    /**
     * 添加cookie
     * @param ac
     */
    private void preShiro(ActionContext ac) {
        String sessionId = ac.getRequest().getHeader("sessionId");
        if (Strings.isNotBlank(sessionId)) {
            try {
                Field req = ServletRequestWrapper.class.getDeclaredField("request");
                req.setAccessible(true);
                Object request = req.get(ac.getRequest());
                Class<?> reqClass = Class.forName("org.eclipse.jetty.server.Request");
                //调用cookie方法使得cookie对象初始化
                Method getCookiesMethod = reqClass.getDeclaredMethod("getCookies");
                getCookiesMethod.invoke(request);
                //获取cookie字段
                Field cookieField = reqClass.getDeclaredField("_cookies");
                cookieField.setAccessible(true);
                Object cookie = cookieField.get(request);
                Class<?> cookieCutterClass = Class.forName("org.eclipse.jetty.server.CookieCutter");
                //添加值到cookie
                Method addCookieFieldMethod = cookieCutterClass.getDeclaredMethod("addCookieField",String.class);
                addCookieFieldMethod.invoke(cookie,sessionId);
            } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException
                    | NoSuchFieldException e) {
                log.error(e);
            }
        }
    }

    private void sufShiro(ActionContext ac) {
        String setCookie = ac.getResponse().getHeader("Set-Cookie");
        if (Strings.isNotBlank(setCookie) && setCookie.contains("sid=")) {
            ac.getResponse().setHeader("sessionId",setCookie.substring(0,setCookie.indexOf(";")));
        }
    }
}

添加回复
请先登陆
回到顶部