qq_47464003 2023-04-24 22:28 采纳率: 62.5%
浏览 22
已结题

Java后端,ssm框架使用cookie问题

这是测试cookie的


    @GetMapping("getStudent")
    public Result getById(HttpServletRequest httpServletRequest)
    {
        Integer student_id = null;
        String nickname;
        Cookie[] cookies = httpServletRequest.getCookies();
        System.out.println("执行");
        if(cookies != null)
        {
            System.out.println("cookie正常");
            for(Cookie cookie : cookies)
            {
                System.out.println("得到cookie" + cookie);
                System.out.println("cookies长度" + cookies.length);
                String token = cookie.getValue();
                if(JwtUtil.verify(token))
                {
                    System.out.println("token验证成功");
                    student_id = Integer.parseInt(JwtUtil.getUserId(token));
                    System.out.println(student_id);
                    nickname = JwtUtil.getUsername(token);
                    System.out.println(nickname);
                }
            }
        }
        Boolean flag = studentService.getById(Integer.valueOf(student_id))!=null?true:false;
        Integer codeid = flag?Student_FIND_OK:Student_FIND_ERR;
        Object result = studentService.getById(Integer.valueOf(student_id));
        return new Result(codeid, result, flag?"成功查询":"查询失败");
    }

这是用户登录时生成cookie,并且测试时token和登陆成功都在控制台出来了。

@PostMapping("/login")
    public Result login(@RequestParam String nickname, @RequestParam String password, HttpServletResponse response)
    {
        Boolean flag = studentService.login(nickname, password);
        Integer codeid = flag?Student_LOGIN_OK:Student_LOGIN_ERR;
        Integer user_id = studentService.getStudentIdByNickname(nickname);
        //查询数据库,登录
        String msg = null;
        if (flag) {
            System.out.println("登录成功");
            String token = JwtUtil.sign(nickname, user_id);
            System.out.println(token);
            if (token != null) {
                Cookie cookie = new Cookie("session", token);
                cookie.setMaxAge(3600);//设置token有效时间
                cookie.setPath("/");
                response.addCookie(cookie);
            }else{
                msg = "密码或账号错误";
            }
        } else {
            msg = "密码或账号错误";
        }
        return new Result(codeid, flag, msg);
    }

工具类,生成token

package com.jzy.util;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    /**
     * 过期时间一天,
     * TODO 正式运行时修改为15分钟
     */
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";

    /**
     * 校验token是否正确
     *
     * @param token 密钥
     * @return 是否正确
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("nickname").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取登陆用户ID
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("user_id").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,15min后过期
     *
     * @param nickname 用户名
     * @return 加密的token
     */
    public static String sign(String nickname, Integer user_id) {
        try {
//            过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
//            私钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//            设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            // 附带username,userId信息,生成签名
            return JWT.create()
                    .withHeader(header)
                    .withClaim("nickname", nickname)
                    .withClaim("user_id",user_id)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

}


问题是我在post登陆后,再用get,得到的cookies数组是空的,但我在post的时候确定已经生成cookie了,这是为啥

img


再调用get时后端就是cookies为空

  • 写回答

2条回答 默认 最新

  • 夜郎king 2022博客之星IT其它领域TOP 12 2023-04-25 07:59
    关注

    既然用到了jwt,一般就不用cookie了。把数据存放到localstorage中

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 4月25日
  • 创建了问题 4月24日

悬赏问题

  • ¥15 无法输出helloworld
  • ¥15 高通uboot 打印ubi init err 22
  • ¥20 PDF元数据中的XMP媒体管理属性
  • ¥15 R语言中lasso回归报错
  • ¥15 网站突然不能访问了,上午还好好的
  • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
  • ¥15 semrush,SEO,内嵌网站,api
  • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
  • ¥15 振荡电路,ADS仿真
  • ¥15 关于#c语言#的问题,请各位专家解答!