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 是现在最为流行的权限认证开发框架,与它起名的只有最初 ...
随机推荐
- 我通过调试ConcurrentLinkedQueue发现一个IDEA的小虫子(bug), vscode复现, eclipse毫无问题
前言: 本渣渣想分析分析Doug Lea大佬对高并发代码编写思路, 于是找到了我们今天的小主角ConcurrentLinkedQueue进行鞭打, 说实话草稿我都打好了, 就差临门一脚, 给踢折了 直 ...
- (转) PHP实现从1累加到100(1+2+….+100=)的几种思路,挺有意思的!!!
一个经典的小学问题也是一个简单的PHP小应用,1+2+3--100=多少?使用PHP应该怎么写? 这里总结了以下几种思路: 1.普通PHPer: $sum=0;for($i=1;$i<=100; ...
- linux学习之路第二天(xshell和xftp的使用图解)
以上xshell的连接过程 2.远程上传和下载文件xftp6 一定要换成22和sftp,否则连接不上 如果出现中文乱码的情况 先点击那个小齿轮 再点击选项 把编码编程UTF-8就ok了
- Robotframework学习笔记之—Rrobotframework运行报错“command: pybot.bat --argumentfile”
Rrobotframework运行报错"command: pybot.bat --argumentfile" 解决方案: 1.可能是缺失文件: 1.1.检查python安装目录下的 ...
- android开发相关知识笔记
1.xpage页面打开: openPage(TestFragment.class) openPage("标识") // 页面打开等待结果返回: openPageForResult( ...
- OpenResty简介
OpenResty(也称为 ngx_openresty)是一个全功能的 Web 应用服务器.它打包了标准的 Nginx 核心,很多的常用的第三方模块,以及它们的大多数依赖项. 通过揉和众多设计良好的 ...
- 5.Java流程控制
所有的流程控制语句都可以相互嵌套.互不影响 一.用户交互Scanner Scanner对象 之前我们学的基本语法中我们并没有实现程序和人的交互,但是Java给我们提供了这样一个工具类,我们可以获取用户 ...
- Django基础009--Paginator分页
1.引入 from django.core.paginator import Paginator 2.Paginator对象提供的方法 articles = models.Article.object ...
- Node性能如何进行监控以及优化?
一. 是什么 Node作为一门服务端语言,性能方面尤为重要,其衡量指标一般有如下: CPU 内存 I/O 网络 CPU 主要分成了两部分: CPU负载:在某个时间段内,占用以及等待CPU的进程总数 C ...
- YsoSerial 工具常用Payload分析之CC3(二)
这是CC链分析的第二篇文章,我想按着common-collections的版本顺序来介绍,所以顺序为 cc1.3.5.6.7(common-collections 3.1),cc2.4(common- ...