spring + mybatis + springMVC + maven 实现登陆的一些功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring + mybatis + springMVC + maven 实现登陆的一些功能相关的知识,希望对你有一定的参考价值。

  近期的项目,从中学到了很多,现在分享给大家,希望对需要的有帮助

  分享给大家的是 ssm的整合, 提供app的一些接口和业务层的代码,

  还是废话少说,直接上代码吧!!!

  dao层的代码就不贴了,都是逆向工程生成的,直接从servcie层开始

  UserYzmservice接口:

  

/**
 * 发送用户验证码
 * @author Administrator
 *
 */
public interface UserYzmService extends BaseService<UserYzm, UserYzmExample, Long>{

         /**
         * @param phone
         * @param yzm
         * @return 校验验证码
         */
        public  boolean  validateYzm(String phone,String yzm);
}

  

  BaseService接口:

public interface BaseService  <T, E, P> {

    int countByExample(E example);

    int deleteByExample(E example);

    int deleteByPrimaryKey(P id);

    int insert(T record);

    int insertSelective(T record);

    int updateByExampleSelective( T record,  E example);

    int updateByExample(T record, E example);

    int updateByPrimaryKeySelective(T record);

    int updateByPrimaryKey(T record);
    
    List<T> selectByExample(E example);

    T selectByPrimaryKey(P id);
    
    PageInfo<T> select(E example, int pageNum, int pageSize);
}

 

  UserYzmServiceImpl:

@Service("userYzmService")
public class UserYzmServiceImpl extends BaseServiceImpl<UserYzm, UserYzmExample, Long> implements UserYzmService{

    @Autowired
    private UserYzmMapper userYzmMapper;
    /**
     * 校验验证码
     */
    public boolean validateYzm(String phone, String yzm) {
        
        UserYzmExample example = new UserYzmExample();  
        example.setOrderByClause("id desc");
        UserYzmExample.Criteria criteria = example.createCriteria();  
        criteria.andPhoneEqualTo(phone);
        criteria.andCodeEqualTo(Integer.parseInt(yzm));
        List<UserYzm> userYzmlist =userYzmMapper.selectByExample(example);
        if(userYzmlist!=null && userYzmlist.size()>0){
            int  min=    DateUtil.diffMinute(new Date(),userYzmlist.get(0).getCreateTime());
            if(min<10){
                int yzmcode=userYzmlist.get(0).getCode();
                if(Integer.valueOf(yzm).intValue()==yzmcode){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public BaseMapper<UserYzm, UserYzmExample, Long> getBaseMapper() {
        // TODO Auto-generated method stub
        return userYzmMapper;
    }
}

 

  UserController:

/**
 * 用户所有接口 包括 1、用户注册; 2、找回密码; 3、获取验证码;4.用户登录
 * 
 * @author shism
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    protected static final Logger log = LoggerFactory
            .getLogger(UserController.class);

    @Autowired
    private UserYzmService userYzmService;
    @Autowired
    private BaseUserService baseUserService;

    /**
     * 获取验证码
     * <pre>
     *     用户ID:userId
     *     电话:phone
     * </pre>
     * @return 
     *         <pre>
     * {
     *             isSuccess:方法是否成功  true 成功 false失败,
     *          errorMessage:错误信息,
     *          message:成功返回值,
     *          errorCode:错误代码 同步一个枚举类ErrorCode,
     * value:[]
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/sendYzm", method = { RequestMethod.POST,
            RequestMethod.GET })
    @ResponseBody
    public Object sendYzm(@RequestBody UserYzm userYzm) {
        String jsonp = null;
        if (StringUtils.isEmpty(userYzm.getPhone())) {
            return this.renderJsonForObject(jsonp, new Result(
                    ErrorCode.ERROR_CODE_99998));
        }
        if (StringUtils.isEmpty(userYzm.getPhone())) {
            return this.renderJsonForObject(jsonp, new Result(
                    ErrorCode.ERROR_CODE_99998));
        }
        // 调用发送验证码Util
        int yzm = CodeUtils.getSmsCode();
        try {
            String retMsg = SmsUtil.sendPhoneMsg(yzm, userYzm.getPhone());
            JSONObject retJsonobject = JSONObject.fromObject(retMsg);
            if (retJsonobject.get("msg") != null) {
                if ("OK".equals(retJsonobject.getString("msg"))) {
                    UserYzm userYzmAdd = new UserYzm();
                    userYzmAdd.setCode(yzm);
                    userYzmAdd.setCreateTime(new Date());
                    userYzmAdd.setPhone(userYzm.getPhone());
                    int flag = userYzmService.insertSelective(userYzmAdd);
                    if (flag == 1) {
                        return this.renderJsonForObject(jsonp, new Result(true,
                                "验证码发送成功,请查收!"));
                    } else {
                        return this.renderJsonForObject(jsonp, new Result(
                                ErrorCode.ERROR_CODE_99985));
                    }
                } else {
                    return this.renderJsonForObject(jsonp, new Result(
                            ErrorCode.ERROR_CODE_99985));
                }
            } else {
                return this.renderJsonForObject(jsonp, new Result(
                        ErrorCode.ERROR_CODE_99985));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return this.renderJsonForObject(jsonp, new Result(
                    ErrorCode.ERROR_CODE_99985));
        }
    }

    /**
     * 注册接口
     * 
     * <pre>
     *     域参数:callback
     *     手机号:phone
     *     密码:uPass
     *     用户类型:userType  ( 1位个人注册 2 为企业注册)
     *     验证码:yzm
     * </pre>
     * @return 
     *         <pre>
     * {
     *             isSuccess:方法是否成功  true 成功 false失败,
     *          errorMessage:错误信息,
     *          message:成功返回值,
     *          errorCode:错误代码 同步一个枚举类ErrorCode,
     *          totalCount:返回值中的总记录数,
     *          pageSize:每页多少数据,默认20条,
     *          pageNo:当前第几页,
     *          pageCount:总页数,
     *          nextPageNo:下一页页数,如果为0则表示无下一页,
     *          imgHost:图片服务器地址
     *          value:{"id":"用户ID(long)","name":"用户名称(string)","phone":"电话(string)","type":"用户类型(Integer)","hasPhone":"是否绑定手机 1已绑定 0未绑定(String)","headImg":"头像(String)","companyName","公司名称(String)"}
     * }
     * </pre>
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping(value = "/reg", method = { RequestMethod.POST,
            RequestMethod.GET })
    @ResponseBody
    public Object reg(@RequestBody BaseUser baseUser) {
        String jsonp = null;
        try {

            // 验证验证码
            if (!userYzmService.validateYzm(baseUser.getPhone(),
                    baseUser.getYzm())) {
                return this.renderJsonForObject(jsonp, new Result(
                        ErrorCode.ERROR_CODE_99983));
            }
            String passwordMd5 = MD5Util.getMD5String(baseUser.getuPass());
            //密码加密
            baseUser.setuPass(passwordMd5);
            baseUser.setCreatTime(new Date());
            //生成userId
            baseUser.setUserId(IdCenterUtil.getInstance().getId()+"");
            BaseUserExample example = new BaseUserExample();
            example.setOrderByClause("id desc");
            BaseUserExample.Criteria criteria = example.createCriteria();
            criteria.andPhoneEqualTo(baseUser.getPhone());
            List<BaseUser> list = baseUserService.selectByExample(example);
            if (list != null && list.size() > 0) {
                return this.renderJsonForObject(jsonp, new Result(
                        ErrorCode.ERROR_CODE_99989));
            } else {
                int flag = baseUserService.insertSelective(baseUser);
                if (flag == 1) {
                    // TODO:注册环信
                    // hxService.createNewIMUserSingle(user.getId());
                    return this.renderJsonForObject(jsonp, new Result(
                            genRetUserJson(baseUser), 1));
                } else {
                    return this.renderJsonForObject(jsonp, new Result(
                            ErrorCode.ERROR_CODE_99988));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return this.renderJsonForObject(jsonp, new Result(
                    ErrorCode.ERROR_CODE_99999));
        }
    }
    /**登录接口 
     *  <pre>
     *     手机号:phone
     *     密码:uPass
     *     登陆类型:type  (pt 普通登陆,wx 微信登陆 qq QQ登陆)
     *             openid
     *             headimgurl
     *             nickname
     *  </pre>
     * @return <pre>{
     *             isSuccess:方法是否成功  true 成功 false失败,
     *          errorMessage:错误信息,
     *          message:成功返回值,
     *          errorCode:错误代码 同步一个枚举类ErrorCode,
     *          totalCount:返回值中的总记录数,
     *          pageSize:每页多少数据,默认20条,
     *          pageNo:当前第几页,
     *          pageCount:总页数,
     *          nextPageNo:下一页页数,如果为0则表示无下一页,
     *          imgHost:图片服务器地址
     *          value:{"id":"用户ID(long)","name":"用户名称(string)","phone":"电话(string)","type":"用户类型(Integer)","workId":"职业(long)","hasPhone":"是否绑定手机 1已绑定 0未绑定(String)","headImg":"头像(String)","companyName","公司名称(String)"}
     * }</pre>
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/login", method = { RequestMethod.POST ,RequestMethod.GET} )
    @ResponseBody
    public Object login(@RequestBody BaseUser baseUser) {
        String jsonp =null;
        if(baseUser!=null){
            BaseUser userOb=null;
            if("pt".equals(baseUser.getType())){
                BaseUser userRet = baseUserService.verifyApiUser(baseUser.getPhone(), baseUser.getuPass());
                if(userRet!=null ){
                    userOb=    userRet;
                }
            }
            if(userOb!=null){
                return this.renderJsonForObject(jsonp,new Result(true,genRetUserJson(userOb), "登录成功"));
            }else{
                return this.renderJsonForObject(jsonp,new Result(ErrorCode.ERROR_CODE_99987));
            }
        }
        return this.renderJsonForObject(jsonp,new Result(ErrorCode.ERROR_CODE_99998));
    }
    
    /**重置密码
     *  <pre>
     *     密码:uPass
     *     电话:phone
     *     验证码:yzm
     *  </pre>
     * @return <pre>{
     *             isSuccess:方法是否成功  true 成功 false失败,
     *          errorMessage:错误信息,
     *          message:成功返回值,
     *          errorCode:错误代码 同步一个枚举类ErrorCode,
     *          totalCount:返回值中的总记录数,
     *          pageSize:每页多少数据,默认20条,
     *          pageNo:当前第几页,
     *          pageCount:总页数,
     *          nextPageNo:下一页页数,如果为0则表示无下一页,
     *          imgHost:图片服务器地址
     *          value:[]
     */
    @RequestMapping(value = "/restPassWord", method = { RequestMethod.POST ,RequestMethod.GET} )
    @ResponseBody
    public Object restPassWord(@RequestBody BaseUser baseUser) {
        String jsonp =null;
        if(baseUser!=null) {
            //校验用户是否存在
            BaseUser obj = baseUserService.selectUserByPhone(baseUser.getPhone());
            //查找10分钟内未过期时间内的验证码 按照发送时间降序排列的 第一个个 校验验证码是否过期或是否正确
            if(obj!=null && userYzmService.validateYzm(baseUser.getPhone(),baseUser.getYzm())){
                baseUser.setuPass(MD5Util.getMD5String(baseUser.getuPass()));
                baseUser.setId(obj.getId());//设置主键id
                baseUser.setUpdateTime(new Date());
                int flag=baseUserService.updateByPrimaryKeySelective(baseUser);
                if(flag==1){
                    return this.renderJsonForObject(jsonp,new Result(true,"重置密码成功"));
                }else{
                    return this.renderJsonForObject(jsonp,new Result(ErrorCode.ERROR_CODE_99986));
                }
            }else{
                if(obj==null){
                    return this.renderJsonForObject(jsonp,new Result(ErrorCode.ERROR_CODE_99980));
                }else{
                return this.renderJsonForObject(jsonp,new Result(ErrorCode.ERROR_CODE_99995));
                }
            }
        }else{
            return this.renderJsonForObject(jsonp, new Result(ErrorCode.ERROR_CODE_99998));
        }
    }
}

  

  BaseController:

public class BaseController  {

    protected static final Logger log = LoggerFactory.getLogger(BaseController.class);
    
    @Autowired(required=true)
    protected HttpServletRequest request;

    @Autowired(required=false)
    protected HttpServletResponse response;

    @Autowired(required=true)
    protected HttpSession session;
    
    protected JSONObject postParm(HttpServletRequest request){
        StringBuffer info = new java.lang.StringBuffer();
        InputStream in=null;
        try {
            in = request.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedInputStream buf = new BufferedInputStream(in);
        byte[] buffer = new byte[1024];
        int iRead;
        try {
            while ((iRead = buf.read(buffer)) != -1) {
                info.append(new String(buffer, 0, iRead, "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(StringUtils.isNotEmpty(info.toString())){
            return JSONObject.fromObject(info.toString());
        }
        return null;
    }
    
    protected void renderJson(String jsonp, Object target,HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setContentType("text/html; charset=UTF-8");
            System.out.println("target:"+target);
            
            JSONObject json = JSONObject.fromObject(target);
            System.out.println("json:"+json);
            
            String echo = nativeToAscii(json.toString());
            if (!StringUtils.isBlank(jsonp)) {
                echo = jsonp + "(" + echo + ")";
            }
            out = response.getWriter();
            out.print("\n" + echo); 
            out.flush();
        } catch (Exception e) {
            log.error("Error occured while response json string.", e);
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (Exception e) {
                    // ignore
                }
            }
        }
    }
    
    protected Object renderJsonForObject(String jsonp, Object target) {
        String echo = null;
        try {
            JSONObject json = JSONObject.fromObject(target);
            System.out.println("====================="+json.toString());
            echo = nativeToAscii(json.toString());
            if (!StringUtils.isBlank(jsonp)) {
                echo = jsonp + "(" + echo + ")";
            }
          
        } catch (Exception e) {
            log.error("Error occured while response json string.", e);
        } 
        return echo;
}
    /**
     * unicode convert (\\u format)
     * 
     * @param input text string
     * @return unicode string
     */
    public static String nativeToAscii(String input) {
        if (input == null)  return null;
        StringBuilder buffer = new StringBuilder(input.length() + 60);
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c <= 0x7E) {
                buffer.append(c);
            } else {
                buffer.append("\\u");
                String hex = Integer.toHexString(c);
                for (int j = hex.length(); j < 4; j++) {
                    buffer.append(‘0‘);
                }
                buffer.append(hex);
            }
        }
        try {
            return buffer.toString();
        } finally {
            buffer.setLength(0);
            buffer = null;
        }
    }
    public  JSONObject genRetUserJson(BaseUser user) {
        JSONObject obj=new JSONObject();
        obj.accumulate("id", user.getUserId());
        if(user.getuName()==null){
            obj.accumulate("name", "");
        }else{
            obj.accumulate("name", user.getuName());
        }
        
        obj.accumulate("phone", user.getPhone());
        if(user.getuType()==null){
            obj.accumulate("uType", "");
        }else{
            obj.accumulate("uType", user.getuType());
        }
        if(StringUtils.isNotEmpty(user.getPhone())){
            obj.accumulate("hasPhone", "1");
        }else{
            obj.accumulate("hasPhone", "0");
        }
        return obj;
    }
}

 

  ErrorCode:

public enum ErrorCode {
    
    ERROR_CODE_99999(99999,"对不起,系统异常,请稍后重试!"),
    ERROR_CODE_99998(99998,"对不起,缺少参数错误编号ERROR99998,请稍后重试!"),
    ERROR_CODE_99997(99997,"对不起,查询对象参数为NULL,请补充之后重试!"),
    ERROR_CODE_99996(99996,"对不起,用户名或密码错误,请重试!"),
    ERROR_CODE_99995(99995,"对不起,验证码错误,请重新获取重试!"),
    ERROR_CODE_99994(99994,"对不起,删除失败,请稍后重试!"),
    ERROR_CODE_99993(99993,"对不起,查询无数据,当前操作失败,请稍后重试!"),
    ERROR_CODE_99992(99992,"对不起,修改失败,请稍后重试!"),
    ERROR_CODE_99991(99991,"对不起,上传图片错误,不是图片格式,请重新上传!"),
    ERROR_CODE_99990(99990,"对不起,上传图片失败,请重新上传!"),
    ERROR_CODE_99989(99989,"对不起,用户名已被注册!"),
    ERROR_CODE_99988(99988,"对不起,注册失败!"),
    ERROR_CODE_99987(99987,"登录失败!"),
    ERROR_CODE_99986(99986,"修改密码失败!"),
    ERROR_CODE_99985(99985,"对不起,验证码发送失败,请稍后重试!"),
    ERROR_CODE_99984(99984,"对不起,订单提交送失败,缺少必要的参数!"),
    ERROR_CODE_99983(99983,"对不起,验证码验证失败,请重新获取!"),
    ERROR_CODE_99982(99982,"对不起,密码错误,请重试!"),
    ERROR_CODE_99981(99981,"对不起,操作失败,请重试!"),
    ERROR_CODE_99980(99980,"对不起,无此用户,请重试!"),
    ERROR_CODE_99979(99979,"支付失败,订单金额与支付金额不一致,请重试!"),
    ERROR_CODE_99978(99978,"对不起,库存不足!"),
    ERROR_CODE_99977(99977,"暂无此组合服务!"),
    ERROR_CODE_99976(99976,"订单已支付,不能取消!"),
    ERROR_CODE_99975(99975,"对不起,支付异常,请稍候重试!"),
    ;
    
    
    private ErrorCode(int key,String value){
        this.key = key;
        this.value = value;
    }
    private int key;
    
    private String value;

    public int getKey() {
        return key;
    }

    public void setKey(int key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

 

以上是关于spring + mybatis + springMVC + maven 实现登陆的一些功能的主要内容,如果未能解决你的问题,请参考以下文章

怎么用spring 管理mybatis

spring整合mybatis

Spring集成Mybatis3

Mybatis整合Spring

Mybatis整合Spring

Mybatis整合Spring