1. User Verification
Complete must log in to enter the product display interface
1. Add request and response parameters to the findByAccount method:
cookie stores user information
(1) Import helper class
①、CookieUtils
package com.hmf.seckill.util;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
@Slf4j
public class CookieUtils {
/**
* @Description: 得到Cookie的值, 不编码
*/
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, false);
}
/**
* @Description: 得到Cookie的值
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}
/**
* @Description: 得到Cookie的值
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}
/**
* @Description: 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) {
setCookie(request, response, cookieName, cookieValue, -1);
}
/**
* @Description: 设置Cookie的值 在指定时间内生效,但不编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage) {
setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
}
/**
* @Description: 设置Cookie的值 不设置生效时间,但编码
* 在服务器被创建,返回给客户端,并且保存客户端
* 如果设置了SETMAXAGE(int seconds),会把cookie保存在客户端的硬盘中
* 如果没有设置,会默认把cookie保存在浏览器的内存中
* 一旦设置setPath():只能通过设置的路径才能获取到当前的cookie信息
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, boolean isEncode) {
setCookie(request, response, cookieName, cookieValue, -1, isEncode);
}
/**
* @Description: 设置Cookie的值 在指定时间内生效, 编码参数
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
}
/**
* @Description: 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage, String encodeString) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
}
/**
* @Description: 删除Cookie带cookie域名
*/
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName) {
doSetCookie(request, response, cookieName, null, -1, false);
}
/**
* @Description: 设置Cookie的值,并使其在指定时间内生效
*/
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
try {
if (cookieValue == null) {
cookieValue = "";
} else if (isEncode) {
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0)
cookie.setMaxAge(cookieMaxage);
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
log.info("========== domainName: {} ==========", domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Description: 设置Cookie的值,并使其在指定时间内生效
*/
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
try {
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0)
cookie.setMaxAge(cookieMaxage);
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
log.info("========== domainName: {} ==========", domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Description: 得到cookie的域名
*/
private static final String getDomainName(HttpServletRequest request) {
String domainName = null;
String serverName = request.getRequestURL().toString();
if (serverName == null || serverName.equals("")) {
domainName = "";
} else {
serverName = serverName.toLowerCase();
serverName = serverName.substring(7);
final int end = serverName.indexOf("/");
serverName = serverName.substring(0, end);
if (serverName.indexOf(":") > 0) {
String[] ary = serverName.split("\\:");
serverName = ary[0];
}
final String[] domains = serverName.split("\\.");
int len = domains.length;
if (len > 3 && !isIp(serverName)) {
// www.xxx.com.cn
domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
} else if (len <= 3 && len > 1) {
// xxx.com or xxx.cn
domainName = "." + domains[len - 2] + "." + domains[len - 1];
} else {
domainName = serverName;
}
}
return domainName;
}
public static String trimSpaces(String IP) {//去掉IP字符串前后所有的空格
while (IP.startsWith(" ")) {
IP = IP.substring(1, IP.length()).trim();
}
while (IP.endsWith(" ")) {
IP = IP.substring(0, IP.length() - 1).trim();
}
return IP;
}
public static boolean isIp(String IP) {//判断是否是一个IP
boolean b = false;
IP = trimSpaces(IP);
if (IP.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
String s[] = IP.split("\\.");
if (Integer.parseInt(s[0]) < 255)
if (Integer.parseInt(s[1]) < 255)
if (Integer.parseInt(s[2]) < 255)
if (Integer.parseInt(s[3]) < 255)
b = true;
}
return b;
}
}
(2) Modify UserServiceImpl
package com.hmf.seckill.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hmf.seckill.exception.BusinessException;
import com.hmf.seckill.pojo.User;
import com.hmf.seckill.mapper.UserMapper;
import com.hmf.seckill.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmf.seckill.util.CookieUtils;
import com.hmf.seckill.util.MD5Utils;
import com.hmf.seckill.util.ValidatorUtils;
import com.hmf.seckill.util.response.ResponseResult;
import com.hmf.seckill.util.response.ResponseResultCode;
import com.hmf.seckill.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;
/**
* <p>
* 用户信息表 服务实现类
* </p>
*
* @author hmf-git
* @since 2022-03-15
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Override
public ResponseResult<?> findByAccount(UserVo userVo, HttpServletRequest request, HttpServletResponse response) {
//先判断信息是否符合
if(!ValidatorUtils.isMobile(userVo.getMobile())){
throw new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_MOBLIE);
}
if(StringUtils.isBlank(userVo.getPassword())){
throw new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_MOBLIE);
}
//再看数据库查出对应的用户
User user=this.getOne(new QueryWrapper<User>().eq("id",userVo.getMobile()));
if(user==null){
throw new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_FIND);
}
//在比较密码
//二重加密
String salt=user.getSalt();
String newPassword=MD5Utils.formPassToDbPass(userVo.getPassword(),salt);
//将前台的加密和后端的盐再次加密
if(!newPassword.equals(user.getPassword())) {
throw new BusinessException(ResponseResultCode.USER_PASSWORD_NOT_MATCH);
}
this.update(new UpdateWrapper<User>().eq("id",userVo.getMobile()).set("last_login_date",new Date()).setSql("login_count=login_count+1"));
//最初的版本(session:全局共用,uuid:不可能重复)
String ticket = UUID.randomUUID().toString().replace("-", "");
// request.getSession().setAttribute("user",user);
request.getSession().setAttribute(ticket,user);
// 将我生成的ticket给用户,用户如何验证? 使用cookie,cookie在客户端,session在服务端
// Cookie cookie=new Cookie("ticket",ticket);
// response.addCookie(cookie); 这样写会导致设置时间麻烦
CookieUtils.setCookie(request,response,"ticket",ticket);
return ResponseResult.success();
}
}
run test
3. Page jump judgment
Authentication is required for all pages except the login page
(1) Modify PathController
package com.hmf.seckill.controller;
import com.hmf.seckill.exception.BusinessException;
import com.hmf.seckill.util.CookieUtils;
import com.hmf.seckill.util.response.ResponseResultCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class PathController {
//跳首页
@RequestMapping("/")
public String toPath(){
return "login";
}
//跳二级页面
@RequestMapping("/{dir}/{path}")
public String toPath(@PathVariable("dir") String dir, @PathVariable("path") String path, HttpServletRequest request ){
String ticket= CookieUtils.getCookieValue(request,"ticket");
// Judge before page jump Is the information brought by the user valid
if(ticket==null){
// If there is no information, a business exception is thrown, and the ticket credential is abnormal
throw new BusinessException(ResponseResultCode.TICKET_ERROR);
}
// Go to the session to get the user corresponding to the ticket , to determine whether there is a value
Object obj = request.getSession().getAttribute(ticket);
if(obj==null){
// The credential has not been obtained, or it has expired, and the credential exception is also thrown.
throw new BusinessException(ResponseResultCode .TICKET_ERROR);
}
//processing operation
return dir+"/"+path;
}
}
(2) Run the test
2. The redis cache completes the global session
There is still a problem with the current session. It only exists in one server. If a cluster is built, only the first A who obtains the credentials can access it.
1. Redis cache completes session sharing
(1) A third party ( redis cache ) is required, put the credentials in the third party, and get them if needed
(2) Import pom dependencies
<!--commons-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--spring-session uses session Third-party storage (redis/mongodb, etc.), default redis-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
(3) Configure redis cache
①、application.yml
redis:
host: 127.0.0.1
# password:
database: 0
port: 6379
3. Customize redis to complete global sharing
1. Define a redisconfig class to connect to redis
create a package
package com.hmf.seckill.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig{
public RedisTemplate redisTemplate(RedisConnectionFactory factory){
//新建一个
RedisTemplate redisTemplate=new RedisTemplate();
//设置一下使用连接工厂
redisTemplate.setConnectionFactory(factory);
//额外设置(String)
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//额外设置(hash 就是map集合)
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//让设置生效
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
2. Write the service layer and implement the class
IRedisService:
Write two methods in service, one is to increase and the other is to get
package com.hmf.seckill.service;
import com.hmf.seckill.pojo.User;
@SuppressWarnings("all")
public interface IRedisService {
void putUserByTicket(String ticket, User user);
User getUserByTicket(String ticket);
}
RedisServiceImpl:
package com.hmf.seckill.service.impl;
import com.hmf.seckill.pojo.User;
import com.hmf.seckill.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class RedisServiceImpl implements IRedisService {
@Autowired
private RedisTemplate redisTemplate;
@Override
public void putUserByTicket(String ticket, User user) {
//user会创建一个文件夹 等于是分类区分
//放值
redisTemplate.opsForValue().set("user:"+ticket,user,2L, TimeUnit.HOURS);
}
@Override
public User getUserByTicket(String ticket) {
Object obj=redisTemplate.opsForValue().get(ticket);
if (obj==null|| !(obj instanceof User)){
return null;
}
//拿值
return (User) obj;
}
}
3. Connect redis with visualization tools
4. Test and implement redis for data sharing
package com.hmf.seckill.controller; import com.hmf.seckill.exception.BusinessException; import com.hmf.seckill.pojo.User; import com.hmf.seckill.service.IRedisService; import com.hmf.seckill.util.CookieUtils; import com.hmf.seckill.util.response.ResponseResultCode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; @Controller public class PathController { @Autowired private IRedisService redisService; //Jump to the home page @RequestMapping("/") public String toPath(){ return "login"; } //Jump to the secondary page @RequestMapping("/{dir}/{path}") public String toPath(@PathVariable( "dir") String dir, @PathVariable("path") String path, HttpServletRequest request){ String ticket= CookieUtils.getCookieValue(request,"ticket"); // Determine whether the information brought by the user is valid before jumping to the page if(ticket==null){ // No information, throw a business exception, ticket credential exception throw new BusinessException(ResponseResultCode.TICKET_ERROR); } // Get the user corresponding to the ticket from the session, and judge whether there is a value // Object obj = request.getSession().getAttribute(ticket); //Go to the cache to get the value User user = redisService.getUserByTicket(ticket); if(user==null){ // The credential has not been obtained, or has expired, and a credential exception is also thrown throw new BusinessException(ResponseResultCode.TICKET_ERROR); } //Processing operation return dir+"/"+path; } }
package com.hmf.seckill.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.hmf.seckill.exception.BusinessException; import com.hmf.seckill.pojo.User; import com.hmf.seckill.mapper.UserMapper; import com.hmf.seckill.service.IRedisService; import com.hmf.seckill.service.IUserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.hmf.seckill.util.CookieUtils; import com.hmf.seckill.util.MD5Utils; import com.hmf.seckill.util.ValidatorUtils; import com.hmf.seckill.util.response.ResponseResult; import com.hmf.seckill.util.response.ResponseResultCode; import com.hmf.seckill.vo.UserVo; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.util.UUID; /** * <p> * 用户信息表 服务实现类 * </p> * * @author hmf-git * @since 2022-03-15 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { @Autowired private IRedisService redisService; @Override throw new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_FIND); public ResponseResult<?> findByAccount(UserVo userVo, HttpServletRequest request, HttpServletResponse response) { //First determine whether the information meets if(!ValidatorUtils.isMobile(userVo.getMobile())){ throw new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_MOBLIE) ; } if (StringUtils.isBlank(userVo.getPassword())){ throw new BusinessException(ResponseResultCode.USER_ACCOUNT_NOT_MOBLIE); } //Look at the database to find out the corresponding user User user=this.getOne(new QueryWrapper<User>().eq( "id", userVo.getMobile())); if(user==null){ } //Comparing passwords //Double encryption String salt=user.getSalt(); String newPassword=MD5Utils.formPassToDbPass(userVo.getPassword(),salt); //Encrypt the front-end encryption and back-end salt again if(!newPassword.equals(user.getPassword())) { throw new BusinessException(ResponseResultCode.USER_PASSWORD_NOT_MATCH ); } this.update(new UpdateWrapper<User>().eq("id",userVo.getMobile()).set("last_login_date",new Date()).setSql("login_count=login_count+1") ); //Initial version (session: shared globally, uuid: impossible to repeat) String ticket = UUID.randomUUID().toString().replace("-", ""); //put it globally or as a server session //request.getSession().setAttribute(ticket,user); //Put it in the cache redisService.putUserByTicket(ticket,user); //Give the ticket I generated to the user, how does the user verify? Use cookies, cookies are on the client side, and sessions are on the server side //Cookie cookie=new Cookie("ticket", ticket); //response.addCookie(cookie); This will cause trouble in setting time CookieUtils.setCookie(request,response ,"ticket",ticket); return ResponseResult.success(); } }