发表于: 2021-03-05 23:11:30
2 1261
今天完成的事情:
cookie工具类
JWT工具类
明天计划的事情:
拦截器
遇到的问题:
以下
收获:
cookie工具类
package com.kbk.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
*
* @Description
* @Author 况博凯
* @Date 2021/03/05 16:27
* @Version 1.0
*
*/
public class CookieUtil {
/**
* @param response 携带cookie的响应
* @param name cookie名
* @param value cookie值
* @param maxAge cookie的最大存在时间
*/
public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAge);
cookie.setPath("/");
try {
cookie.setValue(URLEncoder.encode(value, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.addCookie(cookie);
}
/**
* 获取cookie的方法
* @param cookies 从客户端取得cookie数组
* @param name
* @return
*/
public static Cookie getCookie(Cookie[] cookies, String name) {
if (cookies == null) {
return null;
} else {
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
}
return null;
}
}
JWT工具类
package com.kbk.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
/**
*
* @Description
* @Author 况博凯
* @Date 2021/03/05 21:56
* @Version 1.0
*
*/
public class JWTUtil {
/**
* 生成jwt的方法
* @param date 签发时间
* @param secrety 私钥
* @param
* @return
*/
public static String getJWT(String id, String userName, Date date, String secrety){
JwtBuilder jwtBuilder= Jwts.builder().setIssuer(userName).setId(id)
.setIssuedAt(date)
.signWith(SignatureAlgorithm.HS256,secrety);
return jwtBuilder.compact();
}
/**
* 解析token
* @param token token
* @param secrety 私钥
* @return
*/
public static Claims parseJWT(String token, String secrety){
Claims claims=Jwts.parser().setSigningKey(secrety).parseClaimsJws(token).getBody();
return claims;
}
}
接口:
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String Login(HttpServletRequest request, Model model, HttpServletResponse response){
//获取账号密码
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.selectUserName(username);
//验证该用户是否存在,并判断密码是否相等
if (user != null && password.equals(user.getPassword())) {
String passwrod = user.getPassword();
//给登录进来的用户加盐
String md5Str= MD5Util.getMD5Str(passwrod);
//判断加盐后密码是否一致
boolean flag=MD5Util.getSaltverifyMD5(user.getPassword(),md5Str);
if (flag) {
//生成token
String token = JWTUtil.getJWT("1", user.getUsername(), new Date(), "1234");
//把token装到cookie中发送到客户端
CookieUtil.setCookie(response, "token", token, 60 * 3);
return "LoginSuccessful";
} else {
return "login";
}
} else {
model.addAttribute("msg", "用户名或者密码错误");
return "login";
}
}
运行:
===========
==========
cookie
评论