创建返回对象
根据返回值创建返回对象
返回值 ServerResponse 类:包含三个数据 状态(status)、信息(msg)、[ 泛型 ]数据(data)
public class ServerResponse<T> implements Serializable {
private int status;
private String msg;
private T data;
private ServerResponse(int status){
this.status = status;
}
private ServerResponse(int status,T data){
this.status = status;
this.data = data;
}
private ServerResponse(int status,String msg,T data){
this.status = status;
this.msg = msg;
this.data = data;
}
private ServerResponse(int status,String msg){
this.status = status;
this.msg = msg;
}
创建一个枚举类 ,里面的属性可以通过 类名直接调用
public enum ResponseCode {
SUCCESS(0,"SUCCESS"),
ERROR(1,"ERROR"),
NEED_LOGIN(10,"NEED_LOGIN"),
ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT");
private final int code;
private final String desc;
ResponseCode(int code,String desc){
this.code = code;
this.desc = desc;
}
public int getCode(){
return code;
}
public String getDesc(){
return desc;
}
}
枚举的其他例子
public enum DataSourceType {
MASTER,SLAVE;
}
登录功能
controller层
登录方法 login()
- 方法返回值类型 ServerResponse<T>
- 注意里面的类型是 泛型数据 T ;
- T 代表各种类型 例如: ServerResponse<User>
- 传递三个参数 name;password;session
- 如果返回的是 success 就用 session 保存
@RequestMapping(value="login.do",method = RequestMethod.POST)
@ResponseBody
public ServerResponse<User> login(String username, String password, HttpSession session) {
ServerResponse<User> response = iUserService.login(username, password);
if(response.isSuccess()){
session.setAttribute(Const.CURRENT_USER,response.getData());
}
return response;
}
imp层
先查找用户名,检验是否存在;
@Override
public ServerResponse<User> login(String username, String password) {
// 校验用户是否存在
int i = userMapper.checkUsername(username);
if(i==0){
return ServerResponse.createByErrorMessage("用户不存在");
}
// 校验密码
String md5Password = MD5Util.MD5EncodeUtf8(password);
User user = userMapper.selectLogin(username, md5Password);
if(user==null){
return ServerResponse.createByErrorMessage("用户密码错误");
}
user.setPassword(StringUtils.EMPTY);
return ServerResponse.createBySuccess("登录成功",user);
}
这个查找用户名的语句不严谨,万一有重复的名字
<select id="checkUsername" resultType="int" parameterType="string" >
select count(1)
from mmall_user
where username = #{username,jdbcType=VARCHAR}
</select>
parameterType:可以是 map 也可以是 String