先看一下工程目录
创建UserController
类
在主方法上加上这两个注释:
@Controller
@RequestMapping("/user/")
如:
1、登录接口:
Controller:
层
//登录
@RequestMapping(value = "login.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<User> login(String username, String password, HttpSession session){
//service>> mybatis>>dao
ServerResponse<User> response= iUserService.login(username,password);
if(response.isSussecc()){
session.setAttribute(Const.CURRENT_USER,response.getData());
}
return response;
}
Service
层:
//登录
@Override
public ServerResponse<User> login(String username, String password) {
int resultCount= userMapper.checkUsername(username);
if(resultCount==0){
return ServerResponse.createByErrorMessage("用户名不存在");
}
//TODO 密码登录MD5
String md5Password=MD5Util.MD5EncodeUtf8(password);
User user=userMapper.selectLogin(username,password);
if(user==null){
return ServerResponse.createByErrorMessage("密码错误");
}
user.setPassword(StringUtils.EMPTY);
return ServerResponse.createBySuccessMessage("登录成功",user);
}
2、注销接口:
Controller
: 层
//注销 删除里面的Session即可
@RequestMapping(value = "logout.do",method = RequestMethod.GET)
@ResponseBody
public ServerResponse<String> logout(HttpSession session){
session.removeAttribute(Const.CURRENT_USER);
return ServerResponse.createBySuccess();
}
由于只要删除Session,所以不需要涉及到Service层。
3、注册接口:
Controller
: 层
//注册
@RequestMapping(value = "regiest.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<String> regiest(User user){
return iUserService.regiest(user);
}
//校验邮箱或用户名不否能用
@RequestMapping(value = "check_valid.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<String> checkValid(String str,String type){
return iUserService.checkValid(str,type);
}
Service
层
//注册方法
@Override
public ServerResponse<String> regiest(User user){
//复用下面的checkValid校验方法
ServerResponse validRespose=this.checkValid(user.getUsername(),Const.USERNAME);
if(!validRespose.isSussecc()){
return validRespose;
}
validRespose=this.checkValid(user.getEmail(),Const.EMAIL);
if(!validRespose.isSussecc()){
return validRespose;
}
user.setRole(Const.Role.ROLE_CUSTOMER);
//MD5加密
user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
int resultCount=userMapper.insert(user);
if(resultCount==0){
return ServerResponse.createByErrorMessage ("服务器内部错误,注册失败");
}
return ServerResponse.createBySuccessMessage("注册成功");
}
//判断用户名和邮箱是否有效
public ServerResponse<String> checkValid(String str,String type){
if(StringUtils.isNotBlank(type)){
//开始校验
if(Const.USERNAME.equals(type)){
int resultCount= userMapper.checkUsername(str);
if(resultCount>0){
return ServerResponse.createByErrorMessage("用户名已存在");
}
}
if(Const.EMAIL.equals(type)){
int resultCount=userMapper.checkEmail(str);
if(resultCount>0){
return ServerResponse.createByErrorMessage("email已存在");
}
}
}
else{
return ServerResponse.createByErrorMessage("参数错误");
}
return ServerResponse.createBySuccessMessage("校验成功");
}