• 仿牛客项目总结


    1、通过邮件激活注册账号

    进入注册页面,填写好账号密码和邮箱,点击立即注册。

    注册: 后端接收到请求后,先进行空值判断、邮箱或账号是否已存在,过了这一关后将用户的密码+盐进行md5加密并将其和其他相关信息封装后持久化到数据库,接下来再就是通过JavaMailSender和thymleaf模板引擎发送html激活邮件,邮件中附带用户在数据库存储的id和激活码。

    1. @RequestMapping(path = "/register", method = RequestMethod.POST)
    2. public String register(Model model, User user) {
    3. Map map = userService.register(user);
    4. if (map == null || map.isEmpty()) {
    5. model.addAttribute("msg", "注册成功,我们已经向您的邮箱发送了一封激活邮件,请尽快激活!");
    6. model.addAttribute("target", "/index");
    7. return "/site/operate-result";
    8. } else {
    9. model.addAttribute("usernameMsg", map.get("usernameMsg"));
    10. model.addAttribute("passwordMsg", map.get("passwordMsg"));
    11. model.addAttribute("emailMsg", map.get("emailMsg"));
    12. return "/site/register";
    13. }
    14. }
    1. public Map register(User user) {
    2. Map map = new HashMap<>();
    3. // 空值处理
    4. if (user == null) {
    5. throw new IllegalArgumentException("参数不能为空!");
    6. }
    7. if (StringUtils.isBlank(user.getUsername())) {
    8. map.put("usernameMsg", "账号不能为空!");
    9. return map;
    10. }
    11. if (StringUtils.isBlank(user.getPassword())) {
    12. map.put("passwordMsg", "密码不能为空!");
    13. return map;
    14. }
    15. if (StringUtils.isBlank(user.getEmail())) {
    16. map.put("emailMsg", "邮箱不能为空!");
    17. return map;
    18. }
    19. // 验证账号
    20. User u = userMapper.selectByName(user.getUsername());
    21. if (u != null) {
    22. map.put("usernameMsg", "该账号已存在!");
    23. return map;
    24. }
    25. // 验证邮箱
    26. u = userMapper.selectByEmail(user.getEmail());
    27. if (u != null) {
    28. map.put("emailMsg", "该邮箱已被注册!");
    29. return map;
    30. }
    31. // 注册用户
    32. user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
    33. user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
    34. user.setType(0);
    35. user.setStatus(0);
    36. user.setActivationCode(CommunityUtil.generateUUID());
    37. user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
    38. user.setCreateTime(new Date());
    39. userMapper.insertUser(user);
    40. // 激活邮件
    41. Context context = new Context();
    42. context.setVariable("email", user.getEmail());
    43. // http://localhost:8080/community/activation/101/code
    44. String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
    45. context.setVariable("url", url);
    46. String content = templateEngine.process("/mail/activation", context);
    47. mailClient.sendMail(user.getEmail(), "激活账号", content);
    48. return map;
    49. }

    激活:

     后端收到激活请求后,将激活请求中携带的激活码和用户id拿去和数据库比对,如果激活码配对上了就将数据库中用户的状态从0更新为1,此时此用户账号激活了之后可以正常使用。

    1. // http://localhost:8080/community/activation/101/code
    2. @RequestMapping(path = "/activation/{userId}/{code}", method = RequestMethod.GET)
    3. public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
    4. int result = userService.activation(userId, code);
    5. if (result == ACTIVATION_SUCCESS) {
    6. model.addAttribute("msg", "激活成功,您的账号已经可以正常使用了!");
    7. model.addAttribute("target", "/login");
    8. } else if (result == ACTIVATION_REPEAT) {
    9. model.addAttribute("msg", "无效操作,该账号已经激活过了!");
    10. model.addAttribute("target", "/index");
    11. } else {
    12. model.addAttribute("msg", "激活失败,您提供的激活码不正确!");
    13. model.addAttribute("target", "/index");
    14. }
    15. return "/site/operate-result";
    16. }
    1. public int activation(int userId, String code) {
    2. User user = userMapper.selectById(userId);
    3. if (user.getStatus() == 1) {
    4. return ACTIVATION_REPEAT;
    5. } else if (user.getActivationCode().equals(code)) {
    6. userMapper.updateStatus(userId, 1);
    7. clearCache(userId);
    8. return ACTIVATION_SUCCESS;
    9. } else {
    10. return ACTIVATION_FAILURE;
    11. }
    12. }

     数据库中数据发生变动,将之前redis中的缓存清除

    1. // 3.数据变更时清除缓存数据
    2. private void clearCache(int userId) {
    3. String redisKey = RedisKeyUtil.getUserKey(userId);
    4. redisTemplate.delete(redisKey);
    5. }

     2、登录退出功能

     切换到登录页面第一件事就是去获取验证码

     

     后端收到获取验证码请求后会通过kaptchaProducer生成验证码和验证码图片,将验证码的归属存入cookie设置进response中,再将验证码存入缓存中,最后将验证码图片通过response输出到页面。

    1. @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    2. public void getKaptcha(HttpServletResponse response/*, HttpSession session*/) {
    3. // 生成验证码
    4. String text = kaptchaProducer.createText();
    5. BufferedImage image = kaptchaProducer.createImage(text);
    6. // 将验证码存入session
    7. // session.setAttribute("kaptcha", text);
    8. // 验证码的归属
    9. String kaptchaOwner = CommunityUtil.generateUUID();
    10. Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
    11. cookie.setMaxAge(60);
    12. cookie.setPath(contextPath);
    13. response.addCookie(cookie);
    14. // 将验证码存入Redis
    15. String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
    16. redisTemplate.opsForValue().set(redisKey, text, 60, TimeUnit.SECONDS);
    17. // 将突图片输出给浏览器
    18. response.setContentType("image/png");
    19. try {
    20. OutputStream os = response.getOutputStream();
    21. ImageIO.write(image, "png", os);
    22. } catch (IOException e) {
    23. logger.error("响应验证码失败:" + e.getMessage());
    24. }
    25. }

    获取到验证码以后是这个样子的

     填好验证码后点击登录,发送post请求。

    后端收到登录请求以后,首先会从cookie中获取验证码的归属值,通过验证码的归属值从缓存中取出验证码来,再跟用户输入的验证码比对成功则往下进行,通过用过输入的用户名从数据库中查询出这个用户来,然后用此用户的密码比对用户输入的密码,如果配对成功则生成一个登录凭证存入数据库,再存入缓存,最后再存入cookie里设置进response中,接下来再转发请求到主页。

    1. @RequestMapping(path = "/login", method = RequestMethod.POST)
    2. public String login(String username, String password, String code, boolean rememberme,
    3. Model model, /*HttpSession session, */HttpServletResponse response,
    4. @CookieValue("kaptchaOwner") String kaptchaOwner) {
    5. // 检查验证码
    6. // String kaptcha = (String) session.getAttribute("kaptcha");
    7. String kaptcha = null;
    8. if (StringUtils.isNotBlank(kaptchaOwner)) {
    9. String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
    10. kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
    11. }
    12. if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
    13. model.addAttribute("codeMsg", "验证码不正确!");
    14. return "/site/login";
    15. }
    16. // 检查账号,密码
    17. int expiredSeconds = rememberme ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
    18. Map map = userService.login(username, password, expiredSeconds);
    19. if (map.containsKey("ticket")) {
    20. Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
    21. cookie.setPath(contextPath);
    22. cookie.setMaxAge(expiredSeconds);
    23. response.addCookie(cookie);
    24. return "redirect:/index";
    25. } else {
    26. model.addAttribute("usernameMsg", map.get("usernameMsg"));
    27. model.addAttribute("passwordMsg", map.get("passwordMsg"));
    28. return "/site/login";
    29. }
    30. }

    请求主页后,将page相关的信息进行封装,然后查询全部的帖子后附带查询出每个帖子的发布者和喜欢人数封装进一个个map整合起来放进数据模型,最后返回主页的路径。

    1. @RequestMapping(path = "/index", method = RequestMethod.GET)
    2. public String getIndexPage(Model model, Page page,
    3. @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
    4. // 方法调用钱,SpringMVC会自动实例化Model和Page,并将Page注入Model.
    5. // 所以,在thymeleaf中可以直接访问Page对象中的数据.
    6. page.setRows(discussPostService.findDiscussPostRows(0));
    7. page.setPath("/index?orderMode=" + orderMode);
    8. List list = discussPostService
    9. .findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
    10. List> discussPosts = new ArrayList<>();
    11. if (list != null) {
    12. for (DiscussPost post : list) {
    13. Map map = new HashMap<>();
    14. map.put("post", post);
    15. User user = userService.findUserById(post.getUserId());
    16. map.put("user", user);
    17. long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
    18. map.put("likeCount", likeCount);
    19. discussPosts.add(map);
    20. }
    21. }
    22. model.addAttribute("discussPosts", discussPosts);
    23. model.addAttribute("orderMode", orderMode);
    24. return "/index";
    25. }

     退出功能就是从请求中获取cookie里的登录凭证,用这个登录凭证从数据库中查出登录凭证对象,将它的状态设置为1使其失效。

    1. @RequestMapping(path = "/logout", method = RequestMethod.GET)
    2. public String logout(@CookieValue("ticket") String ticket) {
    3. userService.logout(ticket);
    4. SecurityContextHolder.clearContext();
    5. return "redirect:/login";
    6. }

  • 相关阅读:
    Python笔记——linux/ubuntu下安装mamba,安装bob.learn库
    C++类的运算符重载.md
    PeLK:101 x 101 的超大卷积网络,同参数量下反超 ViT | CVPR 2024
    【业务功能篇108】CDN Nginx
    学习路之api --接口文档和常见的状态码
    Car Show
    算法竞赛——数论(一),数论内容的介绍,基础数论
    Git 教程
    react配置项目路径别名@
    GB/T 28627-2023 抹灰石膏检测
  • 原文地址:https://blog.csdn.net/weixin_51930617/article/details/126934318