基于Vue和springBoot的登录模块设计
1.登录页面设计
2.发送登录请求
使用的是axios发送请求,
需求是,将填写的username 和password传递到登录接口,成功,返回token类型的cookie, 并跳转到home页面;失败,则弹出“登录失败”的提示信息。具体方法如下:
login(){
//表单预验证npm
this.$refs.loginFormRef.validate( async valid=>{
if (!valid) return;
const res=await this.$http.post("login",this.loginForm);
console.log(res)
if (!res.data){
this.$message.error("登录失败!")
}else {
this.$message.success("登录成功!")
this.$router.push("/home")
}
})
}
注意,因为使用的axios发送请求,所以在 main.js文件中要做一下关于 axios 的默认配置。配置如下:
import axios from 'axios'
//配置请求的根路径
axios.defaults.baseURL='http://localhost/'
//设置后,返回的cookie会保存在浏览器,否则不会
axios.defaults.withCredentials=true
Vue.prototype.$http= axios
3.登录接口设计
controller设计
方法:
@Controller
public class TestController {
@Autowired
private TestService testService;
@Autowired
private JwtProperties jwtProperties;
@PostMapping("login")
public ResponseEntity<Boolean> login(@RequestBody User user, HttpServletResponse response, HttpServletRequest request){
//调用 service,传入user对象,返回生成的 token 字符串
String token = this.testService.findByUser(user);
//判断
if (StringUtils.isBlank(token)){
System.out.println("找不到该账户!");
return ResponseEntity.ok(false);
}
//使用 cookieUtils.setCookie方法,就可以把 jwt 类型的token 设置给 cookie
CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getExpire()*60,"utf-8",true);
return ResponseEntity.ok(true);
}
}
service设计
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class TestService {
@Autowired
private UserMapper userMapper;
@Autowired
private JwtProperties jwtProperties;
public String findByUser(User user){
//数据库查询User对象
User user_find = this.userMapper.selectOne(user);
if (user_find==null){
return null;
}
//初始化荷载信息
UserInfo userInfo = new UserInfo();
userInfo.setId(user_find.getId());
userInfo.setUsername(user_find.getUsername());
try {
//使用JwtUtils,生成token字符串,并返回
return JwtUtils.generateToken(userInfo,jwtProperties.getPrivateKey(),jwtProperties.getExpire());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
mapper设计
public interface UserMapper extends Mapper<User> {
}
utils
添加登录验证功能
用户可以在无登录的情况下访问登录页面,访问其他页面,会跳转到登录页面;登录后,可以访问其他页面,同时登录后访问其他页面时,要返回从token中解析的用户信息
1.配置路由文件index.js
添加过滤方法 router.beforeEach() ,每次进行路由跳转时,都会经过此方法,判定后决定是否进行跳转
router.beforeEach(async(to,from,next)=>{
//跳转到登录页面,则放行
if (to.path==='/login') return next();
try {
//不为登录页面,则去后台接口判定是否进行登录,
//返回结果为空,跳转到登录页面;不为空,则放行
const { data } = await axios.get('/verify')
} catch (e) {
return next('/login');
}
next()
})
2.后台接口设计
@GetMapping("verify")
public ResponseEntity<UserInfo> verifyUserInfo(
@CookieValue("SJ_TOKEN") String token,
HttpServletRequest request,
HttpServletResponse response){
UserInfo userInfo = null;
try {
//根据获取的cookie和本地公钥解析出 userInfo 信息
userInfo=JwtUtils.getInfoFromToken(token,jwtProperties.getPublicKey());
if (userInfo==null){
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
//刷新jwt过期时间;本质是重新生成jwt
token =JwtUtils.generateToken(userInfo,this.jwtProperties.getPrivateKey(),this.jwtProperties.getExpire());
//刷新cookie的过期时间
CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getExpire()*60,"utf-8",true);
} catch (Exception e) {
e.printStackTrace();
ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
return ResponseEntity.ok(userInfo);
}
3.登录后,页面获取userInfo信息
在vue组件中定义初始化方法,当页面初始化时,从后台接口中解析出用户信息返回到页面
<script>
export default {
name: 'Home',
data(){
return{
userInfo:{
id:"afsdf",
username:"ggg"
}
}
},
async created () {//初始化方法,页面初始化时,从后台返回userInfo数据
const res = await this.$http.get("/verify");
console.log(res.data)
this.userInfo.id=res.data.id
this.userInfo.username=res.data.username
}
}
</script>