此接口是使用者登陸後修改個人資訊的接口,其中使用者的Id和使用者名是不允許修改的 controller
:
//更新個人使用者資訊
@RequestMapping(value = "update_information.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<User> update_information(HttpSession session,User user){
//防止越權問題,我們将傳過來的使用者Id設定為Session裡面擷取目前登入使用者的Id
User currentUser= (User) session.getAttribute(Const.CURRENT_USER);
if(currentUser==null){
return ServerResponse.createByErrorMessage("使用者未登入");
}
//設定userId和username是不能被修改的
user.setId(currentUser.getId());
user.setUsername(currentUser.getUsername());
ServerResponse<User> response= iUserService.updateInformation(user);
if(response.isSuccess()){
session.setAttribute(Const.CURRENT_USER,response.getData());
}
return response;
}
server
:
//修改個人資訊
ServerResponse<User> updateInformation(User user);
serverImpl
//修改個人資訊
public ServerResponse<User> updateInformation(User user){
//username是不能被更新的
//email也要進行校驗,校驗新的email是不是已經存在,如果當存在相同的email的話,不能是我們目前的使用者的
int resuletCount=userMapper.checkEmailByUserId(user.getEmail(),user.getId());
if(resuletCount>0){
return ServerResponse.createByErrorMessage("郵箱已被使用,請更換後重試");
}
User updateUser=new User();
updateUser.setId(user.getId());
updateUser.setEmail(user.getEmail());
updateUser.setPhone(user.getPhone());
updateUser.setQuestion(user.getQuestion());
updateUser.setAnswer(user.getAnswer());
int updateCount=userMapper.updateByPrimaryKeySelective(updateUser);
if(updateCount>0){
return ServerResponse.createBySuccess("更行個人資訊成功",updateUser);
}
return ServerResponse.createByErrorMessage("更新個人資訊失敗,請稍後重試");
}
Mapper
更新新的Mapper可以直接用逆向工程生成的工具,直接調用即可,故而
Mapper.xml
也是我們不用修改的。
下面,我們來介紹下上面
serverImpl
代碼中根據使用者的Id來校驗郵箱是否可用:
email進行校驗,校驗新的email是不是已經存在,如果當存在相同的email的話,不能是我們目前的使用者的,
Mapper
/根據使用者的Id查詢郵箱是否可用
int checkEmailByUserId(@Param("email") String email, @Param("userId") Integer userId);
Mapper.xml
<select id="checkEmailByUserId" resultType="int" parameterType="map" >
select count(1) from mmall_user
where email = #{email}
and id != #{userId}
</select>
接口測試:
測試郵箱不可用(即使用原郵箱)

image.png
換個郵箱測試: