SpringBoot开发十-开发登录,退出功能
需求介绍—开发登录,退出功能
访问登录页面:点击头部区域的链接打开登录页面
登录:
- 验证账号,密码,验证码
- 成功时生成登录凭证发放给客户端,失败时跳转回登录页面
退出:
- 将登录状态修改为失效的状态
- 跳转至往网站的首页
代码实现
现在我们暂时把登录凭证存到数据库里面有一张表login_tickrt,以后会存到Redis里面。
那么首先要把登录凭证的相关操作实现了,首先写个实体类对应login_tickrt表里的数据,将其封装起来
package com.nowcoder.community.entity;
import java.util.Date;
public class LoginTicket {
private int id;
private int userId;
private String ticket;
private int status;
private Date expired;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getExpired() {
return expired;
}
public void setExpired(Date expired) {
this.expired = expired;
}
@Override
public String toString() {
return "LoginTicket{" +
"id=" + id +
", userId=" + userId +
", ticket='" + ticket + '\'' +
", status=" + status +
", expired=" + expired +
'}';
}
}
接下来实现数据访问的逻辑,那么新建一个接口LoginTicketMapper,对应的有以下几种方法:增加一个凭证,依据ticket来查凭证,修改凭证的状态。
这次我们通过注解的方式实现sql查询。
package com.nowcoder.community.dao; import com.nowcoder.community.entity.LoginTicket;
import org.apache.ibatis.annotations.*; @Mapper
public interface LoginTicketMapper { @Insert({
"insert into login_ticket(user_id,ticket,status,expired) ",
"value(#{userId},#{ticket},#{status},#{expired})"
})
// 希望id自动生成,
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertLoginTicket(LoginTicket loginTicket); @Select({
"select id,user_id,ticket,status,expired ",
"from login_ticket where ticket=#{ticket}"
})
LoginTicket selectByTicket(String ticket); @Update({
"update login_ticket set status=#{status} where ticket=#{ticket}"
})
int updateStatus(String ticket, int status);
}
那么现在就开发业务层UserService:
// 封装一个Map,返回多种情况的返回结果
public Map<String, Object> login(String username, String password, long expiredSeconds) {
Map<String, Object> map = new HashMap<>();
if(StringUtils.isBlank(username)) {
map.put("usernameMsg", "账号不能为空");
}
if(StringUtils.isBlank(password)) {
map.put("passwordMsg", "密码不能为空");
} // 验证账号
User user = userMapper.selectByName(username);
if (user == null) {
map.put("usernameMsg", "该账号不存在");
return map;
}
// 验证状态
if(user.getStatus() == 0) {
map.put("usernameMsg", "该账号未激活");
return map;
} // 验证密码
password = CommunityUtil.md5(password + user.getSalt());
if (!user.getPassword().equals(password)) {
map.put("passwordMsg", "密码不正确");
return map;
} // 生成登录凭证
LoginTicket loginTicket = new LoginTicket();
loginTicket.setUserId(user.getId());
loginTicket.setTicket(CommunityUtil.generateUUID());
loginTicket.setStatus(0);
loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
loginTicketMapper.insertLoginTicket(loginTicket); map.put("ticket", loginTicket.getTicket());
return map;
}
那么现在写表现层,写LoginController来处理页面传来的请求,写能处理请求的方法就可以了。
对于记住我的勾选我们要有不同的保存时间,所以我们定义两个常量的时间比较好,在CommunityConstant里添加定义:
/**
* 默认状态的登录凭证的超时时间
*/
int DEFAULT_EXPIRED_SECONDS = 3600 * 12; /**
* 记住状态的登录凭证的超时时间
*/
int REMEMBER_EXPIRED_SECONDS = 3600 * 24 *100;
辅助功能完成就写对应的表现层:
// 我们在决定Cookie的有效路径,最好是用变量来显示比较方便
@Value("${server.servlet.context-path}")
private String contextPath; @RequestMapping(path = "/login", method = RequestMethod.POST)
public String login(String username, String password, String code, boolean rememberme, Model model, HttpSession httpSession, HttpServletResponse httpServletResponse) {
// 检查验证码
String kaptcha = (String) httpSession.getAttribute("kaptcha"); if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
model.addAttribute("codeMsg","验证码不正确");
return "/site/login";
} // 检查账号,密码
int expiredSeconds = rememberme ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
Map<String, Object> map = userService.login(username, password, expiredSeconds);
if(map.containsKey("ticket")) {
// 需要给客户端发送一个Cookie
Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
cookie.setPath(contextPath);
cookie.setMaxAge(expiredSeconds);
httpServletResponse.addCookie(cookie);
return "redirect:/index";
}
else {
model.addAttribute("usernameMsg", map.get("usernameMsg"));
model.addAttribute("passwordMsg", map.get("passwordMsg"));
return "/site/login";
}
}
最后开发退出:
首先数据层我们已经写好了,只需要写个业务层和表现层
// 业务层调一下mapper的update方法就可以了
public void logout(String ticket) {
loginTicketMapper.updateStatus(ticket, 1);
}
表现层要从Cookie中拿到ticket,然后调业务层。
@RequestMapping(path = "/logout", method = RequestMethod.GET)
public String logout(@CookieValue("ticket") String ticket) {
userService.logout(ticket);
return "redirect:/login";
}
SpringBoot开发十-开发登录,退出功能的更多相关文章
- Atitit.用户权限服务 登录退出功能
Atitit.用户权限服务 登录退出功能 参数说明 /com.attilax/user/loginOut.jsp?url="+url Utype=mer 作者:: ★(attilax)&g ...
- [转] 从零构建 vue2 + vue-router + vuex 开发环境到入门,实现基本的登录退出功能
这是一个创建于 738 天前的主题,其中的信息可能已经有所发展或是发生改变. 前言 vue2 正式版已经发布将近一个月了, 国庆过后就用在了公司的两个正式项目上, 还有一个项目下个月也会采用 vue2 ...
- Struts2 + Hibernate3.3 开发简单的登录注册功能【J2EE】
开发环境: IDE:Myeclipse10.0 数据库:Oracle(SQL Developer) Web容器:Tomcat 7.0 JDK:1.6 Struts:2.0 Hibernate:3.3 ...
- SpringBoot Web开发(5) 开发页面国际化+登录拦截
SpringBoot Web开发(5) 开发页面国际化+登录拦截 一.页面国际化 页面国际化目的:根据浏览器语言设置的信息对页面信息进行切换,或者用户点击链接自行对页面语言信息进行切换. **效果演示 ...
- Android高效率编码-第三方SDK详解系列(二)——Bmob后端云开发,实现登录注册,更改资料,修改密码,邮箱验证,上传,下载,推送消息,缩略图加载等功能
Android高效率编码-第三方SDK详解系列(二)--Bmob后端云开发,实现登录注册,更改资料,修改密码,邮箱验证,上传,下载,推送消息,缩略图加载等功能 我的本意是第二篇写Mob的shareSD ...
- flask 开发用户登录注册功能
flask 开发用户登录注册功能 flask开发过程议案需要四个模块:html页面模板.form表单.db数据库操作.app视图函数 1.主程序 # app.py # Auther: hhh5460 ...
- SpringBoot整合MyBatis-Plus实现快速业务功能开发
概览:使用MybatisPlus和它的代码生成整合SpringBoot可以实现快速的业务功能开发,具体步骤如下 一.添加依赖 <dependency> <groupId>org ...
- SpringBoot:Web开发
西部开源-秦疆老师:基于SpringBoot 2.1.6 的博客教程 , 基于atguigu 1.5.x 视频优化 秦老师交流Q群号: 664386224 未授权禁止转载!编辑不易 , 转发请注明出处 ...
- 第十三章 Odoo 12开发之创建网站前端功能
Odoo 起初是一个后台系统,但很快就有了前端界面的需求.早期基于后台界面的门户界面不够灵活并且对移动端不友好.为解决这一问题,Odoo 引入了新的网站功能,为系统添加了 CMS(Content Ma ...
随机推荐
- 万字长文肝Git--全流程知识点包您满意【建议收藏】
您好,我是码农飞哥,感谢您阅读本文,欢迎一键三连哦. 本文将首先介绍在本地搭建GitLab服务,然后重点介绍Git的常用命令,Git的核心概念以及冲突处理,最后介绍Git与SVN的区别 干货满满,建议 ...
- CentOS-配置jar包自启动(SpringBoot)
在pom.xml文件<plugin>中添加配置后,再打包(开发人员) <plugin> <groupId>org.springframework.boot& ...
- apache 2.2 静态文件目录的配置
引用 #禁止使用proxy_ajp代理的目录: ProxyPass /sns/images/ ! #使用proxy_ajp代理:下面的配置,是把所有目录全用代理(当然,还会跟上面的禁用配置组合成完整的 ...
- 密码学系列之:memory-bound函数
密码学系列之:memory-bound函数 目录 简介 内存函数 内存受限函数 内存受限函数的使用 简介 memory-bound函数可以称为内存受限函数,它是指完成给定计算问题的时间主要取决于保存工 ...
- Python之手把手教你用JS逆向爬取网易云40万+评论并用stylecloud炫酷词云进行情感分析
本文借鉴了@平胸小仙女的知乎回复 https://www.zhihu.com/question/36081767 写在前面: 文章有点长,操作有点复杂,需要代码的直接去文末即可.想要学习的需要有点耐心 ...
- maven解析依赖报错:Cannot resolve com.baomidou:mybatis-plus-generator:3.4.2
不能解析依赖: <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plu ...
- poj1182:食物链
poj1182:食物链 听说是poj中最经典的一道并查集题目.我一做,果然很经典呢!好难啊!!!真的琢磨了很久还弄懂.这道题的重点就在于怎么用并查集表示题目中的关系环. 1. 题干 原题传送门1 原题 ...
- noip模拟26[肾炎黄·酱累黄·换莫黄]
\(noip模拟26\;solutions\) 这个题我做的确实是得心应手,为啥呢,因为前两次考试太难了 T1非常的简单,只不过我忘记了一个定理, T2就是一个小小的线段树,虽然吧我曾经说过我再也不写 ...
- Linux Shell 学习笔记 00
1.Bash = Bourne Again SHell 2.终端提示符: #普通用户 username@hostname$ #管理员用户 root@hostname# 3.shell脚本通常是一个以s ...
- 如何写好技术文档——来自Google十多年的文档经验
本文大部分内容翻译总结自<Software Engineering at Google> 第10章节 Documentation. 另外,该书电子版近日已经可以免费下载了 https:// ...