href=“https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css”
rel=“stylesheet”>
修改员工
method=“post” enctype=“multipart/form-data”>
id
姓名:
当前头像:
选择新头像:
工资:
生日
返回员工列表
配置MvcConfig
通过这里配置:不需要再为每一个访问thymeleaf模板页面单独开发一个controller请求了跳转页面了
package com.blb.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
//通过这里配置:不需要再为每一个访问thymeleaf模板页面单独开发一个controller请求了
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(“login”).setViewName(“login”);
registry.addViewController(“register”).setViewName(“register”);
registry.addViewController(“addEmp”).setViewName(“addEmp”);
}
}
用户模块
实体类
User实体类
package com.blb.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Accessors(chain = true)
public class User {
private Integer id;
private String username;
private String realname;
private String password;
private Boolean gender;
}
注册
验证码实现
核心步骤:
-
生成随机字符串
-
放入session
-
生成图片并响应
验证码工具类
package com.blb.utils;
import org.apache.log4j.Logger;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Arrays;
public class VerifyCodeUtils {
private static final Logger logger = Logger.getLogger(VerifyCodeUtils.class);
private VerifyCodeUtils() {
}
public static final String VERIFY_CODES = “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”;
private static SecureRandom random = new SecureRandom();
/**
-
使用系统默认字符源生成验证码
-
@param verifySize 验证码长度
-
@return
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
-
使用指定源生成验证码
-
@param verifySize 验证码长度
-
@param sources 验证码字符源
-
@return
*/
public static String generateVerifyCode(int verifySize, String sources){
String _sources = sources;
if(_sources == null || _sources.length() == 0){
_sources = VERIFY_CODES;
}
int codesLen = _sources.length();
SecureRandom rand = new SecureRandom();
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(_sources.charAt(rand.nextInt(codesLen-1)));
}
return verifyCode.toString();
}
/**
-
生成随机验证码文件,并返回验证码值
-
@param w
-
@param h
-
@param outputFile
-
@param verifySize
-
@return
-
@throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
-
输出随机验证码图片流,并返回验证码值
-
@param w
-
@param h
-
@param os
-
@param verifySize
-
@return
-
@throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
-
生成指定验证码图像文件
-
@param w
-
@param h
-
@param outputFile
-
@param code
-
@throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
if(outputFile == null){
return;
}
File dir = outputFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
}
FileOutputStream fos = null;
try{
outputFile.createNewFile();
fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
} catch(IOException e){
logger.error(“生成指定验证码图像文件”, e);
} finally {
try {
fos.close();
} catch (IOException e) {
logger.error(“生成指定验证码图像文件”, e);
}
}
}
/**
-
输出指定验证码图片流
-
@param w
-
@param h
-
@param os
-
@param code
-
@throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
SecureRandom rand = new SecureRandom();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for(int i = 0; i < colors.length; i++){
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor©;// 设置背景色
g2.fillRect(0, 2, w, h-4);
//绘制干扰线
SecureRandom random = new SecureRandom();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h-4;
Font font = new Font(“Algerian”, Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for(int i = 0; i < verifySize; i++){
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
}
g2.dispose();
ImageIO.write(image, “jpg”, os);
}
private static Color getRandColor(int fc, int bc) {
int _fc = fc;
int _bc = bc;
if (_fc > 255)
{
_fc = 255;
}
if (_bc > 255)
{
_bc = 255;
}
int r = _fc + random.nextInt(_bc - _fc);
int g = _fc + random.nextInt(_bc - _fc);
int b = _fc + random.nextInt(_bc - _fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
- Math.sin((double) i / (double) period
- (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
- Math.sin((double) i / (double) period
- (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
验证码生成controller
借助工具类生成图片用流的方式响应给网页,因为只能有一个响应流所有这个返回值只能是void不能进行跳转
存到session作用域的原因是后面,不仅要响应给前端页面,注册时还要判断验证码是否输入正确
/**
-
生成验证码
*/
@RequestMapping(“/generateImageCode”)
public void generateImageCode(HttpSession session, HttpServletResponse response) throws IOException {
//1.生成4位随机字符串
String code= VerifyCodeUtils.generateVerifyCode(4);
//2.保存随机字符串到session中
session.setAttribute(“code”,code);
//3.将随机字符串生成图片
//4.response响应图片
response.setContentType(“image/png”);//指定响应类型
ServletOutputStream outputStream = response.getOutputStream();
//参数 宽,高,输出流,生成验证码
VerifyCodeUtils.outputImage(100,60,outputStream,code);
}
注册UserMapper
@Repository
public interface UserMapper {
//根据用户名查询用户
User findByUserName(String username);
//注册用户
void save(User user);
}
注册UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>insert into user values (#{id},#{username},#{realname},#{password},#{gender})
select * from user where username=#{username}
注册service
public void register(User user) {
//根据用户名查询数据库是否存在该用户名
User userDB = userMapper.findByUserName(user.getUsername());
//判断用户是否存在
if(!ObjectUtils.isEmpty(userDB)){//如果userDB不为空
throw new RuntimeException(“用户名已存在”);
}
// 进行注册之前给明文加密
String passwordSecret = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
user.setPassword(passwordSecret);
userMapper.save(user);
}
注册controller
根据用户输入验证码比较session中验证码一致
如果一致完成注册,如果不一致直接返回错误
完成注册向数据库中保存用户信息
保存信息前判断当前用户名是否存在,如果存在直接返回错误
如果当前用户名不存在,加密并保存用户信息
/**
- 用户注册
*/
@RequestMapping(value = “/register”)
public String register(User user, String code, HttpSession session){
log.debug(“接收到的验证码:{}”,code);
log.debug(“用户名:{},真实姓名:{},密码:{},性别:{}”,user.getUsername(),user.getRealname(),user.getPassword(),user.getGender());
try {
//1.比较用户输入的验证码和session中的验证码是否一致
String sessionCode=session.getAttribute(“code”).toString();
//忽略大小写比较
if(!sessionCode.equalsIgnoreCase(code)){
throw new RuntimeException(“验证码输入错误”);
}
//注册用户
userService.register(user);
}
catch (RuntimeException e){
e.printStackTrace();
return “redirect:/register”;//注册失败回到注册页面
}
return “redirect:/login”;//注册成功回到登录页面
}
登录
登录service
public interface UserService {
public void register(User user);
User login(String username, String password);
}
登录serviceImpl
//用户登录
@Override
public User login(String username, String password) {
//根据用户输入的用户名查询数据是否存在
User userDB = userMapper.findByUserName(username);
//判断对象是否存在
if(ObjectUtils.isEmpty(userDB)){
throw new RuntimeException(“用户名输入错误”);
}
if(!userDB.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8))) )
{
throw new RuntimeException(“密码输入错误”);
}
return userDB;
}
登录controller
/**
-
用户登录
*/
@RequestMapping(value = “/login”)
public String login(String username,String password,HttpSession session){
log.debug(“接收到的用户名:{},密码:{}”,username,password);
try {
//执行登录业务逻辑
User user = userService.login(username, password);
//登录成功,保存用户登录记录
session.setAttribute(“user”,user);
}catch (RuntimeException e){
e.printStackTrace();
session.setAttribute(“loginmsg”,e.getMessage());
return “redirect:/login”;//登录失败回到登录页面
}
return “redirect:/employee//queryAllEmployees”;//登录成功,跳转到查询员工信息控制器
}
用户退出
清除session作用域里的user即可
/**
-
用户退出
-
@param session
-
@return
*/
@RequestMapping(“/logout”)
public String logout(HttpSession session){
session.invalidate();
return “redirect:/login”;
}
员工模块
员工实体类
Employee
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Accessors(chain = true)
public class Employee {
private Integer id;
private String name;
@DateTimeFormat(fallbackPatterns = “yyyy-MM-dd”)
private Date birthday;
private double salary;
private String photo;
}
查询所有员工信息
EmployeeMapper
@Repository
public interface EmployeeMapper {
//查询员工信息列表
List queryAllEmp();
}
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>select * from employee
EmployeeService
public interface EmployeeService {
//查询员工信息列表
List queryAllEmp();
}
EmployeeServiceImpl
@Service
@Repository
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
private EmployeeMapper employeeMapper;
@Override
public List queryAllEmp() {
return employeeMapper.queryAllEmp();
}
}
controller
@Controller
@RequestMapping(“/employee”)
public class EmployeeController {
private static final Logger log = LoggerFactory.getLogger(EmployeeController.class);
@Autowired
private EmployeeService employeeService;
@RequestMapping(“/queryAllEmployees”)
public String queryAllEmployees(Model model){
List employees = employeeService.queryAllEmp();
model.addAttribute(“list”,employees);
return “emplist”;
}
}
添加员工信息
EmployeeMapper
@Repository
public interface EmployeeMapper {
//查询员工信息列表
List queryAllEmp();
void save(Employee employee);
}
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>insert into employee values(#{id},#{name},#{salary},#{birthday},#{photo})
select * from employee
EmployeeService
public interface EmployeeService {
//查询员工信息列表
List queryAllEmp();
//添加员工信息
void addEmployee(Employee employee);
}
EmployeeServiceImpl
@Service
@Repository
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
private EmployeeMapper employeeMapper;
@Override
public List queryAllEmp() {
return employeeMapper.queryAllEmp();
}
@Override
public void addEmployee(Employee employee) {
employeeMapper.save(employee);
}
}
controller
/**
-
添加员工信息
-
文件上传:表单方式提交必须是post,表单enctype属性必须为 multipart/form-data
-
@return
*/
@RequestMapping(“/addEmployee”)
public String addEmployee(Employee employee, MultipartFile img){
log.debug(“员工名称:{},员工工资{},员工生日{}”,employee.getName(),employee.getSalary(),employee.getBirthday());
log.debug(“头像名称:{}”,img.getOriginalFilename());
log.debug(“头像大小:{}”,img.getSize());
//处理头像的上传
String fileName=img.getOriginalFilename();//获取文件名以及后缀
fileName= UUID.randomUUID()+“_”+fileName;//重新生成文件夹名
//指定上传文件的路径存储,这里是静态资源static的upload
String path=System.getProperty(“user.dir”);
String dirPath=path+“/src/main/resources/static/photo”;
File filePath=new File(dirPath);
if(!filePath.exists()){
filePath.mkdirs();
}
try {
//2.上传文件 参数:将文件写入到那个目录
img.transferTo(new File(dirPath,fileName));
} catch (IOException e) {
e.printStackTrace();
}
//保存员工信息
employee.setPhoto(fileName);//保存头像文件名
employeeService.addEmployee(employee);
return “redirect:/employee/queryAllEmployees”;
}
修改员工
EmployeeMapper
@Repository
public interface EmployeeMapper {
//查询员工信息列表
List queryAllEmp();
//保存员工信息
void save(Employee employee);
//根据id查询一个员工信息
Employee queryById(Integer id);
//更新员工信息
void updateEmployee(Employee employee);
}
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>insert into employee values(#{id},#{name},#{salary},#{birthday},#{photo})
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加V获取:vip1024b (备注Java)
最后
每年转战互联网行业的人很多,说白了也是冲着高薪去的,不管你是即将步入这个行业还是想转行,学习是必不可少的。作为一个Java开发,学习成了日常生活的一部分,不学习你就会被这个行业淘汰,这也是这个行业残酷的现实。
如果你对Java感兴趣,想要转行改变自己,那就要趁着机遇行动起来。或许,这份限量版的Java零基础宝典能够对你有所帮助。
interface EmployeeMapper {
//查询员工信息列表
List queryAllEmp();
//保存员工信息
void save(Employee employee);
//根据id查询一个员工信息
Employee queryById(Integer id);
//更新员工信息
void updateEmployee(Employee employee);
}
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>insert into employee values(#{id},#{name},#{salary},#{birthday},#{photo})
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-z89Iv35q-1711787670627)]
[外链图片转存中…(img-ET7Q6mkG-1711787670628)]
[外链图片转存中…(img-qqsKYXT3-1711787670628)]
[外链图片转存中…(img-DWSY6WzU-1711787670629)]
[外链图片转存中…(img-gupVaqxf-1711787670629)]
[外链图片转存中…(img-JA7YDjuh-1711787670629)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加V获取:vip1024b (备注Java)
[外链图片转存中…(img-lAnheEcR-1711787670630)]
最后
每年转战互联网行业的人很多,说白了也是冲着高薪去的,不管你是即将步入这个行业还是想转行,学习是必不可少的。作为一个Java开发,学习成了日常生活的一部分,不学习你就会被这个行业淘汰,这也是这个行业残酷的现实。
如果你对Java感兴趣,想要转行改变自己,那就要趁着机遇行动起来。或许,这份限量版的Java零基础宝典能够对你有所帮助。
[外链图片转存中…(img-CVhlHAo8-1711787670630)]