引言:
本文主要分享了Redis在SpringBoot在的整合,与衔接Redis在Java中的使用及连接数据库(附源码)一文,在其基础上增加了利用Redis进行登录的认证,实现拦截的功能;
package com.sx.kak.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* Created by Kak on 2020/9/19.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo implements Serializable{
private String username;
private String password;
}
package com.sx.kak.mapper;
import com.sx.kak.po.Student;
import com.sx.kak.vo.UserInfo;
/**
* Created by Kak on 2020/9/19.
*/
public interface UserInfoMapper {
public UserInfo findUserInfoByUsername(String username);
}
<mapper namespace="com.sx.kak.mapper.UserInfoMapper">
<select id="findUserInfoByUsername" resultType="com.sx.kak.vo.UserInfo" parameterType="String">
select * from tb_UserInfo where username=#{username}
select>
mapper>
package com.sx.kak.service;
import com.sx.kak.po.Student;
import java.util.List;
/**
* Created by Kak on 2020/9/19.
*/
public interface StudentService {
public List<Student> findAllStudent();
}
package com.sx.kak.service.serviceImpl;
import com.sx.kak.mapper.UserInfoMapper;
import com.sx.kak.service.UserService;
import com.sx.kak.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by Kak on 2020/9/19.
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired(required = false)
private UserInfoMapper userInfoMapper;
@Override
public UserInfo findUserInfoByUsernameService(String username) {
UserInfo userInfoByUsername = userInfoMapper.findUserInfoByUsername(username);
return userInfoByUsername;
}
}
将StudentController加入@RequestMapping("/api"),模拟当没有登录时就无权访问api下面的页面了;
package com.sx.kak.intercetpor;
import com.sx.kak.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by Kak on 2020/9/19.
*/
public class AuthInterceptor implements HandlerInterceptor{
@Autowired
//注入
private RedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("interceptor validing.....");
//从redis中读出用户状态信息
Object obj = redisTemplate.opsForValue().get("stus");
if(obj!=null){
UserInfo info = (UserInfo) obj;
System.out.println("login was ok!");
return true;
}
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
通用转化器
package com.sx.kak.utils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
/**
* Created by Kak on 2020/9/19.
*/
public class UnionSerializerConvertor implements RedisSerializer<Object> {
// 创建系统序列化对象
Converter<Object ,byte[]> serializer = new SerializingConverter();
// 创建系统反序列化对象
Converter<byte[],Object > deserializer = new DeserializingConverter();
byte[] studentByte = new byte[0];
// 序列化
@Override
public byte[] serialize(Object o) throws SerializationException {
if(o==null){
return studentByte;
}
return serializer.convert(o);
}
//反序列化
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
if(bytes!=null){
return deserializer.convert(bytes);
}
return null;
}
}
package com.sx.kak.config;
import com.sx.kak.utils.SingleTonRedisUtil;
import com.sx.kak.utils.UnionSerializerConvertor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;
/**
* Created by Kak on 2020/9/17.
*/
@Configuration
public class RedisConfig {
//创建springdata的redis操纵对象
@Bean
public RedisTemplate redisTemplate(){
RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
//配置redis的连接工厂
redisTemplate.setConnectionFactory(jedisConnectionFactory());
// 配置key序列化转换器
redisTemplate.setKeySerializer(new UnionSerializerConvertor());
// 配置value序列化转换器
redisTemplate.setValueSerializer(new UnionSerializerConvertor());
return redisTemplate;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory(){
return new JedisConnectionFactory();
}
}
package com.sx.kak.config;
import com.sx.kak.intercetpor.AuthInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Created by Kak on 2020/9/19.
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册自定义的拦截器,设置拦截的路径
registry.addInterceptor(handlerInterceptor()).addPathPatterns("/api/**");
}
@Bean(name="myAuth")
public HandlerInterceptor handlerInterceptor(){
return new AuthInterceptor();
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面title>
head>
<body>
<a href="/api/findStudent">全查a>
<form action="dealLogin" method="POST">
UserName:<input type="text" name="username"/><br/>
Password:<input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
form>
body>
html>
package com.sx.kak.controller;
import com.sx.kak.service.UserService;
import com.sx.kak.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.concurrent.TimeUnit;
/**
* Created by Kak on 2020/9/19.
*/
@Controller
@Slf4j
public class UserController {
@Autowired(required = false)
private UserService userService;
// 注入redisTemplate操作对象
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("/login")
public String showLogin(){
return "login";
}
@RequestMapping(value = "dealLogin",method = RequestMethod.POST)
public String daelLogin(UserInfo userInfo){
UserInfo userInfoByUsernameService = userService.findUserInfoByUsernameService(userInfo.getUsername());
log.info("login ok:"+userInfo.toString());
try{
//写入redis中
redisTemplate.opsForValue().set("stus",userInfoByUsernameService);
//设置用户状态的生存期
redisTemplate.expire("stus",10, TimeUnit.SECONDS);
return "success";
}catch (Exception ex){
log.info(ex.getMessage());
}
return "cannot";
}
}