shop--14.升级--本地账号注册,登录,修改密码
Dao层
本地账户LocalUser
@Repository public interface LocalUserDao { /** * 根据传入的用户名和密码查询对应的信息,登录时使用 * @param username * @param password * @return */ LocalUser queryLocalUserByUserNameAndPWd(@Param( "username" ) String username, @Param( "password" ) String password); /** * 通过userId查询用户信息 * @param userId * @return */ LocalUser queryLocalUserByUserId(@Param( "userId" ) long userId); /** * 添加本地账号 * @param localUser * @return */ int insertLocalUser(LocalUser localUser); /** * 通过userId,username,password确定要修改密码的用户,然后进行密码的修改 * @param userId * @param username * @param password * @param newPassword * @param lastEditTime * @return */ int updateLocalUser(@Param( "userId" ) Long userId, @Param( "username" ) String username, @Param( "password" ) String password, @Param( "newPassword" ) String newPassword, @Param( "lastEditTime" ) Date lastEditTime); }
用户详细信息
PersonInfoDao
@Repository public interface PersonInfoDao { /** * 注册用户信息 * @param personInfo * @return */ int registerPersonInfo(PersonInfo personInfo); /** * 获取最新注册的用户Id * @return */ long qyeryNewRegisterId(); }
LocalUserDao.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.shop.dao.LocalUserDao"> <resultMap id="localUserResultMap" type="com.shop.bean.LocalUser"> <id column="local_user_id" property="localUserId"/> <result column="user_name" property="username"/> <result column="password" property="password"/> <result column="create_time" property="createTime"/> <result column="last_edit_time" property="lastEditTime"/> <association column="user_id" property="personInfo" javaType="com.shop.bean.PersonInfo"> <id column="user_id" property="userId"/> <result column="nick_name" property="nickname"/> <result column="gender" property="gender"/> <result column="email" property="email"/> <result column="photo" property="photo"/> <result column="user_type" property="userType"/> <result column="create_time" property="createTime"/> <result column="last_edit_time" property="lastEditTime"/> <result column="status" property="status"/> </association> </resultMap> <!--LocalUser queryLocalUserByUserNameAndPWd(@Param( "username" ) String username, @Param( "password" ) String password);--> <select id="queryLocalUserByUserNameAndPWd" resultMap="localUserResultMap"> SELECT l.local_user_id, l.user_name, l.password, l.create_time, l.last_edit_time, p.user_id, p.nick_name, p.gender, p.email, p.photo, p.user_type, p.create_time, p.last_edit_time, p.status FROM local_user l LEFT JOIN person_info p ON l.user_id=p.user_id WHERE l.user_name=#{username} AND l.password=#{password} </select> <!--LocalUser queryLocalUserByUserId(long userId);--> <select id="queryLocalUserByUserId" resultMap="localUserResultMap" parameterType="Long"> SELECT l.local_user_id, l.user_name, l.password, l.create_time, l.last_edit_time, p.user_id, p.nick_name, p.gender, p.email, p.photo, p.user_type, p.create_time, p.last_edit_time, p.status FROM local_user l LEFT JOIN person_info p ON l.user_id=p.user_id WHERE l.user_id=#{userId} </select> <!--int insertLocalUser(LocalUser localUser);--> <insert id="insertLocalUser" parameterType="com.shop.bean.LocalUser" useGeneratedKeys="true" keyColumn="local_user_id" keyProperty="localUserId"> INSERT INTO local_user(user_name, password, user_id, create_time, last_edit_time) VALUES(#{username}, #{password}, #{personInfo.userId}, #{createTime}, #{lastEditTime}) </insert> <!--int updateLocalUser(@Param( "userId" ) Long userId, @Param( "username" ) String username, @Param( "password" ) String password, @Param( "newPassword" ) String newPassword, @Param( "lastEditTime" ) Date lastEditTime);--> <update id="updateLocalUser"> UPDATE local_user <set> <if test="newPassword != null">password=#{newPassword},</if> <if test="lastEditTime != null">last_edit_time=#{lastEditTime}</if> </set> WHERE user_id=#{userId} AND user_name=#{username} AND password=#{password} </update> </mapper>
PersonInfoDao.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.shop.dao.PersonInfoDao"> <!--int registerPersonInfo(PersonInfo personInfo);--> <insert id="registerPersonInfo" parameterType="com.shop.bean.PersonInfo" useGeneratedKeys="true" keyColumn="user_id" keyProperty="userId"> INSERT INTO person_info(nick_name, photo, email, gender, status, user_type, create_time, last_edit_time) VALUES(#{nickname}, #{photo}, #{email}, #{gender}, #{status}, #{userType}, #{createTime}, #{lastEditTime}) </insert> <!--long qyeryNewRegisterId();--> <select id="qyeryNewRegisterId" resultType="Long"> SELECT MAX(user_id) FROM person_info </select> </mapper>
Service层开发
package com.shop.service; import com.shop.bean.LocalUser; import com.shop.dto.LocalUserExecution; import org.springframework.web.multipart.commons.CommonsMultipartFile; /** * Created by Skye on 2018/5/14. */ public interface LocalUserService { /** * 根据传入的用户名和密码查询对应的信息,登录时使用 * @param username * @param password * @return */ LocalUser getLocalUserByUserNameAndPwd(String username, String password); /** * 通过userId获取本地账号信息 * @param userId * @return */ LocalUser getLocalUserByUserId(long userId); /** * 修改本地账号的密码 * @param userId * @param username * @param password * @param newPassword * @return */ LocalUserExecution modyfiLocalUser(long userId, String username, String password, String newPassword); /** * 本地用户注册,和用户头像上传 * @param localUser * @param photo * @return */ LocalUserExecution registerLocalUser(LocalUser localUser, CommonsMultipartFile photo); }
serviceImpl
package com.shop.service.serviceImpl; import com.shop.bean.LocalUser; import com.shop.bean.PersonInfo; import com.shop.dao.LocalUserDao; import com.shop.dao.PersonInfoDao; import com.shop.dto.LocalUserExecution; import com.shop.enums.LocalUserStateEnum; import com.shop.execptions.LocalUserException; import com.shop.service.LocalUserService; import com.shop.util.ImageUtil; import com.shop.util.MD5; import com.shop.util.PathUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.multipart.commons.CommonsMultipartFile; import java.util.Date; /** * Created by Skye on 2018/5/14. */ @Service public class LocalUserServiceImpl implements LocalUserService { @Autowired private LocalUserDao localUserDao; @Autowired private PersonInfoDao personInfoDao; @Override public LocalUser getLocalUserByUserNameAndPwd(String username, String password) { return localUserDao.queryLocalUserByUserNameAndPWd( username, MD5.getMd5(password) ); } @Override public LocalUser getLocalUserByUserId(long userId) { return localUserDao.queryLocalUserByUserId( userId ); } @Override public LocalUserExecution modyfiLocalUser(long userId, String username, String password, String newPassword) { //非空判断,并且新旧密码是否相同,若相同,则不进行修改 if(userId != -1 && username != null && password != null && newPassword != null && !password.equals( newPassword )){ try{ int effectNum = localUserDao.updateLocalUser( userId, username, MD5.getMd5( password ), MD5.getMd5( newPassword ), new Date( ) ); if(effectNum <= 0){ throw new LocalUserException("密码更新失败"); } return new LocalUserExecution(LocalUserStateEnum.SUCCESS); } catch(LocalUserException e){ throw new LocalUserException( "更新密码失败" + e.getMessage() ); } } else{ return new LocalUserExecution( LocalUserStateEnum.EMPTY_LOCALUSER_INFO ); } } /** * 本地用户注册 * @param localUser * @param photo * @return */ @Override @Transactional public LocalUserExecution registerLocalUser(LocalUser localUser, CommonsMultipartFile photo) { if(localUser == null || localUser.getUsername() == null || localUser.getPassword() == null){ return new LocalUserExecution( LocalUserStateEnum.EMPTY_LOCALUSER_INFO ); } try{ localUser.setCreateTime( new Date( ) ); localUser.setLastEditTime( new Date( ) ); localUser.setPassword( MD5.getMd5( localUser.getPassword()) ); //将用户头像放入用户所在的文件夹下 if(localUser.getPersonInfo() != null && localUser.getPersonInfo().getUserId() == null){ if(photo != null){ try{ addPhoto( localUser, photo ); } catch (Exception e){ throw new RuntimeException( "add photo error" + e.toString() ); } } localUser.getPersonInfo().setCreateTime( new Date( ) ); localUser.getPersonInfo().setLastEditTime( new Date( ) ); localUser.getPersonInfo().setStatus( 1 ); try{ //插入用户详细信息的数据到person_info PersonInfo personInfo = localUser.getPersonInfo(); int effectNum = personInfoDao.registerPersonInfo( personInfo ); if(effectNum <= 0){ throw new RuntimeException( "添加用户信息失败" ); } else{ Long user_id = personInfoDao.qyeryNewRegisterId(); localUser.getPersonInfo().setUserId( user_id ); } }catch(Exception e){ throw new RuntimeException( "insertPersonInfo error " + e.toString() ); } } // 然后在将用户注册信息插入到local_user中 int effectNum = localUserDao.insertLocalUser( localUser ); if(effectNum <= 0){ throw new RuntimeException( "创建账号失败" ); } else{ return new LocalUserExecution( LocalUserStateEnum.SUCCESS ); } } catch (Exception e){ throw new RuntimeException( "insert localUser error " + e.toString() ); } } /** * 将用户头像添加到用户的文件夹下,并将本地用户信息中的头像地址更新 * @param localUser * @param photo */ private void addPhoto(LocalUser localUser, CommonsMultipartFile photo){ String relativeImgPath = PathUtil.getPersonInfoImagePath(); String realRelativeImgPath = ImageUtil.generateThumbnail(photo, relativeImgPath); localUser.getPersonInfo().setPhoto( realRelativeImgPath ); } }
LocalUserExecution
public class LocalUserExecution { private int state; private String stateInfo; private List<LocalUser> localUserList; private LocalUser localUser; private int count; public LocalUserExecution() { } //操作失败时,使用的构造器 public LocalUserExecution(LocalUserStateEnum localUserEnum){ this.state = localUserEnum.getState(); this.stateInfo = localUserEnum.getStateInfo(); } //操作成功时,使用的构造器 public LocalUserExecution(LocalUserStateEnum localUserStateEnum, LocalUser localUser){ this.state = localUserStateEnum.getState(); this.stateInfo = localUserStateEnum.getStateInfo(); this.localUser = localUser; } //操作成功时,使用的构造器 public LocalUserExecution(LocalUserStateEnum localUserStateEnum, List<LocalUser> localUserList){ this.state = localUserStateEnum.getState(); this.stateInfo = localUserStateEnum.getStateInfo(); this.localUserList = localUserList; } public int getState() { return state; } public String getStateInfo() { return stateInfo; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
LocalUserStateEnum
package com.shop.enums; /** * Created by Skye on 2018/5/14. */ public enum LocalUserStateEnum { SUCCESS(1, "操作成功"), INNER_ERROR(-1001, "内部错误"), EMPTY_LOCALUSER_INFO(-1002, "本地用户信息为空"); private int state; private String stateInfo; LocalUserStateEnum(int state, String stateInfo) { this.state = state; this.stateInfo = stateInfo; } public int getState() { return state; } public String getStateInfo() { return stateInfo; } public static LocalUserStateEnum stateof(int state){ for(LocalUserStateEnum s : values()){ if(s.state == state){ return s; } } return null; } }
LocalUserException
package com.shop.execptions; /** * Created by Skye on 2018/5/14. */ public class LocalUserException extends RuntimeException { private static final long serialVersionUID = -4908599956606896236L; public LocalUserException(String message) { super(message); } }
Controller层
package com.shop.controller.local; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.shop.bean.LocalUser; import com.shop.bean.PersonInfo; import com.shop.dto.LocalUserExecution; import com.shop.enums.LocalUserStateEnum; import com.shop.execptions.LocalUserException; import com.shop.service.LocalUserService; import com.shop.util.CodeUtil; import com.shop.util.HttpServletRequestUtil; import com.shop.util.MD5; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Created by Skye on 2018/5/14. */ @Controller @RequestMapping("/local") public class LocalUserController { @Autowired LocalUserService localUserService; /** * 修改本地用户的登录密码 * @param request * @return */ @RequestMapping(value="/changelocalpwd", method= RequestMethod.POST) @ResponseBody private Map<String, Object> changeLocalPwd(HttpServletRequest request){ Map<String, Object> modelMap = new HashMap<>(); //验证码校验 if(!CodeUtil.checkVerifyCode(request)){ modelMap.put( "success", false ); modelMap.put( "errMsg", "验证码错误" ); return modelMap; } String username = HttpServletRequestUtil.getString( request, "username" ); String password = HttpServletRequestUtil.getString( request, "password" ); String newPassword = HttpServletRequestUtil.getString( request, "newPassword" ); PersonInfo user = (PersonInfo) request.getSession().getAttribute( "user" ); //非空判断 if(username != null && password != null && newPassword != null && user != null && user.getUserId() != null && !password.equals( newPassword ) ){ try{ //通过系统传过来的userId来从数据库获取localUser,判断是否是本人操作,即用户名和密码是否存在且匹配 LocalUser localUser = localUserService.getLocalUserByUserId( user.getUserId() ); if(localUser == null || !localUser.getPassword().equals( MD5.getMd5(password) )){ modelMap.put( "success", false ); modelMap.put( "errMsg", "账号非本次登录账号" ); return modelMap; } //修改本地用户的密码 LocalUserExecution localUserExecution = localUserService.modyfiLocalUser( user.getUserId(), username, password, newPassword ); if(localUserExecution.getState() == LocalUserStateEnum.SUCCESS.getState()){ modelMap.put( "success", true ); } else{ modelMap.put( "success", false ); modelMap.put( "errMsg", localUserExecution.getStateInfo() ); } }catch (LocalUserException e){ modelMap.put( "success", false ); modelMap.put( "errMsg", e.getMessage() ); return modelMap; } } else{ modelMap.put( "success", false ); modelMap.put( "errMsg", "请输入密码" ); } return modelMap; } /** * 本地用户注册 * @param request * @return */ @RequestMapping(value="/localuserregister", method=RequestMethod.POST) @ResponseBody private Map<String, Object> localUserRegister(HttpServletRequest request){ Map<String, Object> modelMap = new HashMap<>( ); //验证码校验 if(!CodeUtil.checkVerifyCode(request)) { modelMap.put( "success", false ); modelMap.put( "errMsg", "验证码错误" ); return modelMap; } //1.接收并转化相应的参数,包括本地账户,图片信息 ObjectMapper objectMapper = new ObjectMapper( ); LocalUser localUser = null; String localUserStr = HttpServletRequestUtil.getString( request, "localUser" ); if(localUserStr != null){ try { localUser = objectMapper.readValue( localUserStr, LocalUser.class ); } catch (IOException e) { modelMap.put( "success", false ); modelMap.put( "errMsg", e.getMessage() ); return modelMap; } } CommonsMultipartFile photo = null; //在本次会话的上下文获取上传的文件 CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext() ); //如果文件上传的有值 if(commonsMultipartResolver.isMultipart( request )){ MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; photo = (CommonsMultipartFile) multipartHttpServletRequest.getFile( "thumbnail" ); } else{ modelMap.put( "success", false ); modelMap.put( "errMsg", "上传图片不能为空" ); return modelMap; } //进行本地用户注册 if(localUser != null && localUser.getUsername() != null && localUser.getPassword() != null && photo != null){ try{ LocalUserExecution localUserExecution = localUserService.registerLocalUser( localUser, photo ); if(localUserExecution.getState() == LocalUserStateEnum.SUCCESS.getState()){ modelMap.put( "success", true ); } else{ modelMap.put( "success", false ); modelMap.put( "errMsg", localUserExecution.getStateInfo() ); } } catch (Exception e){ modelMap.put( "success", false ); modelMap.put( "errMsg", e.toString() ); return modelMap; } } else{ modelMap.put( "success", false ); modelMap.put( "errMsg", "请输入注册信息" ); } return modelMap; } /** * 对登录用户进行核对 * @param request * @return */ @RequestMapping(value="/logincheck", method=RequestMethod.POST) @ResponseBody private Map<String, Object> logincheck(HttpServletRequest request){ Map<String, Object> modelMap = new HashMap<>( ); /*//验证码校验 if(!CodeUtil.checkVerifyCode(request)){ modelMap.put( "success", false ); modelMap.put( "errMsg", "验证码错误" ); return modelMap; }*/ String username = HttpServletRequestUtil.getString( request, "userName" ); String password = HttpServletRequestUtil.getString( request, "password" ); //非空校验 if(username != null && password != null){ //从数据库获取username和password对应的用户信息,如果存在,则证明正确,否则提示用户不存在或密码错误 LocalUser localUser = localUserService.getLocalUserByUserNameAndPwd( username, password ); if(localUser != null){ modelMap.put( "success", true ); request.getSession().setAttribute( "user", localUser.getPersonInfo() ); } else{ modelMap.put( "success", false ); modelMap.put( "errMsg", "用户名或密码错误" ); } } else{ modelMap.put( "success", false ); modelMap.put( "errMsg", "用户名和密码均不能为空" ); } return modelMap; } /** * 用户点击登出按钮时,注销掉session中的user * @param request * @return */ @RequestMapping(value="/logout", method=RequestMethod.POST) @ResponseBody private Map<String, Object> logout(HttpServletRequest request){ Map<String, Object> modelMap = new HashMap<>( ); //将session中的user注销掉 request.getSession().setAttribute( "user", null ); modelMap.put( "success", true ); return modelMap; } }