封装高可复用的服务端响应对象和登录demo

来源:互联网 发布:数据机房图片 编辑:程序博客网 时间:2024/06/10 02:43

封装高可复用的服务端响应对象和登录demo

在平时的编码过程中,返回给前端的数据都会统一规范起来,用一个泛型来作为响应对象

ServerResponse:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)public class ServerResponse<T> implements Serializable{    private int status;    private String msg;    /**     * 泛型在返回时可以指定里面返回的内容,也可以不指定,     * 泛型还可以包含多种类型:String,map,list等     */    private T data;    /**     * 使用了类上面那个注解,在这种情况下,只返回status,不会有msg和data     * @param status     */    private ServerResponse(int status){        this.status = status;    }    private ServerResponse(int status,String msg){        this.status = status;        this.msg = msg;    }    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;    }    /**     * @JsonIgnore,在json序列化时,该字段不会显示在json里面     * 使之不在json序列化结果当中     * @return     */    @JsonIgnore    public boolean isSuccess(){        return this.status == ResponseCode.SUCCESS.getCode();    }    public int getStatus(){        return status;    }    public T getData(){        return data;    }    public String getMsg(){        return msg;    }    /**     * 成功,返回一个status。     */    public static <T> ServerResponse<T> createBySuccess(){        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());    }    /**     * 成功,返回一个文本供前端提示使用     */    public static <T> ServerResponse<T> createBySuccessMessage(String msg){        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);    }    /**     * 成功,返回对应的数据     */    public static <T> ServerResponse<T> createBySuccess(T data){        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);    }    /**     * 成功,把消息和数据都返回     */    public static <T> ServerResponse<T> createBySuccess(String msg,T data){        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);    }    /**     * 失败,返回一个status     */    public static <T> ServerResponse<T> createByError(){        return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());    }    /**     * 失败,返回一个文本供前端提示使用     */    public static <T> ServerResponse<T> createByErrorMessage(String errorMessage){        return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMessage);    }    /**     * 失败,返回一个status和提示     */    public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMessage){        return new ServerResponse<T>(errorCode,errorMessage);    }}

其中,@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)的作用是:对于失败的情况,不返回data,只返回status和msg时,默认为有key的空节点,即有key,但value是null,这种是不需要返回给前端的,就在类上使用这个注解,保证序列化json的时候,如果是null的对象,key也会消失。

使用枚举定义响应码:

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 class Const {    public static final String CURRENT_USER = "currentUser";    /**     * 校验使用的常量:邮箱和用户名     */    public static final String EMAIL = "email";    public static final String USERNAME = "username";    public interface ProductListOrderBy{        /**         * price_desc:用下划线作为分割,前面表示orderby哪个字段,后面表示排序规则:升序还是降序         */        Set<String> PRICE_ASC_DESC = Sets.newHashSet("price_desc","price_asc");    }    /**     * 普通用户和管理员是一个组,也可用枚举,但是此处枚举显得过于繁重,     * 通过内部的接口类来把常量进行分组     */    public interface Role{        //普通用户        int ROLE_CUSTOMER = 0;        //管理员        int ROLE_ADMIN = 1;    }}

使用guava缓存记录用户信息:

package com.hcxmall.common;import com.google.common.cache.CacheBuilder;import com.google.common.cache.CacheLoader;import com.google.common.cache.LoadingCache;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.util.concurrent.TimeUnit;/** * @author HCX * @create 2017 - 11 - 13 16:09 */public class TokenCache {    private static Logger logger = LoggerFactory.getLogger(TokenCache.class);    public static final String TOKEN_PREFIX = "token_";    /**     * 声明静态内存块     * initialCapacity(1000):设置缓存的初始化容量     * maximumSize(10000):缓存的最大容量,当超过此容量时,guawa的cache会使用LRU算法来移除缓存项     * expireAfterAccess(12, TimeUnit.HOURS):设置有效期 12小时     */    private static LoadingCache<String,String> localCache = CacheBuilder.newBuilder().initialCapacity(1000).maximumSize(10000).expireAfterAccess(12, TimeUnit.HOURS)            .build(new CacheLoader<String, String>() {                //默认的数据加载实现,当调用get取值的时候,如果key没有对应的值,就调用这个方法进行加载                @Override                public String load(String s) throws Exception {                    //防止空指针异常,使用字符串null null.equals()会报空指针异常                    return "null";                }            });    public static void setKey(String key,String value){        localCache.put(key,value);    }     public static String getKey(String key){        String value = null;        try{            value = localCache.get(key);            if("null".equals(value)){                return null;            }        }catch (Exception e){            logger.error("localCache get error",e);        }        return null;     }}

登录demo

user表.jpg

user实体:

public class User {    private Integer id;    private String username;    private String password;    private String email;    private String phone;    private String question;    private String answer;    private Integer role;    private Date createTime;    private Date updateTime;}

前台用户登录UserController:

package com.hcxmall.controller.portal;import com.hcxmall.common.Const;import com.hcxmall.common.ResponseCode;import com.hcxmall.common.ServerResponse;import com.hcxmall.pojo.User;import com.hcxmall.service.IUserService;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 javax.servlet.http.HttpSession;/** * @author HCX * @create 2017 - 11 - 13 9:58 */@Controller@RequestMapping("/user/")public class UserController {    @Autowired    private IUserService iUserService;    /**     *用户登录     * @param username     * @param password     * @param session     * @return     */    @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;    }    /**     * 用户登出     */    @RequestMapping(value = "logout.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<String> logout(HttpSession session){        session.removeAttribute(Const.CURRENT_USER);        return ServerResponse.createBySuccess();    }    /**     * 用户注册     * @param user     * @return     */    @RequestMapping(value = "register.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<String> register(User user){        return iUserService.register(user);    }    /**     * 校验用户名和email是否存在     * @param str     * @param type 是用户名还是email     * @return     */    @RequestMapping(value = "check_valid.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<String> checkValid(String str,String type){        return iUserService.checkValid(str,type);    }    /**     * 获取用户登录信息     * @param session     * @return     */    @RequestMapping(value = "get_user_info.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<User> getUserInfo(HttpSession session){        User user = (User) session.getAttribute(Const.CURRENT_USER);        if(user!=null){            return ServerResponse.createBySuccess(user);        }        return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");    }    /**     * 忘记密保问题     * @param username     * @return     */    @RequestMapping(value = "forget_get_question.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<String> forgetGetQuestion(String username){        return iUserService.selectQuestion(username);    }    /**     * 校验问题答案是否正确:使用本地缓存检查问题答案     * @param username     * @param question     * @param answer     * @return     */    @RequestMapping(value = "forget_check_answer.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<String> forgetCheckAnswer(String username,String question,String answer){        return iUserService.checkAnswer(username,question,answer);    }    /**     * 忘记密码重置密码     * token返回给前端之后,忘记密码中的重置密码需要此token,拿到该token和缓存中作对比     * @param username     * @param passwordNew     * @param forgetToken     * @return     */    @RequestMapping(value = "forget_reset_password.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){        return iUserService.forgetResetPassword(username,passwordNew,forgetToken);    }    /**     * 登录状态的重置密码     * @param session     * @param passwordOld     * @param passwordNew     * @return     */    @RequestMapping(value = "reset_password.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<String> resetPassword(HttpSession session,String passwordOld,String passwordNew){        User user = (User)session.getAttribute(Const.CURRENT_USER);        if(user == null){            return ServerResponse.createByErrorMessage("用户未登录");        }        return iUserService.resetPassword(passwordOld,passwordNew,user);    }    //更新用户个人信息    // 返回user:在更新完个人用户信息之后,要把新的用户信息放到session里并且还要返回给前端,前端直接更新到页面上    //只有在登录状态才能更新用户的信息    /**     * 更新用户个人信息     * @param session     * @param user     * @return     */    @RequestMapping(value = "update_information.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<User> update_information(HttpSession session,User user){        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);        if(currentUser == null){            return ServerResponse.createByErrorMessage("用户未登录");        }        //传来的user对象中没有userId        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;    }    //如果调用该接口 用户没有登录,要进行强制登录    /**     * 获取用户的详细信息:在个人中心修改信息的时候,先获取再修改     * @param session     * @return     */    @RequestMapping(value = "get_information.do",method = RequestMethod.POST)    @ResponseBody    public ServerResponse<User> get_information(HttpSession session){        User currentUser =(User) session.getAttribute(Const.CURRENT_USER);        if(currentUser == null){            //与前端约定,一旦传了10过去,前端就要进行强制登录            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"未登录,需要强制登录status=10");        }        return iUserService.getInformation(currentUser.getId());    }}

后台管理员登录UserManageController:

package com.hcxmall.controller.backend;import com.hcxmall.common.Const;import com.hcxmall.common.ServerResponse;import com.hcxmall.pojo.User;import com.hcxmall.service.IUserService;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 javax.servlet.http.HttpSession;/** * 后台管理 * * @author HCX * @create 2017 - 11 - 14 12:18 */@Controller@RequestMapping("/manage/user")public class UserManageController {    @Autowired    private IUserService iUserService;    @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()){            User user = response.getData();            if(user.getRole() == Const.Role.ROLE_ADMIN){                //说明登录的是管理员                session.setAttribute(Const.CURRENT_USER,user);                return response;            }else {                return ServerResponse.createByErrorMessage("不是管理员,无法登录");            }        }        return response;    }}

IUserService:

public interface IUserService {    ServerResponse<User> login(String username, String password);    ServerResponse<String> register(User user);    ServerResponse<String> checkValid(String str,String type);    ServerResponse selectQuestion(String username);    ServerResponse<String> checkAnswer(String username,String question,String answer);    ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken);    ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user);    ServerResponse<User> updateInformation(User user);    ServerResponse<User> getInformation(Integer userId);    ServerResponse checkAdminRole(User user);}

UserServiceImpl:

package com.hcxmall.service.impl;import com.hcxmall.common.Const;import com.hcxmall.common.ServerResponse;import com.hcxmall.common.TokenCache;import com.hcxmall.dao.UserMapper;import com.hcxmall.pojo.User;import com.hcxmall.service.IUserService;import com.hcxmall.util.MD5Util;import org.apache.commons.lang.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.UUID;/** * @author HCX * @create 2017 - 11 - 13 9:58 */@Service("iUserService")public class UserServiceImpl implements IUserService {    @Autowired    private UserMapper userMapper;    /**     * 用户登录     */    @Override    public ServerResponse<User> login(String username, String password) {        int resultCount = userMapper.checkUsername(username);        if(resultCount==0){            return ServerResponse.createByErrorMessage("用户名不存在");        }        //密码登录MD5        String md5Password = MD5Util.MD5EncodUtf8(password);        User user = userMapper.selectLogin(username,md5Password);        if(user==null){            return ServerResponse.createByErrorMessage("密码错误");        }        //置空密码        user.setPassword(StringUtils.EMPTY);        return ServerResponse.createBySuccess("登录成功",user);    }    /**     * 用户注册     * @param user     * @return     */    @Override    public ServerResponse<String> register(User user){        /*//校验用户名        int resultCount = userMapper.checkUsername(user.getUsername());        if(resultCount>0){            return ServerResponse.createByErrorMessage("用户名已存在");        }        //校验邮箱        resultCount = userMapper.checkEmail(user.getEmail());        if(resultCount>0){            return ServerResponse.createByErrorMessage("email已存在");        }*/        ServerResponse<String> validResponse = this.checkValid(user.getUsername(), Const.USERNAME);        if(!validResponse.isSuccess()){            return validResponse;        }        validResponse = this.checkValid(user.getEmail(), Const.EMAIL);        if(!validResponse.isSuccess()){            return validResponse;        }        user.setRole(Const.Role.ROLE_CUSTOMER);        //密码使用MD5加密        user.setPassword(MD5Util.MD5EncodUtf8(user.getPassword()));        int resultCount = userMapper.insert(user);        if(resultCount == 0){            return ServerResponse.createByErrorMessage("注册失败");        }        return ServerResponse.createBySuccessMessage("注册成功");    }    /**     * 校验用户名和email是否存在:     * 此处是为了给前端一个实时的反馈,在用户填写资料时,当填完了用户名和邮箱之后,在点击下一个输入框时,就要验证用户名和邮箱是否存在,做到实时校验。     * @param str valid值     * @param type username或email     * @return     */    @Override    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("校验成功");    }    @Override    public ServerResponse selectQuestion(String username){        //校验用户名        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);        if(validResponse.isSuccess()){            //用户不存在            return ServerResponse.createByErrorMessage("用户不存在");        }        String question = userMapper.selectQuestionByUsername(username);        if(StringUtils.isNotBlank(question)){            return ServerResponse.createBySuccess(question);        }        return ServerResponse.createByErrorMessage("找回密码的问题是空的");    }    @Override    public ServerResponse<String> checkAnswer(String username,String question,String answer){        int resultCount = userMapper.checkAnswer(username, question, answer);        if(resultCount>0){            //说明问题及问题答案是这个用户的,并且是正确的            String forgetToken = UUID.randomUUID().toString();            //把forgetToken放到本地缓存cache中,设置有效期            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);            //该token返回给前端之后,忘记密码中的重置密码需要此token,拿到该token和缓存中作对比            return ServerResponse.createBySuccess(forgetToken);        }        return ServerResponse.createByErrorMessage("问题的答案错误");    }    @Override    public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){        if(StringUtils.isBlank(forgetToken)){            return ServerResponse.createByErrorMessage("参数错误,token需要传递");        }        ServerResponse validResponse = this.checkValid(username,Const.USERNAME);        if(validResponse.isSuccess()){            return ServerResponse.createByErrorMessage("用户不存在");        }        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);        if(StringUtils.isBlank(token)){            return ServerResponse.createByErrorMessage("token无效或者过期");        }        if(StringUtils.equals(forgetToken,token)){            String md5Password = MD5Util.MD5EncodUtf8(passwordNew);            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);            if(rowCount>0){                return ServerResponse.createBySuccessMessage("修改密码成功");            }        }else {            return ServerResponse.createByErrorMessage("token错误,请重新获取重置密码的token");        }        return ServerResponse.createByErrorMessage("修改密码失败");    }    @Override    public ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user){        //防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户,        // 因为我们会查询一个count(1),如果不指定id,那么结果就是true 即count>0;        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodUtf8(passwordOld), user.getId());        if(resultCount == 0){            return ServerResponse.createByErrorMessage("旧密码错误");        }        user.setPassword(MD5Util.MD5EncodUtf8(passwordNew));        int updateCount = userMapper.updateByPrimaryKeySelective(user);        if(updateCount>0){            return ServerResponse.createBySuccessMessage("密码更新成功");        }        return ServerResponse.createByErrorMessage("密码更新失败");    }    @Override    public ServerResponse<User> updateInformation(User user){        //username不能被更新        //email也要进行一个校验,校验的email是不是已经存在,并且存在的email如果相同的话,不能是我们当前的这个用户的        int resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());        if(resultCount>0){            return ServerResponse.createByErrorMessage("email已存在,请更换email再尝试更新");        }        User updateUser = new User();        updateUser.setId(user.getId());        updateUser.setEmail(user.getEmail());        updateUser.setPhone(user.getPhone());        updateUser.setAnswer(user.getAnswer());        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);        if(updateCount>0){            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);        }        return ServerResponse.createByErrorMessage("更新个人信息失败");    }    @Override    public ServerResponse<User> getInformation(Integer userId){        User user = userMapper.selectByPrimaryKey(userId);        if(user == null){            return ServerResponse.createByErrorMessage("找不到当前用户");        }        user.setPassword(StringUtils.EMPTY);        return ServerResponse.createBySuccess(user);    }    /**     * 校验是否是管理员     * @param user     * @return     */    @Override    public ServerResponse checkAdminRole(User user){        if(user!=null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){            return ServerResponse.createBySuccess();        }        return ServerResponse.createByError();    }}

UserMapper:

package com.hcxmall.dao;import com.hcxmall.pojo.User;import org.apache.ibatis.annotations.Param;/** * @author HCX * @create 2017 - 11 - 13 9:58 */public interface UserMapper {    int deleteByPrimaryKey(Integer id);    int insert(User record);    int insertSelective(User record);    User selectByPrimaryKey(Integer id);    int updateByPrimaryKeySelective(User record);    int updateByPrimaryKey(User record);    /**     * 校验用户名是否存在     * @param username     * @return     */    int checkUsername(String username);    int checkEmail(String email);    /**     * 获取登录用户的信息     * @param username     * @param password     * @return     */    User selectLogin(@Param("username") String username,@Param("password") String password);    String selectQuestionByUsername(String username);    int checkAnswer(@Param("username") String username,@Param("question") String question,@Param("answer") String answer);    int updatePasswordByUsername(@Param("username") String username,@Param("passwordNew") String passwordNew);    int checkPassword(@Param("password") String password,@Param("userId") Integer userId);    int checkEmailByUserId(@Param("email") String email,@Param("userId") Integer userId);}

UserMapper.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.hcxmall.dao.UserMapper" >  <resultMap id="BaseResultMap" type="com.hcxmall.pojo.User" >    <constructor >      <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />      <arg column="username" jdbcType="VARCHAR" javaType="java.lang.String" />      <arg column="password" jdbcType="VARCHAR" javaType="java.lang.String" />      <arg column="email" jdbcType="VARCHAR" javaType="java.lang.String" />      <arg column="phone" jdbcType="VARCHAR" javaType="java.lang.String" />      <arg column="question" jdbcType="VARCHAR" javaType="java.lang.String" />      <arg column="answer" jdbcType="VARCHAR" javaType="java.lang.String" />      <arg column="role" jdbcType="INTEGER" javaType="java.lang.Integer" />      <arg column="create_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />      <arg column="update_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />    </constructor>  </resultMap>  <sql id="Base_Column_List" >    id, username, password, email, phone, question, answer, role, create_time, update_time  </sql>  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >    select     <include refid="Base_Column_List" />    from mmall_user    where id = #{id,jdbcType=INTEGER}  </select>  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >    delete from mmall_user    where id = #{id,jdbcType=INTEGER}  </delete>  <insert id="insert" parameterType="com.hcxmall.pojo.User" >    insert into mmall_user (id, username, password,       email, phone, question,       answer, role, create_time,       update_time)    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},       #{email,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{question,jdbcType=VARCHAR},       #{answer,jdbcType=VARCHAR}, #{role,jdbcType=INTEGER}, now(),      now())  </insert>  <insert id="insertSelective" parameterType="com.hcxmall.pojo.User" >    insert into mmall_user    <trim prefix="(" suffix=")" suffixOverrides="," >      <if test="id != null" >        id,      </if>      <if test="username != null" >        username,      </if>      <if test="password != null" >        password,      </if>      <if test="email != null" >        email,      </if>      <if test="phone != null" >        phone,      </if>      <if test="question != null" >        question,      </if>      <if test="answer != null" >        answer,      </if>      <if test="role != null" >        role,      </if>      <if test="createTime != null" >        create_time,      </if>      <if test="updateTime != null" >        update_time,      </if>    </trim>    <trim prefix="values (" suffix=")" suffixOverrides="," >      <if test="id != null" >        #{id,jdbcType=INTEGER},      </if>      <if test="username != null" >        #{username,jdbcType=VARCHAR},      </if>      <if test="password != null" >        #{password,jdbcType=VARCHAR},      </if>      <if test="email != null" >        #{email,jdbcType=VARCHAR},      </if>      <if test="phone != null" >        #{phone,jdbcType=VARCHAR},      </if>      <if test="question != null" >        #{question,jdbcType=VARCHAR},      </if>      <if test="answer != null" >        #{answer,jdbcType=VARCHAR},      </if>      <if test="role != null" >        #{role,jdbcType=INTEGER},      </if>      <if test="createTime != null" >        now(),      </if>      <if test="updateTime != null" >        now(),      </if>    </trim>  </insert>  <update id="updateByPrimaryKeySelective" parameterType="com.hcxmall.pojo.User" >    update mmall_user    <set >      <if test="username != null" >        username = #{username,jdbcType=VARCHAR},      </if>      <if test="password != null" >        password = #{password,jdbcType=VARCHAR},      </if>      <if test="email != null" >        email = #{email,jdbcType=VARCHAR},      </if>      <if test="phone != null" >        phone = #{phone,jdbcType=VARCHAR},      </if>      <if test="question != null" >        question = #{question,jdbcType=VARCHAR},      </if>      <if test="answer != null" >        answer = #{answer,jdbcType=VARCHAR},      </if>      <if test="role != null" >        role = #{role,jdbcType=INTEGER},      </if>      <if test="createTime != null" >        create_time = #{createTime,jdbcType=TIMESTAMP},      </if>      <if test="updateTime != null" >        update_time = now(),      </if>    </set>    where id = #{id,jdbcType=INTEGER}  </update>  <update id="updateByPrimaryKey" parameterType="com.hcxmall.pojo.User" >    update mmall_user    set username = #{username,jdbcType=VARCHAR},      password = #{password,jdbcType=VARCHAR},      email = #{email,jdbcType=VARCHAR},      phone = #{phone,jdbcType=VARCHAR},      question = #{question,jdbcType=VARCHAR},      answer = #{answer,jdbcType=VARCHAR},      role = #{role,jdbcType=INTEGER},      create_time = #{createTime,jdbcType=TIMESTAMP},      update_time = now()    where id = #{id,jdbcType=INTEGER}  </update>  <select id="checkUsername" resultType="int" parameterType="string">    SELECT COUNT(1) FROM mmall_user    WHERE username = #{username}  </select>  <select id="checkEmail" resultType="int" parameterType="string">     SELECT COUNT(1) FROM mmall_user     WHERE email = #{email}  </select>  <select id="selectLogin" resultMap="BaseResultMap" parameterType="map">    SELECT    <include refid="Base_Column_List" />    FROM mmall_user    WHERE username = #{username}    AND password = #{password}  </select>  <select id="selectQuestionByUsername" resultType="string" parameterType="string">    SELECT question    FROM mmall_user    WHERE username = #{username}  </select>  <select id="checkAnswer" resultType="int" parameterType="map">    SELECT COUNT(1)    FROM mmall_user    WHERE username = #{username}    and question = #{question}    and answer = #{answer}  </select>  <select id="updatePasswordByUsername" parameterType="map">    UPDATE mmall_user    SET password = #{passwordNew},update_time = now()    WHERE username = #{username}  </select>  <select id="checkPassword" resultType="int" parameterType="map">    SELECT COUNT(1)    FROM mmall_user    WHERE id = #{userId}    and password = #{password}  </select>  <select id="checkEmailByUserId" resultType="int" parameterType="map" >    SELECT count(1)    FROM mmall_user    WHERE email = #{email}    AND id != #{userId}  </select></mapper>

密码存到数据库时使用MD5加密:

package com.hcxmall.util;import java.security.MessageDigest;/** * MD5加密 * * @author HCX * @create 2017 - 11 - 13 11:37 */public class MD5Util {    /**     * 内部使用的加密算法     * @param b     * @return     */    private static String byteArrayToHexString(byte b[]){        StringBuffer resultSb = new StringBuffer();        for(int i = 0;i<b.length;i++){            resultSb.append(byteToHexString(b[i]));        }        return resultSb.toString();    }    /**     * 内部使用的加密算法     * @param b     * @return     */    private static String byteToHexString(byte b){        int n=b;        if(n<0){            n+=256;        }        int d1 = n/16;        int d2 = n%16;        return hexDigits[d1] + hexDigits[d2];    }    /**     * 返回大写MD5     * @param origin 要加密的原字符串     * @param charsetname 加密算法使用的字符集     * @return     */    public static String MD5Encode(String origin,String charsetname){        String resultString = null;        try {            resultString = new String(origin);            MessageDigest md = MessageDigest.getInstance("MD5");            //如果字符集不传,则使用默认的字符集            if(charsetname == null || "".equals(charsetname)){                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));            }else {                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));            }        }catch (Exception exception){        }        return resultString.toUpperCase();    }    public static String MD5EncodUtf8(String origin){//        origin = origin+PropertiesUtil.getProperty("password.salt","");        return MD5Encode(origin,"utf-8");    }    private static final String hexDigits[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};}
原创粉丝点击