短视频商城系统,session和cookie实现登录

短视频商城系统,session和cookie实现登录

项目准备
1.登录页面的login.html
2.主页index.html
3.处理登录的方法
4.获取session中数据的方法
5.过滤器

登录页面
在static目录下新建一个文件叫做login.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:9090/study/login" method="post">
        <input type="text" name="username"/>
        <input type="password" name="password">
        <input type="submit" value="登录">
    </form>
</body>
</html>
复制代码

 

登录逻辑处理
通过request获取到登录输入的用户名和密码,这里不做校验,直接把用户名放到session当中,然后重定向到index.html。

@PostMapping("/login")
public void userLogin (HttpServletRequest request, HttpServletResponse response) {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    HttpSession httpSession = request.getSession();
    httpSession.setAttribute("username", username);
    response.sendRedirect("index.html");
}

 

主页
在index.html页面中通过点击获取用户名获取username的值

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="http://localhost:9090/study/index">获取用户名</a>
</body>
</html>
复制代码

 

从session中获取值

@GetMapping("/index")
public String index(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    return (String) session.getAttribute("username");
}

 

过滤器
过滤器,用于判断用户是否登录,即是否从session中能获取到用户名称,如果能获取到说明用户是登陆了的,如果不能就跳转到登录页面。

复制代码
@Component
@WebFilter(filterName="LoginFilter",urlPatterns="/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;

        String path = req.getServletPath();
        if (!StringUtils.equals("/login", path) && !path.contains("html")) {
            HttpSession session = req.getSession();
            String username = (String)session.getAttribute("username");
            if (StringUtils.isEmpty(username)) {
                res.sendRedirect("login.html");
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
复制代码

 

以上就是短视频商城系统,session和cookie实现登录, 更多内容欢迎关注之后的文章

posted @   云豹科技-苏凌霄  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2023-01-13 搭建直播平台,Ext Js grid 改变单元格背景颜色的方法
2023-01-13 直播平台软件开发,Extjs Grid自动换行
2023-01-13 视频直播源码,下拉多选el-tag显示在输入框中
2022-01-13 android短视频开发,上传视频自动添加水印
2022-01-13 直播app开发,推出语音聊天室时保持悬浮窗存在状态
2022-01-13 直播带货平台,仿某宝实现商品上下滑动
点击右上角即可分享
微信分享提示