diff --git a/boot-service/src/main/java/com/xwbing/constant/CommonConstant.java b/boot-service/src/main/java/com/xwbing/constant/CommonConstant.java index 27a33f3..7dfab65 100644 --- a/boot-service/src/main/java/com/xwbing/constant/CommonConstant.java +++ b/boot-service/src/main/java/com/xwbing/constant/CommonConstant.java @@ -27,14 +27,14 @@ public class CommonConstant { /** * 邮件服务器配置项 */ - public static final String SYSCONFIG_EMAILCONFIGKEY = "email_config"; + public static final String EMAIL_KEY = "email_config"; /** * * 当前登录用户 */ - public static final String SESSION_CURRENT_USER = "current_user"; + public static final String CURRENT_USER = "current_user"; /** * 当前登录用户id */ - public static final String SESSION_CURRENT_USER_ID = "current_id"; + public static final String CURRENT_USER_ID = "current_id"; } diff --git a/boot-service/src/main/java/com/xwbing/constant/CommonEnum.java b/boot-service/src/main/java/com/xwbing/constant/CommonEnum.java index 014e54d..2e313c8 100644 --- a/boot-service/src/main/java/com/xwbing/constant/CommonEnum.java +++ b/boot-service/src/main/java/com/xwbing/constant/CommonEnum.java @@ -1,7 +1,10 @@ package com.xwbing.constant; +import com.alibaba.fastjson.JSONObject; + +import java.util.ArrayList; import java.util.Arrays; -import java.util.stream.Collectors; +import java.util.List; /** * 说明: 公共枚举 @@ -10,12 +13,15 @@ import java.util.stream.Collectors; * 作者: xiangwb */ public class CommonEnum { - public enum YesOrNo { + private CommonEnum() { + } + + public enum YesOrNoEnum { YES("是", "Y"), NO("否", "N"); private String name; private String code; - YesOrNo(String name, String code) { + YesOrNoEnum(String name, String code) { this.name = name; this.code = code; } @@ -29,21 +35,18 @@ public class CommonEnum { } } - /** - * 登录登出标记 - */ - public enum LoginInOut { - IN("登录", 1), OUT("登出", 2); + public enum SexEnum { + MAN("男", "1"), WOMAN("女", "0"); private String name; - private int value; + private String code; - LoginInOut(String name, int value) { + SexEnum(String name, String code) { this.name = name; - this.value = value; + this.code = code; } - public int getValue() { - return value; + public String getCode() { + return code; } public String getName() { @@ -51,34 +54,25 @@ public class CommonEnum { } } - public enum ValidateResultEnum { - SUCCESS("校验通过", 1), FAILED("校验失败", 0); - private String msg; - private int errorCode; - - ValidateResultEnum(String msg, int errorCode) { - this.msg = msg; - this.errorCode = errorCode; - } - - public String getMsg() { - return this.msg; - } - - public int getErrorCode() { - return this.errorCode; - } - } - public static void main(String[] args) { String code = "Y"; - for (YesOrNo yesOrNo : YesOrNo.values()) { - if (yesOrNo.getCode().equals(code)) { - System.out.println(yesOrNo.getName()); - break; - } +// for (YesOrNoEnum yesOrNoEnum : YesOrNoEnum.values()) { +// if (yesOrNoEnum.getCode().equals(code)) { +// System.out.println(yesOrNoEnum.getName()); +// break; +// } +// } + YesOrNoEnum yesOrNoEnum = Arrays.stream(YesOrNoEnum.values()).filter(obj -> obj.getCode().equals(code)).findFirst().get(); + System.out.println(yesOrNoEnum.getName()); + + List resultVos = new ArrayList<>(); + JSONObject jsonObject; + for (YesOrNoEnum status : YesOrNoEnum.values()) { + jsonObject = new JSONObject(); + jsonObject.put("code", status.getCode()); + jsonObject.put("name", status.getName()); + resultVos.add(jsonObject); } - YesOrNo yesOrNo = Arrays.stream(YesOrNo.values()).filter(obj -> obj.getCode().equals(code)).collect(Collectors.toList()).get(0); - System.out.println(yesOrNo.getName()); +// return resultVos; } } diff --git a/boot-service/src/main/java/com/xwbing/entity/SysConfig.java b/boot-service/src/main/java/com/xwbing/entity/SysConfig.java index 96e67f1..73a0098 100644 --- a/boot-service/src/main/java/com/xwbing/entity/SysConfig.java +++ b/boot-service/src/main/java/com/xwbing/entity/SysConfig.java @@ -5,7 +5,6 @@ import lombok.EqualsAndHashCode; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; -import javax.persistence.Column; import javax.persistence.Entity; import javax.validation.constraints.Pattern; @@ -22,11 +21,11 @@ public class SysConfig extends BaseEntity { private static final long serialVersionUID = -7587016038432881980L; public static String table = "system_config"; /** - * 配置项的key + * 配置项的code */ - @NotBlank(message = "配置项的key不能为空") - @Length(min = 1, max = 50, message = "key长度为1-50") - private String key; + @NotBlank(message = "配置项的code不能为空") + @Length(min = 1, max = 50, message = "code长度为1-50") + private String code; /** * 配置项的值 */ @@ -43,7 +42,5 @@ public class SysConfig extends BaseEntity { */ @NotBlank(message = "是否启用不能为空") @Pattern(regexp = "[Y|N]",message = "是否启用格式为Y|N") - @Column(name = "is_enable") - private String isEnable; - + private String enable; } diff --git a/boot-service/src/main/java/com/xwbing/entity/SysUser.java b/boot-service/src/main/java/com/xwbing/entity/SysUser.java index cd2206c..148b475 100644 --- a/boot-service/src/main/java/com/xwbing/entity/SysUser.java +++ b/boot-service/src/main/java/com/xwbing/entity/SysUser.java @@ -26,15 +26,27 @@ public class SysUser extends BaseEntity { * 用户名 */ @NotBlank(message = "用户名不能为空") - @Length(min = 1, max = 20, message = "长度为1-20") + @Length(min = 1, max = 20, message = "用户名长度为1-20") @Column(name = "user_name") private String userName; /** * 姓名 */ @NotBlank(message = "姓名不能为空") - @Length(min = 1, max = 20, message = "长度为1-5") + @Length(min = 1, max = 20, message = "姓名长度为1-5") private String name; + /** + * 邮箱 + */ + @NotBlank(message = "邮箱不能为空") + @Email(message = "邮箱格式有误") + private String mail; + /** + * 性别 + */ + @NotBlank(message = "性别不能为空") + @Pattern(regexp = "[01]", message = "性别格式为0|1,0代表女,1代表男") + private String sex; /** * 盐值 */ @@ -44,14 +56,11 @@ public class SysUser extends BaseEntity { */ private String password; /** - * 邮箱 + * 是否为管理员 */ - @Email - private String mail; - /** - * 性别 - */ - @NotBlank - @Pattern(regexp = "[01]", message = "性别格式为0|1,0代表女,1代表男") - private String sex; + private String admin; + //临时字段 + private transient String create; + private transient String modified; + private transient String sexName; } diff --git a/boot-service/src/main/java/com/xwbing/repository/SysConfigRepository.java b/boot-service/src/main/java/com/xwbing/repository/SysConfigRepository.java index 061cb98..2a780c3 100644 --- a/boot-service/src/main/java/com/xwbing/repository/SysConfigRepository.java +++ b/boot-service/src/main/java/com/xwbing/repository/SysConfigRepository.java @@ -3,12 +3,16 @@ package com.xwbing.repository; import com.xwbing.entity.SysConfig; import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + /** * 说明: * 项目名称: boot-module-demo * 创建时间: 2017/5/5 16:44 * 作者: xiangwb */ -public interface SysConfigRepository extends JpaRepository { - SysConfig findByKey(String code); +public interface SysConfigRepository extends JpaRepository { + SysConfig findByCode(String code); + + List findByEnable(String enable); } diff --git a/boot-service/src/main/java/com/xwbing/service/SysConfigService.java b/boot-service/src/main/java/com/xwbing/service/SysConfigService.java index ffbbc0c..fef9747 100644 --- a/boot-service/src/main/java/com/xwbing/service/SysConfigService.java +++ b/boot-service/src/main/java/com/xwbing/service/SysConfigService.java @@ -11,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; +import java.util.List; /** * 说明: @@ -22,21 +23,22 @@ import java.util.Date; public class SysConfigService { @Autowired private SysConfigRepository sysConfigRepository; - private static Logger logger= LoggerFactory.getLogger(SysConfigService.class); + private static Logger logger = LoggerFactory.getLogger(SysConfigService.class); + public RestMessage save(SysConfig sysConfig) { logger.info("保存配置信息"); RestMessage result = new RestMessage(); - sysConfig.setId(PassWordUtil.createId()); - sysConfig.setCreateTime(new Date()); - if (sysConfig==null) { + if (sysConfig == null) { throw new BusinessException("配置数据不能为空"); } - SysConfig old = findByKey(sysConfig.getKey()); - if (old!=null) { - throw new BusinessException(sysConfig.getKey() + "已存在"); + SysConfig old = findByCode(sysConfig.getCode()); + if (old != null) { + throw new BusinessException(sysConfig.getCode() + "已存在"); } + sysConfig.setId(PassWordUtil.createId()); + sysConfig.setCreateTime(new Date()); SysConfig one = sysConfigRepository.save(sysConfig); - if (one!=null) { + if (one != null) { result.setSuccess(true); result.setMessage("保存配置成功"); } else { @@ -48,8 +50,8 @@ public class SysConfigService { public RestMessage removeByCode(String code) { logger.info("删除配置信息"); RestMessage result = new RestMessage(); - SysConfig old = findByKey(code); - if (old==null) { + SysConfig old = findByCode(code); + if (old == null) { throw new BusinessException("该配置项不存在"); } sysConfigRepository.delete(old.getId()); @@ -58,7 +60,30 @@ public class SysConfigService { return result; } - public SysConfig findByKey(String key) { - return sysConfigRepository.findByKey(key); + public RestMessage update(SysConfig sysConfig) { + RestMessage result = new RestMessage(); + SysConfig old = findByCode(sysConfig.getCode()); + if (old == null) { + throw new BusinessException("该配置项不存在"); + } + old.setValue(sysConfig.getValue()); + old.setEnable(sysConfig.getEnable()); + old.setModifiedTime(new Date()); + SysConfig save = sysConfigRepository.save(old); + if (save != null) { + result.setMessage("更新成功"); + result.setSuccess(true); + } else { + result.setMessage("更新失败"); + } + return result; + } + + public SysConfig findByCode(String code) { + return sysConfigRepository.findByCode(code); + } + + public List findByEnable(String enable) { + return sysConfigRepository.findByEnable(enable); } } diff --git a/boot-service/src/main/java/com/xwbing/service/UserService.java b/boot-service/src/main/java/com/xwbing/service/UserService.java index 3c00285..206d51c 100644 --- a/boot-service/src/main/java/com/xwbing/service/UserService.java +++ b/boot-service/src/main/java/com/xwbing/service/UserService.java @@ -2,18 +2,19 @@ package com.xwbing.service; import com.alibaba.fastjson.JSONObject; import com.xwbing.constant.CommonConstant; +import com.xwbing.constant.CommonEnum; import com.xwbing.entity.SysConfig; import com.xwbing.entity.SysUser; +import com.xwbing.util.CommonDataUtil; import com.xwbing.entity.model.EmailModel; import com.xwbing.exception.BusinessException; import com.xwbing.repository.UserRepository; import com.xwbing.util.*; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Service; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; +import javax.annotation.Resource; +import java.util.Arrays; import java.util.Date; import java.util.List; @@ -25,9 +26,9 @@ import java.util.List; */ @Service public class UserService { - @Autowired + @Resource private UserRepository userRepository; - @Autowired + @Resource private SysConfigService sysConfigService; /** @@ -48,25 +49,16 @@ public class UserService { String[] res = PassWordUtil.getUserSecret(null, null); sysUser.setSalt(res[1]); sysUser.setPassword(res[2]); + // 设置否管理员 + sysUser.setAdmin(CommonEnum.YesOrNoEnum.NO.getCode()); SysUser one = userRepository.save(sysUser); if (one == null) { throw new BusinessException("新增用户失败"); } - SysConfig sysConfig = sysConfigService.findByKey(CommonConstant.SYSCONFIG_EMAILCONFIGKEY); - if (sysConfig==null) { - throw new BusinessException("没有查找到邮件配置项"); - } - EmailModel emailModel = null; - if (StringUtils.isNotEmpty(sysConfig.getKey())) { - JSONObject jsonObject = JSONObject.parseObject(sysConfig.getValue()); - emailModel = JSONObject.toJavaObject(jsonObject, EmailModel.class); - } - emailModel.setToEmail(sysUser.getMail()); - emailModel.setSubject(emailModel.getSubject()); - emailModel.setCentent(emailModel.getCentent() + " 你的用户名是:" + sysUser.getUserName() + "密码是:" + res[0]); + //发送邮件 + boolean send = sendEmail(sysUser, res[0]); // 发送邮件结束 - boolean sucess = EmailUtil.sendTextEmail(emailModel); - if (!sucess) { + if (!send) { throw new BusinessException("发送密码邮件错误"); } result.setSuccess(true); @@ -85,7 +77,14 @@ public class UserService { if (old == null) { throw new BusinessException("该对象不存在"); } + if (id.equals(CommonDataUtil.getToken(CommonConstant.CURRENT_USER_ID))) { + throw new BusinessException("不能删除当前登录用户"); + } + if (CommonEnum.YesOrNoEnum.YES.getCode().equals(old.getAdmin())) { + throw new BusinessException("不能对管理员进行删除操作"); + } userRepository.delete(id); + result.setMessage("删除成功"); result.setSuccess(true); return result; @@ -103,17 +102,24 @@ public class UserService { if (old == null) { throw new BusinessException("该对象不存在"); } + if (old.getId().equals(CommonDataUtil.getToken(CommonConstant.CURRENT_USER_ID))) { + throw new BusinessException("不能修改当前登录用户"); + } + if (CommonEnum.YesOrNoEnum.YES.getCode().equals(old.getAdmin())) { + throw new BusinessException("不能对管理员进行修改操作"); + } // 根据实际情况补充 old.setName(sysUser.getName()); old.setMail(sysUser.getMail()); old.setSex(sysUser.getSex()); - old.setUserName(sysUser.getUserName()); + old.setModifiedTime(new Date()); +// old.setUserName(sysUser.getUserName());//用户名不能修改 SysUser one = userRepository.save(old); - if (one == null) { - result.setMessage("更新用户成功"); + if (one != null) { + result.setMessage("更新成功"); result.setSuccess(true); } else { - result.setMessage("更新用户失败"); + result.setMessage("更新失败"); } return result; } @@ -134,7 +140,49 @@ public class UserService { * @return */ public List listAll() { - return userRepository.findAll(); + List all = userRepository.findAll(); + if (CollectionUtils.isNotEmpty(all)) { + all.forEach(sysUser -> { + CommonEnum.SexEnum sexEnum = Arrays.stream(CommonEnum.SexEnum.values()).filter(obj -> obj.getCode().equals(sysUser.getSex())).findFirst().get(); + sysUser.setSexName(sexEnum.getName()); + sysUser.setCreate(DateUtil2.dateToStr(sysUser.getCreateTime(), DateUtil2.YYYY_MM_DD_HH_MM_SS)); + Date modifiedTime = sysUser.getModifiedTime(); + if (modifiedTime != null) + sysUser.setModified(DateUtil2.dateToStr(sysUser.getModifiedTime(), DateUtil2.YYYY_MM_DD_HH_MM_SS)); + }); + } + return all; + } + + /** + * 重置密码 + * + * @param id + * @return + */ + public RestMessage resetPassWord(String id) { + RestMessage result = new RestMessage(); + SysUser old = findOne(id); + if (old == null) + throw new BusinessException("未查询到用户信息"); + if (CommonDataUtil.getToken(CommonConstant.CURRENT_USER_ID).equals(id)) + throw new BusinessException("不能重置当前登录用户"); + if (CommonEnum.YesOrNoEnum.YES.getCode().equals(old.getAdmin())) { + throw new BusinessException("管理员密码不能重置"); + } + String[] str = PassWordUtil.getUserSecret(null, null); + old.setSalt(str[1]); + old.setPassword(str[2]); + old.setModifiedTime(new Date()); + SysUser save = userRepository.save(old); + if (save == null) + throw new BusinessException("重置密码失败"); + boolean send = sendEmail(old, str[0]); + if (!send) + throw new BusinessException("发送密码邮件错误"); + result.setSuccess(true); + result.setMessage("重置密码成功"); + return result; } /** @@ -144,25 +192,24 @@ public class UserService { * @param oldPassWord * @return */ - public RestMessage updatePassWord(HttpServletRequest request,String newPassWord, String oldPassWord) { + public RestMessage updatePassWord(String newPassWord, String oldPassWord, String id) { RestMessage result = new RestMessage(); - HttpSession session = request.getSession(); - String id = (String) session.getAttribute(CommonConstant.SESSION_CURRENT_USER_ID); SysUser sysUser = findOne(id); if (sysUser == null) throw new BusinessException("该用户不存在"); boolean flag = checkPassWord(oldPassWord, sysUser.getPassword(), sysUser.getSalt()); if (!flag) - throw new BusinessException("原密码错误,请重新输入"); + throw new BusinessException("原密码错误,请重新输入"); String[] str = PassWordUtil.getUserSecret(newPassWord, null); sysUser.setSalt(str[1]); sysUser.setPassword(str[2]); - SysUser one = userRepository.save(sysUser); - if (one!=null) { - result.setMessage("更新密码成功"); + sysUser.setModifiedTime(new Date()); + SysUser save = userRepository.save(sysUser); + if (save != null) { + result.setMessage("修改密码成功"); result.setSuccess(true); } else { - result.setMessage("更新密码失败"); + result.setMessage("修改密码失败"); } return result; } @@ -170,18 +217,16 @@ public class UserService { /** * 登录 * - * @param request * @param userName * @param passWord * @param checkCode * @return */ - public RestMessage login(HttpServletRequest request, String userName, String passWord, String checkCode) { + public RestMessage login(String userName, String passWord, String checkCode) { RestMessage restMessage = new RestMessage(); - HttpSession session = request.getSession(); - String imgCode = (String) session.getAttribute(CommonConstant.KEY_CAPTCHA); + String imgCode = (String) CommonDataUtil.getToken(CommonConstant.KEY_CAPTCHA); //验证验证码 - if (!checkCode.equalsIgnoreCase(imgCode) ) { + if (!checkCode.equalsIgnoreCase(imgCode)) { throw new BusinessException("验证码错误"); } //验证账号,密码 @@ -191,8 +236,8 @@ public class UserService { boolean flag = checkPassWord(passWord, user.getPassword(), user.getSalt()); if (!flag) throw new BusinessException("密码错误"); - session.setAttribute(CommonConstant.SESSION_CURRENT_USER, userName); - session.setAttribute(CommonConstant.SESSION_CURRENT_USER_ID, user.getId()); + CommonDataUtil.setToken(CommonConstant.CURRENT_USER, userName); + CommonDataUtil.setToken(CommonConstant.CURRENT_USER_ID, user.getId()); restMessage.setSuccess(true); restMessage.setMessage("登录成功"); return restMessage; @@ -226,4 +271,24 @@ public class UserService { //判断密码是否相同 return realPassWord.equals(validatePassWord); } + + /** + * 发送邮件 + * + * @param sysUser + * @param passWord + * @return + */ + private boolean sendEmail(SysUser sysUser, String passWord) { + SysConfig sysConfig = sysConfigService.findByCode(CommonConstant.EMAIL_KEY); + if (sysConfig == null) { + throw new BusinessException("没有查找到邮件配置项"); + } + JSONObject jsonObject = JSONObject.parseObject(sysConfig.getValue()); + EmailModel emailModel = JSONObject.toJavaObject(jsonObject, EmailModel.class); + emailModel.setToEmail(sysUser.getMail()); + emailModel.setSubject(emailModel.getSubject()); + emailModel.setCentent(emailModel.getCentent() + " 你的用户名是:" + sysUser.getUserName() + ",密码是:" + passWord); + return EmailUtil.sendTextEmail(emailModel); + } } diff --git a/boot-service/src/main/java/com/xwbing/util/CommonDataUtil.java b/boot-service/src/main/java/com/xwbing/util/CommonDataUtil.java new file mode 100644 index 0000000..31ee48b --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/CommonDataUtil.java @@ -0,0 +1,29 @@ +package com.xwbing.util; + +import java.util.HashMap; +import java.util.Map; + +/** + * 项目名称: boot-module-demo + * 创建时间: 2017/11/6 10:00 + * 作者: xiangwb + * 说明: 公共数据类 + */ +public class CommonDataUtil { + private static Map token = new HashMap(); + + public CommonDataUtil() { + } + + public static Object getToken(String key) { + return token.get(key); + } + + public static void setToken(String key, Object value) { + token.put(key, value); + } + + public static void clearMap() { + token.clear(); + } +} diff --git a/boot-service/src/main/java/com/xwbing/util/EmailUtil.java b/boot-service/src/main/java/com/xwbing/util/EmailUtil.java index 690b120..9b017eb 100644 --- a/boot-service/src/main/java/com/xwbing/util/EmailUtil.java +++ b/boot-service/src/main/java/com/xwbing/util/EmailUtil.java @@ -127,6 +127,7 @@ public class EmailUtil { } public static void main(String[] args) { + String email = "{'serverHost':'smtp.163.com','serverPort':25,'serverHost':'smtp.163.com','protocol':'smtp','auth':true,'fromEmail':'xwbing2009@163.com','password':'xwbing900417','subject':'注册成功','centent':'注册成功'}"; EmailModel emailModel = new EmailModel(); emailModel.setServerHost("smtp.163.com"); emailModel.setServerPort(25); diff --git a/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaServlet.java b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaServlet.java index 047d3d1..c337abc 100644 --- a/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaServlet.java +++ b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaServlet.java @@ -1,12 +1,12 @@ package com.xwbing.util.captcah; import com.xwbing.constant.CommonConstant; +import com.xwbing.util.CommonDataUtil; import javax.imageio.ImageIO; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; @@ -18,6 +18,7 @@ import java.io.OutputStream; */ public class CaptchaServlet extends HttpServlet { private static final long serialVersionUID = -124247581620199710L; + @Override protected void service(HttpServletRequest req, HttpServletResponse res) { // 设置相应类型,告诉浏览器输出的内容为图片 @@ -27,12 +28,13 @@ public class CaptchaServlet extends HttpServlet { res.setHeader("Cache-Control", "no-cache"); res.setDateHeader("Expire", 0); try { - HttpSession session = req.getSession(); CaptchaUtil tool = new CaptchaUtil(); StringBuffer code = new StringBuffer(); BufferedImage image = tool.genRandomCodeImage(code); - session.removeAttribute(CommonConstant.KEY_CAPTCHA); - session.setAttribute(CommonConstant.KEY_CAPTCHA, code.toString()); +// HttpSession session = req.getSession(); +// session.removeAttribute(CommonConstant.KEY_CAPTCHA); +// session.setAttribute(CommonConstant.KEY_CAPTCHA, code.toString()); + CommonDataUtil.setToken(CommonConstant.KEY_CAPTCHA, code.toString()); // 将内存中的图片通过流形式输出到客户端 OutputStream out = res.getOutputStream(); ImageIO.write(image, "JPEG", out); diff --git a/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaUtil.java b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaUtil.java index 71e3d1e..eef8934 100644 --- a/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaUtil.java +++ b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaUtil.java @@ -102,11 +102,11 @@ public class CaptchaUtil { CaptchaUtil tool = new CaptchaUtil(); StringBuffer code = new StringBuffer(); BufferedImage image = tool.genRandomCodeImage(code); - System.out.println(">>> random key =: " + code); + System.out.println(">>> random code =: " + code); try { // 将内存中的图片通过流动形式输出到客户端 ImageIO.write(image, "JPEG", new FileOutputStream(new File( - "random-key.jpg"))); + "random-code.jpg"))); } catch (Exception e) { e.printStackTrace(); } diff --git a/boot-web/pom.xml b/boot-web/pom.xml index b67dbfa..fa86c72 100644 --- a/boot-web/pom.xml +++ b/boot-web/pom.xml @@ -25,12 +25,12 @@ - - - - - - + + + nexus-drore-team-3rd + http://192.168.11.110:8081/nexus/content/repositories/thirdparty/ + + @@ -85,32 +85,32 @@ - - - - - - - - - + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + ROOT + false + + - - - - - - - - - - - - - - - - + + org.apache.maven.plugins + maven-source-plugin + 2.4 + + true + + + + compile + + jar + + + + \ No newline at end of file diff --git a/boot-web/src/main/java/com/xwbing/controller/MailTestControl.java b/boot-web/src/main/java/com/xwbing/controller/MailTestControl.java index 2c6d9d0..94d9c8d 100644 --- a/boot-web/src/main/java/com/xwbing/controller/MailTestControl.java +++ b/boot-web/src/main/java/com/xwbing/controller/MailTestControl.java @@ -4,11 +4,12 @@ import com.alibaba.fastjson.JSONObject; import com.xwbing.service.MailService; import com.xwbing.util.JSONObjResult; import com.xwbing.util.RestMessage; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import javax.annotation.Resource; + /** * 项目名称: sb-boot-module-demo * 创建时间: 2017/9/18 13:42 @@ -18,7 +19,7 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/mail/") public class MailTestControl { - @Autowired + @Resource private MailService mailService; /** diff --git a/boot-web/src/main/java/com/xwbing/controller/SysConfigControl.java b/boot-web/src/main/java/com/xwbing/controller/SysConfigControl.java index 061d6ae..b470683 100644 --- a/boot-web/src/main/java/com/xwbing/controller/SysConfigControl.java +++ b/boot-web/src/main/java/com/xwbing/controller/SysConfigControl.java @@ -12,11 +12,11 @@ import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; +import javax.annotation.Resource; import javax.validation.Valid; -import java.util.Objects; +import java.util.List; /** * 说明: 系统配置控制层 @@ -28,31 +28,31 @@ import java.util.Objects; @RestController @RequestMapping("/config/") public class SysConfigControl { - private static Logger log = LoggerFactory.getLogger(SysConfigControl.class); - @Autowired + private final Logger logger = LoggerFactory.getLogger(SysConfigControl.class); + @Resource private SysConfigService sysConfigService; @ApiOperation(value = "新增", notes = "新增系统配置信息") @ApiImplicitParams({ - @ApiImplicitParam(name = "key", value = "配置项的key,长度为1-50", paramType = "query", required = true, dataType = "string"), + @ApiImplicitParam(name = "code", value = "配置项的key,长度为1-50", paramType = "query", required = true, dataType = "string"), @ApiImplicitParam(name = "value", value = "配置项的值", paramType = "query", required = true, dataType = "string"), - @ApiImplicitParam(name = "isEnable", value = "是否启用,格式为Y|N", paramType = "query", required = true, dataType = "string"), + @ApiImplicitParam(name = "enable", value = "是否启用,格式为Y|N", paramType = "query", required = true, dataType = "string"), @ApiImplicitParam(name = "name", value = "配置名称,长度为1-10", paramType = "query", required = true, dataType = "string") }) @PostMapping("save") - public JSONObject save(@Valid SysConfig sysConfig) { + public JSONObject save(@RequestBody @Valid SysConfig sysConfig) { String logMsg = "新增系统配置信息"; - log.info(logMsg); + logger.info(logMsg); RestMessage result = sysConfigService.save(sysConfig); return JSONObjResult.toJSONObj(result); } @ApiOperation(value = "删除", notes = "根据code删除系统配置信息") - @ApiImplicitParam(name = "key", value = "配置项的code", paramType = "query", required = true, dataType = "string") - @PostMapping("removeByCode/{code}") + @ApiImplicitParam(name = "code", value = "配置项的code", paramType = "query", required = true, dataType = "string") + @GetMapping("removeByCode/{code}") public JSONObject removeByCode(@PathVariable String code) { String logMsg = "删除系统配置信息"; - log.info(logMsg + " key:{}", code); + logger.info(logMsg + " code:{}", code); if (StringUtils.isEmpty(code)) { return JSONObjResult.toJSONObj("code不能为空"); } @@ -60,19 +60,48 @@ public class SysConfigControl { return JSONObjResult.toJSONObj(result); } + @ApiOperation(value = "修改", notes = "修改系统配置信息") + @ApiImplicitParams({ + @ApiImplicitParam(name = "code", value = "配置项的key,长度为1-50", paramType = "query", required = true, dataType = "string"), + @ApiImplicitParam(name = "value", value = "配置项的值", paramType = "query", required = true, dataType = "string"), + @ApiImplicitParam(name = "enable", value = "是否启用,格式为Y|N", paramType = "query", required = true, dataType = "string"), + }) + @PostMapping("update") + public JSONObject update(@RequestBody SysConfig sysConfig) { + String logMsg = "修改系统配置信息"; + logger.info(logMsg); + if (StringUtils.isEmpty(sysConfig.getCode())) + return JSONObjResult.toJSONObj("配置项的code不能为空"); + RestMessage result = sysConfigService.update(sysConfig); + return JSONObjResult.toJSONObj(result); + } + @ApiOperation(value = "查找", notes = "根据key查找系统配置信息") - @ApiImplicitParam(name = "key", value = "配置项的code", paramType = "query", required = true, dataType = "string") - @PostMapping("findByCode") + @ApiImplicitParam(name = "code", value = "配置项的code", paramType = "query", required = true, dataType = "string") + @GetMapping("findByCode") public JSONObject findByCode(@RequestParam String code) { String logMsg = "根据code查找系统配置信息"; - log.info(logMsg + " key:{}", code); + logger.info(logMsg + " code:{}", code); if (StringUtils.isEmpty(code)) { return JSONObjResult.toJSONObj("code不能为空"); } - SysConfig one = sysConfigService.findByKey(code); - if (Objects.isNull(one)) { - return JSONObjResult.toJSONObj("该对象不存在"); + SysConfig one = sysConfigService.findByCode(code); + if (one == null) { + return JSONObjResult.toJSONObj("该配置不存在"); } return JSONObjResult.toJSONObj(one, true, ""); } + + @ApiOperation(value = "查找列表", notes = "根据是否启用查找配置列表") + @ApiImplicitParam(name = "enable", value = "是否启用,格式为Y|N", paramType = "query", required = true, dataType = "string") + @GetMapping("listByEnable") + public JSONObject findByEnable(@RequestParam String enable) { + String logMsg = "根据是否启用查找配置列表"; + logger.info(logMsg + " enable:{}", enable); + if (StringUtils.isEmpty(enable)) { + return JSONObjResult.toJSONObj("是否启用不能为空"); + } + List byEnable = sysConfigService.findByEnable(enable); + return JSONObjResult.toJSONObj(byEnable, true, ""); + } } diff --git a/boot-web/src/main/java/com/xwbing/controller/TestControl.java b/boot-web/src/main/java/com/xwbing/controller/TestControl.java index 93fc362..0fa3b5a 100644 --- a/boot-web/src/main/java/com/xwbing/controller/TestControl.java +++ b/boot-web/src/main/java/com/xwbing/controller/TestControl.java @@ -4,11 +4,12 @@ import com.xwbing.annotation.LogInfo; import com.xwbing.redis.RedisService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import javax.annotation.Resource; + /** * 说明: * 项目名称: boot-module-demo @@ -18,7 +19,7 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/test/") public class TestControl { - @Autowired + @Resource private RedisService redisService; private final Logger logger = LoggerFactory.getLogger(TestControl.class); diff --git a/boot-web/src/main/java/com/xwbing/controller/UserControl.java b/boot-web/src/main/java/com/xwbing/controller/UserControl.java index 801b60e..34b0050 100644 --- a/boot-web/src/main/java/com/xwbing/controller/UserControl.java +++ b/boot-web/src/main/java/com/xwbing/controller/UserControl.java @@ -1,23 +1,20 @@ package com.xwbing.controller; import com.alibaba.fastjson.JSONObject; +import com.xwbing.annotation.LogInfo; import com.xwbing.entity.SysUser; import com.xwbing.service.UserService; import com.xwbing.util.JSONObjResult; import com.xwbing.util.RestMessage; import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletRequest; +import javax.annotation.Resource; import javax.validation.Valid; import java.util.List; -import java.util.Objects; /** - * 说明: user + * 说明: 用户控制层 * 项目名称: boot-module-demo * 创建时间: 2017/5/10 16:36 * 作者: xiangwb @@ -25,17 +22,30 @@ import java.util.Objects; @RestController @RequestMapping("/user/") public class UserControl { - private final static Logger log = LoggerFactory.getLogger(UserControl.class); - @Autowired + @Resource private UserService userService; + /** + * 添加用户 + * + * @param sysUser + * @return + */ + @LogInfo("添加用户") @PostMapping("save") - public JSONObject save(@Valid SysUser sysUser) { + public JSONObject save(@RequestBody @Valid SysUser sysUser) { RestMessage result = userService.save(sysUser); return JSONObjResult.toJSONObj(result); } - @PostMapping("removeById") + /** + * 删除用户 + * + * @param id + * @return + */ + @LogInfo("删除用户") + @GetMapping("removeById") public JSONObject removeById(@RequestParam String id) { if (StringUtils.isEmpty(id)) { return JSONObjResult.toJSONObj("主键不能为空"); @@ -44,8 +54,15 @@ public class UserControl { return JSONObjResult.toJSONObj(result); } + /** + * 修改用户信息 + * + * @param sysUser + * @return + */ + @LogInfo("修改用户信息") @PostMapping("update") - public JSONObject update(SysUser sysUser) { + public JSONObject update(@RequestBody @Valid SysUser sysUser) { if (StringUtils.isEmpty(sysUser.getId())) { return JSONObjResult.toJSONObj("主键不能为空"); } @@ -53,41 +70,80 @@ public class UserControl { return JSONObjResult.toJSONObj(result); } + /** + * 获取用户详情 + * + * @param id + * @return + */ + @LogInfo("获取用户详情") @GetMapping("findById") public JSONObject findById(@RequestParam String id) { if (StringUtils.isEmpty(id)) { return JSONObjResult.toJSONObj("主键不能为空"); } SysUser sysUser = userService.findOne(id); - if (Objects.isNull(sysUser)) { + if (sysUser == null) { return JSONObjResult.toJSONObj("未查到该对象"); } return JSONObjResult.toJSONObj(sysUser, true, ""); } + /** + * 列表查询所有用户 + * + * @return + */ + @LogInfo("列表查询所有用户") @GetMapping("findList") public JSONObject findList() { List list = userService.listAll(); return JSONObjResult.toJSONObj(list, true, ""); } + /** + * 登录 + * + * @param userName + * @param passWord + * @param checkCode + * @return + */ + @LogInfo("登录") @GetMapping("login") - public JSONObject login(HttpServletRequest req, @RequestParam String userName, @RequestParam String passWord,@RequestParam String checkCode) { + public JSONObject login(@RequestParam String userName, @RequestParam String passWord, @RequestParam String checkCode) { if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord)) return JSONObjResult.toJSONObj("用户名或密码不能为空"); - if (StringUtils.isEmpty(checkCode) ) + if (StringUtils.isEmpty(checkCode)) return JSONObjResult.toJSONObj("请输入验证码"); - RestMessage login = userService.login(req, userName, passWord, checkCode); + RestMessage login = userService.login(userName, passWord, checkCode); return JSONObjResult.toJSONObj(login); } + /** + * 修改密码 + * + * @param newPassWord + * @param oldPassWord + * @return + */ + @LogInfo("修改密码") @GetMapping("updatePassWord") - public JSONObject updatePassWord(HttpServletRequest request, @RequestParam String newPassWord, @RequestParam String oldPassWord) { - if (StringUtils.isEmpty(newPassWord)) - return JSONObjResult.toJSONObj("新密码不能为空"); - if (StringUtils.isEmpty(oldPassWord)) - return JSONObjResult.toJSONObj("旧密码不能为空"); - RestMessage restMessage = userService.updatePassWord(request, newPassWord, oldPassWord); + public JSONObject updatePassWord(@RequestParam String newPassWord, @RequestParam String oldPassWord, @RequestParam String id) { + if (StringUtils.isEmpty(newPassWord) || StringUtils.isEmpty(oldPassWord)) + return JSONObjResult.toJSONObj("原密码或新密码不能为空"); + if (StringUtils.isEmpty(id)) + return JSONObjResult.toJSONObj("主键不能为空"); + RestMessage restMessage = userService.updatePassWord(newPassWord, oldPassWord, id); + return JSONObjResult.toJSONObj(restMessage); + } + + @LogInfo("重置密码") + @GetMapping("resetPassWord") + public JSONObject resetPassWord(@RequestParam String id) { + if (StringUtils.isEmpty(id)) + return JSONObjResult.toJSONObj("主键不能为空"); + RestMessage restMessage = userService.resetPassWord(id); return JSONObjResult.toJSONObj(restMessage); } } diff --git a/boot-web/src/main/java/com/xwbing/handler/GlobalExceptionHandler.java b/boot-web/src/main/java/com/xwbing/handler/GlobalExceptionHandler.java index c1e7654..fb1430e 100644 --- a/boot-web/src/main/java/com/xwbing/handler/GlobalExceptionHandler.java +++ b/boot-web/src/main/java/com/xwbing/handler/GlobalExceptionHandler.java @@ -7,7 +7,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; +import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @@ -56,11 +58,9 @@ public class GlobalExceptionHandler { */ @ExceptionHandler(value = BindException.class) @ResponseBody - public JSONObject handlerBindException(HttpServletRequest request, - HttpServletResponse response, BindException ex) { - + public JSONObject handlerBindException(HttpServletRequest request, HttpServletResponse response, BindException ex) { List list = ex.getAllErrors(); - StringBuffer stringBuffer = new StringBuffer(); + StringBuilder stringBuffer = new StringBuilder(); for (ObjectError objectError : list) { if (stringBuffer.length() > 0) stringBuffer.append(" && "); @@ -71,6 +71,29 @@ public class GlobalExceptionHandler { return JSONObjResult.toJSONObj(stringBuffer.toString()); } + /** + * 表单检验(validator) 异常 (@RequestBody) + * + * @param ex + * @return + */ + @ExceptionHandler(value = MethodArgumentNotValidException.class) + @ResponseStatus(value = HttpStatus.OK) + @ResponseBody + public JSONObject handlerMethodArgumentNotValidException(MethodArgumentNotValidException ex) { + + BindingResult bindingResult = ex.getBindingResult(); + List allErrors = bindingResult.getAllErrors(); + StringBuilder stringBuffer = new StringBuilder(); + for (ObjectError objectError : allErrors) { + if (stringBuffer.length() > 0) + stringBuffer.append(" && "); + stringBuffer.append(objectError.getDefaultMessage()); + } + logger.error(stringBuffer.toString()); + return JSONObjResult.toJSONObj(stringBuffer.toString()); + } + /** * @param request * @param ex diff --git a/boot-web/src/main/java/com/xwbing/handler/LoginInterceptor.java b/boot-web/src/main/java/com/xwbing/handler/LoginInterceptor.java index 4c3906e..8d9cd5a 100644 --- a/boot-web/src/main/java/com/xwbing/handler/LoginInterceptor.java +++ b/boot-web/src/main/java/com/xwbing/handler/LoginInterceptor.java @@ -2,13 +2,13 @@ package com.xwbing.handler; import com.xwbing.configuration.DispatcherServletConfig; import com.xwbing.constant.CommonConstant; +import com.xwbing.util.CommonDataUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; import java.util.HashSet; import java.util.Set; @@ -21,20 +21,27 @@ import java.util.Set; public class LoginInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(DispatcherServletConfig.class); private static final Set set = new HashSet<>();//拦截器白名单 + static { set.add("/v2/api-docs"); set.add("/servlet/captchaCode"); set.add("/swagger-ui.html"); } + @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String servletPath = request.getServletPath(); - if(!set.contains(servletPath) && !servletPath.contains("login")){ - HttpSession session = request.getSession(); - if (session.getAttribute(CommonConstant.SESSION_CURRENT_USER)!=null) { + if (!set.contains(servletPath) && !servletPath.contains("login")) { +// HttpSession session = request.getSession(); +// if (session.getAttribute(CommonConstant.CURRENT_USER)!=null) { +// return true; +// }else { +// return false; +// } + if (CommonDataUtil.getToken(CommonConstant.CURRENT_USER) != null) { // TODO: 2017/10/3 return true; - }else { + } else { // TODO: 2017/10/3 return false; }