定义通用的返回对象 CommonReturnType
//归一化处理http返回
public class CommonReturnType {
//表明对应请求的返回处理结果“success”或“fail”
private String status;
// status = success, data 内返回前端需要的 json数据
// status = fail, data 内使用通用的错误码格式
private Object data;
//定义一个通用的创建方法
public static CommonReturnType create(Object result){
return CommonReturnType.create(result,"success");
}
public static CommonReturnType create(Object result,String status){
CommonReturnType type= new CommonReturnType();
type.setStatus(status);
type.setData(result);
return type;
}
...
}
定义错误接口 CommonError
public interface CommonError {
public int getErrorCode();
public String getErrMsg();
public CommonError setErrMsg(String errMsg);
}
定义枚举类 EmBusinessError
public enum EmBusinessError implements CommonError {
// 通用错误类型 10001
PARAMETER_VALIDATION_ERROR(10001, "参数不合法"),
UNKNOWN_ERROR(10002, "未知错误"),
// 20000 开头为用户信息相关错误定义
USER_NOT_EXIST(20001, "用户不存在"),
;
private int errCode;
private String errMsg;
private EmBusinessError(int errCode, String errMsg){
this.errCode = errCode;
this.errMsg = errMsg;
}
@Override
public int getErrCode() {
return this.errCode;
}
@Override
public String getErrMsg() {
return this.errMsg;
}
@Override
public CommonError setErrMsg(String errMsg) {
this.errMsg = errMsg;
return this;
}
}
包装器业务异常类实现
//包装器业务异常类实现
public class BusinessException extends Exception implements CommonError {
private CommonError commonError;
//直接接受EmBusinessError的传参 用于构造业务异常
public BusinessException(CommonError commonError){
super();
this.commonError= commonError;
}
//接收自定义errMsg的方式构造业务异常
public BusinessException(CommonError commonError, String errMsg) {
super();
this.commonError = commonError;
this.commonError.setErrMsg(errMsg);
}
@Override
public int getErrorCode() {
return this.commonError.getErrorCode();
}
@Override
public String getErrMsg() {
return this.commonError.getErrMsg();
}
@Override
public CommonError setErrMsg(String errMsg) {
this.commonError.setErrMsg(errMsg);
return this;
}
}
定义BaseController 处理异常
public class BaseController {
public static final String CONTENT_TYPE_FORMED = "application/x-www-form-urlencoded";
//定义exceptionhandler解决未被controller层吸收的exception
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object handlerException(HttpServletRequest request, Exception ex){
Map<String, Object> responseData = new HashMap<>();
if(ex instanceof BusinessException){
BusinessException businessException = (BusinessException) ex;
responseData = new HashMap<>();
responseData.put("errCode",businessException.getErrorCode());
responseData.put("errMsg",businessException.getErrMsg());
}else{
responseData.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrorCode());
responseData.put("errMsg",EmBusinessError.UNKNOWN_ERROR.getErrMsg());
}
return CommonReturnType.create(responseData,"fail");
}
}
验证码功能的简单实现
//用户获取短信接口
@RequestMapping(value = "/getotp", method = {RequestMethod.POST})
@ResponseBody
public CommonReturnType getOtp(@RequestParam(name = "telphone") String telephone) {
//按照一定规则生成验证码
Random random = new Random();
int randonInt = random.nextInt(99999); //生成0~99999的数字
randonInt += 10000;
String otpCode = String.valueOf(randonInt);
//将OTP验证码通对应手机号关联。这里利用session
httpServletRequest.getSession().setAttribute(telephone, otpCode);
//发送短信
System.out.println("手机:" + telephone + " 验证码:" + randonInt);
return CommonReturnType.create(null);
}
创建getotp页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="static/assets/global/plugins/jquery-1.11.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="static/assets/global/plugins/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="static/assets/global/css/components.css">
<link rel="stylesheet" type="text/css" href="static/assets/admin/pages/css/login.css">
<title></title>
</head>
<body class="login">
<div class="content">
<h3 class="form-title">获取otp信息</h3>
<div class="form-group">
<label class="control-label">手机号</label>
<div>
<input class="form-control" type="text" placeholder="手机号" name="telephone" id="telephone">
</div>
</div>
<div class="form-actions">
<button class="btn blue" id="getotp" type="submit">
获取otp短信
</button>
</div>
</div>
</body>
<script>
$(document).ready(function() {
// 绑定otp的click实现用于向后端发送获取手机验证码的请求
$("#getotp").on("click", function() {
var telephone = $("#telephone").val();
if (telephone == null || telephone == "") {
alert("手机号不能为空");
return false;
}
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: "http://localhost:8080/user/getotp",
data: {
"telephone": $("#telephone").val()
},
xhrFields:{
withCredentials:true
},
success: function(data) {
if (data.status == "success") {
alert("otp已经发送到了您的手机上,请注意查收");
window.location.href="http://localhost:63342/springboot0611/html/register.html";
} else {
alert("otp发送失败,原因为" + data.data.errMsg);
}
},
error: function(data) {
alert("otp发送失败,原因为" + data.responseText);
}
});
return false;
});
});
</script>
</html>
注册功能实现
UserService增加方法
void register(UserModel userModel) throws BusinessException;
UserServiceImpl 实现
@Override
public void register(UserModel userModel) throws BusinessException {
if(userModel == null){
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
}
if(StringUtils.isEmpty(userModel.getTelphone())
|| StringUtils.isEmpty(userModel.getName())
|| userModel.getGender() == null
|| userModel.getAge() == null
|| StringUtils.isEmpty(userModel.getEncrptPassword())){
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
}
UserDO userDO = convertFromModel(userModel);
try{
userDOMapper.insertSelective(userDO);
}catch (DuplicateKeyException ex){
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "手机号码已注册");
}
userModel.setId(userDO.getId()); // 获取自增 id 修改UserDOMapping.xml
UserPasswordDO userPasswordDO = convertPasswordFromModel(userModel);
userPasswordDOMapper.insertSelective(userPasswordDO);
return;
}
private UserDO convertFromModel(UserModel userModel){
if(userModel == null){
return null;
}
UserDO userDO = new UserDO();
BeanUtils.copyProperties(userModel, userDO);
return userDO;
}
private UserPasswordDO convertPasswordFromModel(UserModel userModel){
if(userModel == null){
return null;
}
UserPasswordDO userPasswordDO = new UserPasswordDO();
userPasswordDO.setEncrptPassword(userModel.getEncrptPassword());
userPasswordDO.setUserId(userModel.getId());
return userPasswordDO;
}
修改UserDOMapping.xml 获取自增的主键
<insert id="insertSelective" parameterType="com.wilbur.dataObject.UserDO" keyProperty="id" useGeneratedKeys="true">
解决跨域问题
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")