短视频商城系统,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实现登录, 更多内容欢迎关注之后的文章
标签:username,index,String,登录,request,session,cookie,商城 From: https://www.cnblogs.com/yunbaomengnan/p/17962168