UserController.java
14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package com.qgutech.controller;
import com.qgutech.common.JsonResult;
import com.qgutech.model.Page;
import com.qgutech.model.User;
import com.qgutech.service.UserService;
import com.qgutech.util.CookieUtil;
import com.qgutech.util.LoginCookieUtil;
import com.qgutech.util.PowerUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* @author xxx
* @date 2024/12/17 12:10
* @description
*/
@Slf4j
@Controller
@RequestMapping(value = "/user")
public class UserController {
private final String POWER_SESSION_ID = "power_session_id";
@Resource
private UserService userService;
@Value("${power.user.dir}")
private String USER_DIR;
@RequestMapping("/page")
public String page(String searchName, Map<String, Object> map, @RequestParam(required = false, defaultValue = "1") Integer pageNo) {
Page<User> page = new Page<>();
if (null != pageNo) {
page.setPageNo(pageNo);
}
List<User> users = userService.getUserList(searchName, page);
if (CollectionUtils.isNotEmpty(users)) {
for (User user : users) {
String photo = user.getPhoto();
if (StringUtils.isBlank(photo)) {
user.setPhoto("default.jpg");
}
}
}
map.put("list", users);
map.put("current", pageNo);
map.put("total", page.getTotal());
map.put("pages", page.getPages());
map.put("searchName", searchName);
return "indexUser";
}
/**
* 用户登录
*/
@PostMapping(value = "/login")
public String login(String loginName, String password, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
// String loginName = paramUser.getLoginName();
// String password = paramUser.getPassword();
log.debug("接收到的用户名:{},密码:{}", loginName, password);
if (StringUtils.isBlank(loginName) || StringUtils.isBlank(password)) {
request.setAttribute("msg", "用户名或密码不能为空!");
return "login";//登录失败回到登录页面
}
try {
//执行登录业务逻辑
User user = userService.login(loginName, password);
//登录成功,保存用户登录记录
session.setAttribute("user", user);
String powerSessionId = UUID.randomUUID().toString().replaceAll("-", "");
setCookie(powerSessionId, request, response);
} catch (RuntimeException e) {
e.printStackTrace();
request.setAttribute("msg", e.getMessage());
return "login";//登录失败回到登录页面
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/user/page";//登录成功,跳转到查询员工信息控制器
// return "indexUser";//登录成功,跳转到查询员工信息控制器
}
/**
* 用户登录H5
*/
@PostMapping(value = "/userLogin")
@ResponseBody
public JsonResult<?> userLogin(@RequestBody User param, HttpServletRequest request, HttpServletResponse response) {
String msg = "成功";
String powerSessionId = UUID.randomUUID().toString().replaceAll("-", "");
Map<String, Object> resultMap = new HashMap<>();
resultMap.put(POWER_SESSION_ID, powerSessionId);
try {
//执行登录业务逻辑
String loginName = param.getLoginName();
String password = param.getPassword();
if (StringUtils.isBlank(loginName) || StringUtils.isBlank(password)) {
msg = "用户名或密码不能为空!";
return new JsonResult<>(false, msg, "");
}
User user = userService.login(loginName, password);
if (user != null) {
String photo = user.getPhoto();
if (StringUtils.isBlank(photo)) {
user.setPhoto("default.jpg");
}
}
resultMap.put("user", user);
//登录成功,保存用户登录记录
setCookie(powerSessionId, request, response);
} catch (RuntimeException e) {
e.printStackTrace();
msg = e.getMessage();
return new JsonResult<>(false, msg, "");
}
return new JsonResult<>(true, msg, resultMap);
}
private void setCookie(String powerSessionId, HttpServletRequest request, HttpServletResponse response) {
String cookieDomain = CookieUtil.getCookieDomain(request);
String scheme = request.getScheme();
boolean secure = false;
boolean httpOnly = false;
if ("https".equals(scheme)) {
secure = true;
httpOnly = false;
}
LoginCookieUtil.addCookie(response, POWER_SESSION_ID, powerSessionId,
"/", null, cookieDomain, secure, httpOnly);
}
/**
* 用户注册
*/
@RequestMapping(value = "/register")
public String register(User user, String code, HttpSession session) {
log.debug("接收到的验证码:{}", code);
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";//注册成功回到登录页面
}
/**
* 添加员工信息
* 文件上传:表单方式提交必须是post,表单enctype属性必须为 multipart/form-data
*
* @return
*/
@PostMapping("/saveUser")
public String saveUser(User user, Model model, MultipartFile img) {
log.info("=========user==[{}]", user);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
user.setUserId(uuid);
String mobile = user.getMobile();
if (StringUtils.isEmpty(mobile)) {
model.addAttribute("saveMsg", "手机号不能为空");
return "addUser";
}
User oldUser = userService.getUserByMobile(mobile);
if (oldUser != null) {
model.addAttribute("saveMsg", "手机号已被使用!");
return "addUser";
}
//处理头像的上传
String fileName = img.getOriginalFilename();//获取文件名以及后缀
fileName = UUID.randomUUID() + "_" + fileName;//重新生成文件夹名
//指定上传文件的路径存储,这里是静态资源static的upload
String dirPath = USER_DIR + "/photo";
File filePath = new File(dirPath);
if (!filePath.exists()) {
filePath.mkdirs();
}
try {
//2.上传文件 参数:将文件写入到那个目录
img.transferTo(new File(dirPath, fileName));
} catch (IOException e) {
e.printStackTrace();
}
//保存员工信息
user.setPhoto(fileName);//保存头像文件名
user.setLoginName(mobile);
userService.saveUser(user);
return "redirect:/user/page";
}
@RequestMapping("/getUser/{userId}")
@ResponseBody
public User getUser(@PathVariable("userId") String id) {
return userService.getUserById(id);
}
@RequestMapping("/deleteUser/{userId}")
public String deleteUser(@PathVariable("userId") String userId) {
userService.deleteUserById(userId);
return "redirect:/user/page";
}
/**
* 用户退出
*
* @param request
* @return
*/
@RequestMapping("/logout")
public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception {
session.invalidate();
Cookie sessionIdCookie = CookieUtil.getCookie(request, POWER_SESSION_ID);
if (sessionIdCookie != null) {
String powerSessionId = sessionIdCookie.getValue();
if (powerSessionId != null) {
CookieUtil.setCookie(response, POWER_SESSION_ID, null,
"/", "0", CookieUtil.getCookieDomain(request));
request.removeAttribute(powerSessionId);
}
}
return "redirect:/login";
}
/**
* 用户退出H5
*
* @param request
* @return
*/
@RequestMapping("/userLogout")
@ResponseBody
public JsonResult<?> userLogout(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception {
session.invalidate();
Cookie sessionIdCookie = CookieUtil.getCookie(request, POWER_SESSION_ID);
if (sessionIdCookie != null) {
String powerSessionId = sessionIdCookie.getValue();
if (powerSessionId != null) {
CookieUtil.setCookie(response, POWER_SESSION_ID, null,
"/", "0", CookieUtil.getCookieDomain(request));
request.removeAttribute(powerSessionId);
}
}
return new JsonResult<>(true, "退出成功!", "");
}
/**
* 生成验证码
*/
@RequestMapping("/generateImageCode")
public void generateImageCode(HttpSession session, HttpServletResponse response) throws IOException {
//1.生成4位随机字符串
String code = PowerUtil.generateVerifyCode(4);
//2.保存随机字符串到session中
session.setAttribute("code", code);
//3.将随机字符串生成图片
//4.response响应图片
response.setContentType("image/png");//指定响应类型
ServletOutputStream outputStream = response.getOutputStream();
//参数 宽,高,输出流,生成验证码
PowerUtil.outputImage(100, 60, outputStream, code);
}
@RequestMapping("/toUpdateUser/{userId}")
public String toUpdateUser(@PathVariable("userId") String userId, Model model) {
User user = userService.getUserById(userId);
model.addAttribute("user", user);
return "updateUser";
}
/**
* 更新员工信息
*
* @param user
* @return
*/
@RequestMapping("/updateUser")
public String updateUser(User user, Model model) {
String userName = user.getUserName();
if (StringUtils.isBlank(userName)) {
model.addAttribute("updateMsg", "姓名不能为空");
return "updateUser";
}
String mobile = user.getMobile();
if (StringUtils.isEmpty(mobile)) {
model.addAttribute("updateMsg", "手机号不能为空");
return "updateUser";
}
User oldUser = userService.getUserById(user.getUserId());
String loginName = oldUser.getLoginName();
Boolean isExistMobile = userService.isExistMobile(mobile, loginName);
if (isExistMobile) {
model.addAttribute("updateMsg", "手机号已被使用!");
return "updateUser";
}
if ("admin".equals(loginName)) {
user.setLoginName("admin");
} else {
user.setLoginName(mobile);
}
userService.updateUser(user);
//跳转员工列表
return "redirect:/user/page";//更新成功跳转到查询所有员工列表
}
@RequestMapping("/toUpdatePasswd/{userId}")
public String toUpdatePassword(@PathVariable("userId") String userId, Model model) {
User user = userService.getUserById(userId);
model.addAttribute("user", user);
return "updatePasswd";
}
/**
* 更新员工信息
*
* @param user
* @return
*/
@RequestMapping("/updatePassword")
public String updatePassword(User user, Model model) {
String oldPassword = user.getOldPassword();
if (StringUtils.isBlank(oldPassword)) {
model.addAttribute("pdMsg", "原密码不能为空");
return "updatePasswd";
}
String password = user.getPassword();
if (StringUtils.isBlank(password)) {
model.addAttribute("pdMsg", "新密码不能为空");
return "updatePasswd";
}
User oldUser = userService.getUserById(user.getUserId());
String dbPassword = oldUser.getPassword();
String paramPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes(StandardCharsets.UTF_8));
if (!paramPassword.equals(dbPassword)) {
model.addAttribute("pdMsg", "原密码不正确");
return "updatePasswd";
}
String newPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
userService.updatePassword(user.getUserId(), newPassword);
//跳转员工列表
return "redirect:/user/page";//更新成功跳转到查询所有员工列表
}
@RequestMapping("/resertPasswd/{userId}")
public String resertPasswd(@PathVariable("userId") String userId, Model model) {
String newPassword = DigestUtils.md5DigestAsHex("hczd".getBytes(StandardCharsets.UTF_8));
userService.updatePassword(userId, newPassword);
//跳转员工列表
return "redirect:/user/page";//更新成功跳转到查询所有员工列表
}
}