}

com.yusael.service 包下创建 UserServiceImpl.java

package com.yusael.service;

import com.yusael.dao.UserDAO;

import com.yusael.entity.User;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service

@Transactional

public class UserServiceImpl implements UserService {

@Autowired

private UserDAO userDAO;

@Override

public void register(User user) {

user.setId(UUID.randomUUID().toString());

userDAO.save(user);

}

@Override

public User login(String username, String password) {

return userDAO.login(username, password);

}

}

生成验证码的工具


在开发 com.yusael.controller 包的内容前,我们需要引入一个验证码功能的代码,将它放到 com.yusael.utils 下作为一个工具类:这个不需要我们自己写,直接拿过来用就可以了。

package com.yusael.utils;

import javax.imageio.ImageIO;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Arrays;

import java.util.Random;

public class ValidateImageCodeUtils {

/**

  • 验证码难度级别 Simple-数字 Medium-数字和小写字母 Hard-数字和大小写字母

*/

public enum SecurityCodeLevel {

Simple, Medium, Hard

};

/**

  • 产生默认验证码,4位中等难度

  • @return

*/

public static String getSecurityCode() {

return getSecurityCode(4, SecurityCodeLevel.Medium, false);

}

/**

  • 产生长度和难度任意的验证码

  • @param length

  • @param level

  • @param isCanRepeat

  • @return

*/

public static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {

// 随机抽取len个字符

int len = length;

// 字符集合(–除去易混淆的数字0,1,字母l,o,O)

char[] codes = {

‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’,

‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’,

‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’, ‘M’, ‘N’, ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’

};

// 根据不同难度截取字符串

if (level == SecurityCodeLevel.Simple) {

codes = Arrays.copyOfRange(codes, 0, 10);

} else if (level == SecurityCodeLevel.Medium) {

codes = Arrays.copyOfRange(codes, 0, 36);

}

// 字符集和长度

int n = codes.length;

// 抛出运行时异常

if (len > n && isCanRepeat == false) {

throw new RuntimeException(String.format(“调用SecurityCode.getSecurityCode(%1 s , s,%2 s,s,%3 s ) 出现异常, " + " 当 i s C a n R e p e a t 为 s)出现异常," + "当isCanRepeat为%3 s)出现异常,"+"isCanRepeats时,传入参数%1 s 不能大于 s不能大于%4 s不能大于s”, len, level, isCanRepeat, n));

}

// 存放抽取出来的字符

char[] result = new char[len];

// 判断能否出现重复字符

if (isCanRepeat) {

for (int i = 0; i < result.length; i++) {

// 索引0 and n-1

int r = (int) (Math.random() * n);

// 将result中的第i个元素设置为code[r]存放的数值

result[i] = codes[r];

}

} else {

for (int i = 0; i < result.length; i++) {

// 索引0 and n-1

int r = (int) (Math.random() * n);

// 将result中的第i个元素设置为code[r]存放的数值

result[i] = codes[r];

// 必须确保不会再次抽取到那个字符,这里用数组中最后一个字符改写code[r],并将n-1

codes[r] = codes[n - 1];

n–;

}

}

return String.valueOf(result);

}

/**

  • 生成验证码图片

  • @param securityCode

  • @return

*/

public static BufferedImage createImage(String securityCode){

int codeLength = securityCode.length();//验证码长度

int fontSize = 18;//字体大小

int fontWidth = fontSize+1;

//图片宽高

int width = codeLength*fontWidth+6;

int height = fontSize*2+1;

//图片

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics2D g = image.createGraphics();

g.setColor(Color.WHITE);//设置背景色

g.fillRect(0, 0, width, height);//填充背景

g.setColor(Color.LIGHT_GRAY);//设置边框颜色

g.setFont(new Font(“Arial”, Font.BOLD, height-2));//边框字体样式

g.drawRect(0, 0, width-1, height-1);//绘制边框

//绘制噪点

Random rand = new Random();

g.setColor(Color.LIGHT_GRAY);

for (int i = 0; i < codeLength*6; i++) {

int x = rand.nextInt(width);

int y = rand.nextInt(height);

g.drawRect(x, y, 1, 1);//绘制1*1大小的矩形

}

//绘制验证码

int codeY = height-10;

g.setColor(new Color(19,148,246));

g.setFont(new Font(“Georgia”, Font.BOLD, fontSize));

for(int i=0;i<codeLength;i++){

double deg=new Random().nextDouble()*20;

g.rotate(Math.toRadians(deg), i*16+13,codeY-7.5);

g.drawString(String.valueOf(securityCode.charAt(i)), i*16+5, codeY);

g.rotate(Math.toRadians(-deg), i*16+13,codeY-7.5);

}

g.dispose();//关闭资源

return image;

}

public static void main(String[] args) throws IOException {

String securityCode = ValidateImageCodeUtils.getSecurityCode();

System.out.println(securityCode);

BufferedImage image = ValidateImageCodeUtils.createImage(securityCode);

ImageIO.write(image,“png”,new FileOutputStream(“aa.png”));

}

}

controller


IndexController

我们知道,resources/templates 下面放的是我们的页面文件(html),如果我们直接访问 templates 下的静态页面是无法获取 static 中的样式的。

我们需要用控制器进行去访问,该控制器没有其他作用,只是为了访问界面而已

com.yusael.controller 下创建一个 IndexController.java

package com.yusael.controller;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

// 直接访问templates下的静态页面是无法获取static中的样式的

// 用该控制器进行去访问, 该控制器没有其他作用, 只是为了访问界面而已

@Controller

public class IndexController {

@GetMapping(“/index”)

public String toIndex() {

return “ems/login”;

}

@GetMapping(“/toRegister”)

public String toRgsiter() {

return “ems/regist”;

}

@GetMapping(“/toSave”)

public String toSaave() {

return “ems/addEmp”;

}

}

UserController

com.yusael.controller 下开发 UserController.java

package com.yusael.controller;

import com.yusael.entity.User;

import com.yusael.service.UserService;

import com.yusael.utils.ValidateImageCodeUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import java.awt.image.BufferedImage;

import java.io.IOException;

@Controller

@RequestMapping(“/user”)

public class UserController {

@Autowired

private UserService userService;

// 登录方法

@PostMapping(“/login”)

public String login(String username, String password, HttpSession session) {

User login = userService.login(username, password);

if (login != null) {

session.setAttribute(“user”, login);

System.out.println(“登录成功”);

return “redirect:/emp/findAll”; // 跳转到查询所有

} else {

return “redirect:/index”; // 跳转回到登录

}

}

// 注册方法

@PostMapping(“/register”)

public String register(User user, String code, HttpSession session) {

String sessionCode = (String)session.getAttribute(“code”); // 生成的验证码

// 忽略大小写, 比较用户输入的验证码与生成的验证码

if (sessionCode.equalsIgnoreCase(code)) { // 输入正确

userService.register(user); // 注册

System.out.println(“注册成功”);

return “redirect:/index”; // 注册成功跳转到登录界面

} else { // 输入错误

return “redirect:/toRegister”; // 注册失败跳转到注册界面

}

}

// 生成验证码

@GetMapping(“/code”)

public void getImage(HttpSession session, HttpServletResponse response) throws IOException {

// 生成验证码

String securityCode = ValidateImageCodeUtils.getSecurityCode();

BufferedImage image = ValidateImageCodeUtils.createImage(securityCode);

// 存入session作用域中

session.setAttribute(“code”, securityCode);

// 响应图片

ServletOutputStream os = response.getOutputStream();

ImageIO.write(image, “png”, os);

}

}

前端页面


这里就把 登陆页面login.html 和 注册页面regist.html 的文件放出来(能体会到后端效果即可),完整项目可以去 https://github.com/szluyu99/ems_thymeleaf

login.htmlregist.html 放到 resources/templates/ems 下:(css、img这些请去GitHub获取,没有这些不影响项目功能)

在这里插入图片描述

登录页面 login.html

login

2009/11/20


main

login

class=“form_table”>

username:

password:

ABC@126.com

注册页面 regist.html

regist

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
img

最后

如果觉得本文对你有帮助的话,不妨给我点个赞,关注一下吧!

tp-equiv=“Content-Type” content=“text/html; charset=UTF-8”>

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-uw8VK66b-1710416363625)]
[外链图片转存中…(img-pOHFgrUY-1710416363626)]
[外链图片转存中…(img-BF91oTAb-1710416363627)]

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
[外链图片转存中…(img-8Az8bJPS-1710416363627)]

最后

如果觉得本文对你有帮助的话,不妨给我点个赞,关注一下吧!

[外链图片转存中…(img-kca0Z1kt-1710416363628)]

[外链图片转存中…(img-9X48K05k-1710416363628)]

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐