SpringBoot开发十二-账号设置
需求介绍—账号设置
账号设置里面的上传头像(文件)
首先请求必须是一个 POST 请求,其次表单的属性 enctype = “multipart/form-data”
然后就是利用 MultipartFile 处理上传文件。
然后就是访问账号设置页面,上传头像,获取头像。
代码实现
我们的头像上传之后是存放到我们的服务器硬盘之上,所以我们需要在 application.properties配置一下我们的资源上传之后是存放到了哪里
# community
community.path.domain=http://localhost:8080
community.path.upload=f:/nowcoder/data/upload
我们上传完文件最终是需要更新用户的 HeaderUrl,所以 Service 就需要提供一个方法改变这个 URL,然后上传文件的事情我们就在 Controller 里面解决掉,业务层只解决更新路径的这个业务就可以了。
那么在 UserService 里面追加一个方法更新用户的 URL
public int updateHeader(int userId, String headerUrl) {
return userMapper.updateHeader(userId, headerUrl);
}
// 重置密码
public Map<String, Object> resetPassword(String email, String password) {
Map<String, Object> map = new HashMap<>();
// 空值处理
if (StringUtils.isBlank(email)) {
map.put("emailMsg", "邮箱不能为空!");
return map;
}
if (StringUtils.isBlank(password)) {
map.put("passwordMsg", "密码不能为空!");
return map;
}
// 验证邮箱
User user = userMapper.selectByEmail(email);
if (user == null) {
map.put("emailMsg", "该邮箱尚未注册!");
return map;
}
// 重置密码
password = CommunityUtil.md5(password + user.getSalt());
userMapper.updatePassword(user.getId(), password);
map.put("user", user);
return map;
}
// 修改密码
public Map<String, Object> updatePassword(int userId, String oldPassword, String newPassword) {
Map<String, Object> map = new HashMap<>();
// 空值处理
if (StringUtils.isBlank(oldPassword)) {
map.put("oldPasswordMsg", "原密码不能为空!");
return map;
}
if (StringUtils.isBlank(newPassword)) {
map.put("newPasswordMsg", "新密码不能为空!");
return map;
}
// 验证原始密码
User user = userMapper.selectById(userId);
oldPassword = CommunityUtil.md5(oldPassword + user.getSalt());
if (!user.getPassword().equals(oldPassword)) {
map.put("oldPasswordMsg", "原密码输入有误!");
return map;
}
// 更新密码
newPassword = CommunityUtil.md5(newPassword + user.getSalt());
userMapper.updatePassword(userId, newPassword);
return map;
}
首先新建一个 UserController 实现对于用户的一些请求
package com.nowcoder.community.controller; import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map; @Controller
@RequestMapping("/user")
public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Value("${community.path.upload}")
private String uploadPath; @Value("${community.path.domain}")
private String domain; @Value("${server.servlet.context-path}")
private String contextPath; @Autowired
private UserService userService; @Autowired
private HostHolder hostHolder; @LoginRequired
@RequestMapping(path = "/setting", method = RequestMethod.GET)
public String getSettingPage() {
return "/site/setting";
} @LoginRequired
@RequestMapping(path = "/upload", method = RequestMethod.POST)
public String uploadHeader(MultipartFile headerImage, Model model) {
if (headerImage == null) {
model.addAttribute("error", "您还没有选择图片!");
return "/site/setting";
} String fileName = headerImage.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
if (StringUtils.isBlank(suffix)) {
model.addAttribute("error", "文件的格式不正确!");
return "/site/setting";
} // 生成随机文件名
fileName = CommunityUtil.generateUUID() + suffix;
// 确定文件存放的路径
File dest = new File(uploadPath + "/" + fileName);
try {
// 存储文件
headerImage.transferTo(dest);
} catch (IOException e) {
logger.error("上传文件失败: " + e.getMessage());
throw new RuntimeException("上传文件失败,服务器发生异常!", e);
} // 更新当前用户的头像的路径(web访问路径)
// http://localhost:8080/community/user/header/xxx.png
User user = hostHolder.getUser();
String headerUrl = domain + contextPath + "/user/header/" + fileName;
userService.updateHeader(user.getId(), headerUrl); return "redirect:/index";
} @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
// 服务器存放路径
fileName = uploadPath + "/" + fileName;
// 文件后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
// 响应图片
response.setContentType("image/" + suffix);
try (
FileInputStream fis = new FileInputStream(fileName);
OutputStream os = response.getOutputStream();
) {
byte[] buffer = new byte[1024];
int b = 0;
while ((b = fis.read(buffer)) != -1) {
os.write(buffer, 0, b);
}
} catch (IOException e) {
logger.error("读取头像失败: " + e.getMessage());
}
} // 修改密码
@LoginRequired
@RequestMapping(path = "/updatePassword", method = RequestMethod.POST)
public String updatePassword(String oldPassword, String newPassword, Model model) {
User user = hostHolder.getUser();
Map<String, Object> map = userService.updatePassword(user.getId(), oldPassword, newPassword);
if (map == null || map.isEmpty()) {
return "redirect:/logout";
} else {
model.addAttribute("oldPasswordMsg", map.get("oldPasswordMsg"));
model.addAttribute("newPasswordMsg", map.get("newPasswordMsg"));
return "/site/setting";
}
}
}
最后就是处理页面的逻辑了。
SpringBoot开发十二-账号设置的更多相关文章
- SpringBoot第十二集:度量指标监控与异步调用(2020最新最易懂)
SpringBoot第十二集:度量指标监控与异步调用(2020最新最易懂) Spring Boot Actuator是spring boot项目一个监控模块,提供了很多原生的端点,包含了对应用系统的自 ...
- 专题开发十二:JEECG微云高速开发平台-基础用户权限
专题开发十二:JEECG微云高速开发平台-基础用户权限 11.3.4自己定义button权限 Jeecg中.眼下button权限设置,是通过对平台自己封装的button标签(<t:dgFun ...
- STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
目录 STC8H开发(一): 在Keil5中配置和使用FwLib_STC8封装库(图文详解) STC8H开发(二): 在Linux VSCode中配置和使用FwLib_STC8封装库(图文详解) ST ...
- 敏捷宣言(Agile Manifesto)和敏捷开发十二原则
敏捷宣言 The Agile Manifesto Individuals and interactions over Process and tools 个体与交互 重于 过程和工具 Working ...
- SpringBoot系列(十二)过滤器配置详解
SpringBoot(十二)过滤器详解 往期精彩推荐 SpringBoot系列(一)idea新建Springboot项目 SpringBoot系列(二)入门知识 springBoot系列(三)配置文件 ...
- Java微信公众平台开发(十二)--微信用户信息的获取
转自:http://www.cuiyongzhi.com/post/56.html 前面的文章有讲到微信的一系列开发文章,包括token获取.菜单创建等,在这一篇将讲述在微信公众平台开发中如何获取微信 ...
- SpringBoot(十二):SpringBoot整合Mybatis-Plus
本节版本虽然只用到了基本特性,但可以满足大部分的增删改查. 一.环境准备SpringBoot 1.5.10.RELEASEMybatis-Plus 2.1.9Mybatis-Plus 官方地址:htt ...
- SpringBoot入门 (十二) 定时任务
本文记录在SpringBoot中使用定时任务. 在我们的项目中,经常需要用到定时任务去帮我们做一些事情,比如服务状态监控,业务数据状态的更改等,SpringBoot中实现定时任务有2中方案,一种是自带 ...
- SpringBoot系列十二:SpringBoot整合 Shiro
声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合 Shiro 2.具体内容 Shiro 是现在最为流行的权限认证开发框架,与它起名的只有最初 ...
随机推荐
- Web 前端开发规范手册
一.规范目的 Web 前端开发规范手册 1.1 概述 ......................................................................... ...
- 面试题三:MySQL
MySQL有哪些存储引擎? MyISAM.InnoDB.CSV.Memory等 MyISAM和InnoDB比较: InnoDB MyISAM 事务 支持 不支持 存储限制 64TB 无 锁粒度 行锁 ...
- Linux学习之路第十天(网路配置)
网路配置 Linux配置原理图(含虚拟机) 目前我们的网路配置采用NAT. 2.查看网络ip和网关 查看虚拟网络编辑器 修改ip地址(修改虚拟网卡的ip) 修改就完事了. 3.查看网关 Linux网络 ...
- docker起不来报错:Failed to start Docker Application Container Engine.
报错信息如下: [root@localhost localdisk]# systemctl restart docker Job for docker.service failed because t ...
- 保存TextBox中的文字为Path功能
保存TextBox中的文字为Path功能 今天再设计一个我自己程序的Icon时使用了Path+textbox做了图形,我不想导出为PNG,因为颜色比较单一,我又想通过代码控制颜色,所以我想完整的保存为 ...
- vue3 script setup 定稿
vue script setup 已经官宣定稿.本文主要翻译了来自 0040-script-setup 的内容. 摘要 在单文件组件(SFC)中引入一个新的 <script> 类型 set ...
- VBA收集
EXCEL启用宏 1.excel另存为"启用宏的XLSM"的文件格式 excel2007打开显示"宏的工具栏" 点击"左上角的OFFICE按钮&quo ...
- urllib库中的URL编码解码和GETPOST请求
在urllib库的使用过程中,会在请求发送之前按照发送请求的方式进行编码处理,来使得传递的参数更加的安全,也更加符合模拟浏览器发送请求的形式.这就需要用urllib中的parse模块.parse的使用 ...
- ES6 数值类型常用方法
ES6 数值类型常用方法 <script type="text/javascript"> // Number常用方法 /* Number.isFinite() 用来检查 ...
- PAT乙级:1063 计算谱半径 (20分)
PAT乙级:1063 计算谱半径 (20分) 题干 在数学中,矩阵的"谱半径"是指其特征值的模集合的上确界.换言之,对于给定的 n 个复数空间的特征值 { a1+b1i,⋯,a** ...