`
收藏列表
标题 标签 来源
动态 行转列
DELIMITER $$
USE `test`$$
DROP PROCEDURE IF EXISTS `score_statistical`$$
CREATE   PROCEDURE `score_statistical` ()
BEGIN
SET @EE='';
set @str_tmp='';
SELECT @EE:=CONCAT(@EE,'SUM(IF(caiming=\'',caiming,'\'',',num,0)) AS ',caiming,',') as aa into @str_tmp FROM (SELECT DISTINCT caiming FROM orders) A order by length(aa) desc limit 1; 
SET @QQ=CONCAT('SELECT ifnull(custName,\'total\'),',LEFT(@str_tmp,char_length(@str_tmp)-1),'   FROM orders GROUP BY custName WITH ROLLUP');
PREPARE stmt  FROM @QQ; 
EXECUTE stmt ;
deallocate prepare stmt; 
END$$
 DELIMITER ;
 
  CALL `score_statistical`() 
DateUtil
/**
 * Copyright appscomm 2013. All rights reserved.
 */

package com.appscomm.common.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @ClassName:DateUtil.java
 * @ 
 */

public class DateUtil {

	// 24小时制格式
    public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_FORMAT = "yyyy-MM-dd";

    public static final String DATE_FORMAT2 = "yyyyMMdd";

    public static final String DATETIME_FORMAT2 = "yyyyMMddHHmmss";

    public static final String DATETIME_MIN_FORMAT = "yyyyMMddHHmm";

    public static final String DATETIME_FORMAT17 = "yyyyMMddHHmmssSSS";
    
    public static final String DATETIME_FORMAT19 = "yyyy-MM-dd HH:mm:ss:SSS";
    
    public static final String DATE_FORMAT_DAY="yyyy-MM-dd";
    
    public static final String DATE_FORMAT_MONTH="yyyy-MM";
    
    public static final String DATE_FORMAT_MIN="hh:MM";
    private static SimpleDateFormat SIMPLE_DB_DATE_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd");
	private static DateFormat DB_DATE_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	
    public static Date formatDate(String str, String pattern) {
        SimpleDateFormat dateFormat = null;
        try {
            dateFormat = new SimpleDateFormat(pattern);
            return dateFormat.parse(str);
        } catch (Exception e) {
            return null;
        }
    }
    
    public static String parseDate(Object date, String pattern) {
        SimpleDateFormat dateFormat = null;
        try {
            dateFormat = new SimpleDateFormat(pattern);
            return dateFormat.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    public static String formatDate(Date date, String pattern) {
        SimpleDateFormat dateFormat = null;
        try {
            if (StringUtils.isEmpty(pattern)) {
                dateFormat = new SimpleDateFormat(DATETIME_FORMAT);
            } else {
                dateFormat = new SimpleDateFormat(pattern);
            }
        } catch (Exception e) {
            dateFormat = new SimpleDateFormat(DATETIME_FORMAT);
        }
        return dateFormat.format(date);
    }
    
    public static String getCurDateTime() {
        Calendar cal = Calendar.getInstance();
        return formatDate(cal.getTime(), null);
    }

    public static String getDateTime24() {
        return getDateTime(7);
    }

    public static String getDateTime(int size) {
        return formatDate(new Date(), DATETIME_FORMAT17) + RandomStringUtils.randomNumeric(size);
    }

    public static String formatDateCN(Date date) {
        if (date == null) {
            return "";
        }
        Calendar cal = Calendar.getInstance(Locale.CHINA);
        cal.setTime(date);
        return cal.get(Calendar.YEAR) + "年" + (cal.get(Calendar.MONTH) + 1) + "月" + cal.get(Calendar.DATE) + "日";
    }

    public static String getBefore(long beforeMils, String pattern) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(calendar.getTimeInMillis() - beforeMils);
        return formatDate(calendar.getTime(), pattern);
    }
    public static String getFirstDay(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, 1);// 设置为当月的第一天
		String day_first = df.format(calendar.getTime());
		StringBuffer firstStr = new StringBuffer().append(day_first).append(
				" 00:00:00");
		return firstStr.toString();
	}

	public static String getLastDay(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, 1); // 加一个月
		calendar.set(Calendar.DATE, 1); // 设置为该月第一天
		calendar.add(Calendar.DATE, -1); // 再减一天即为上个月最后一天
		String day_last = df.format(calendar.getTime());
		StringBuffer lastStr = new StringBuffer().append(day_last).append(
				" 23:59:59");
		return lastStr.toString();
	}

	public static Date parseSimpleDbDate(String dateStr) throws Exception {
		synchronized (SIMPLE_DB_DATE_FORMAT) {
			return SIMPLE_DB_DATE_FORMAT.parse(dateStr);
		}
	}

	public static Date parseDbDate(String dateStr) throws Exception {
		synchronized (DB_DATE_FORMAT) {
			return DB_DATE_FORMAT.parse(dateStr);
		}
	}

	public static String formatSimpleDbDate(Date date) {
		synchronized (SIMPLE_DB_DATE_FORMAT) {
			return SIMPLE_DB_DATE_FORMAT.format(date);
		}
	}

	public static String formatDbDate(Date date) {
		synchronized (DB_DATE_FORMAT) {
			return DB_DATE_FORMAT.format(date);
		}
	}

	/**
	 * 
	 * 
	 * 功能描述:原来时间与当前时间比较<5分钟,则判断为未超时,返回false,否则返回true
	 * 
	 * @param srcTime
	 *            原来时间
	 * @param currentTime
	 *            当前时间
	 * @return
	 * @author Administrator
	 * @version 1.0
	 * @since 2013-7-31
	 *
	 */
	public static boolean isLockTimeOut(Date srcTime, Date currentTime) {
		if (srcTime == null || currentTime == null)
			return false;
		if ((currentTime.getTime() - srcTime.getTime()) < 300000)
			return false;
		else
			return true;
	}

	public static Date minusDate(Date srcDate, int dateNum)
			throws ParseException {
		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(srcDate);
		date.set(Calendar.DATE, date.get(Calendar.DATE) - dateNum);
		return dft.parse(dft.format(date.getTime()));
	}

	public static Date addDate(Date srcDate, int dateNum) throws ParseException {
		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(srcDate);
		date.set(Calendar.DATE, date.get(Calendar.DATE) + dateNum);
		return dft.parse(dft.format(date.getTime()));
	}

	public static Date trunc(Date time, String formatStr) {
		SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
		String timeStr = formatter.format(time);
		try {
			return formatter.parse(timeStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date trunc(Date maxEndTime) {
		return trunc(maxEndTime, "yyyy-MM-dd 00:00:00");
	}

	public static Date truncMax(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		String day_last = df.format(calendar.getTime());
		StringBuffer lastStr = new StringBuffer().append(day_last).append(
				" 23:59:59");
		try {
			return DB_DATE_FORMAT.parse(lastStr.toString());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static boolean dateSimpleEqual(Date begin, Date end) {
		Calendar beginCalendar = Calendar.getInstance();
		beginCalendar.setTime(DateUtil.trunc(begin, "yyyy-MM-dd"));
		Calendar endCalendar = Calendar.getInstance();
		endCalendar.setTime(DateUtil.trunc(end, "yyyy-MM-dd"));
		return beginCalendar.getTimeInMillis() == endCalendar.getTimeInMillis();
	}
	public static boolean dateMonthEqual(Date begin, Date end) {
		Calendar beginCalendar = Calendar.getInstance();
		beginCalendar.setTime(DateUtil.trunc(begin, "yyyy-MM"));
		Calendar endCalendar = Calendar.getInstance();
		endCalendar.setTime(DateUtil.trunc(end, "yyyy-MM"));
		return beginCalendar.getTimeInMillis() == endCalendar.getTimeInMillis();
	}
	
	public static String makeDateSeqNo() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
		Date now = new Date();
		String dateStr = format.format(now) + "" + now.getTime();
		return dateStr;
	}
}
1
package com.appscomm.plm.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.guzz.dao.GuzzBaseDao;
import org.guzz.orm.se.SearchExpression;
import org.guzz.orm.se.Terms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.appscomm.common.AccountTypeEnum;
import com.appscomm.common.AppscommException;
import com.appscomm.common.AppscommTokenManager;
import com.appscomm.common.ContactTypeEnum;
import com.appscomm.common.calibrator.AppClientCalibrator;
import com.appscomm.common.calibrator.CalibratorChain;
import com.appscomm.common.calibrator.CalibratorResult;
import com.appscomm.common.calibrator.ParamExistCalibrator;
import com.appscomm.common.redis.support.RedisOpsTemplate;
import com.appscomm.common.utils.BeanCopierUtils;
import com.appscomm.plm.common.calibrator.AccountTypeCalibrator;
import com.appscomm.plm.domain.PlmLoginAccount;
import com.appscomm.plm.domain.PlmUser;
import com.appscomm.plm.domain.PlmUserContact;
import com.appscomm.plm.domain.PlmUserInfo;
import com.appscomm.plm.inout.BaseUserResponse;
import com.appscomm.plm.inout.UserForgotPasswordRequest;
import com.appscomm.plm.inout.UserLoginRequest;
import com.appscomm.plm.inout.UserLoginResponse;
import com.appscomm.plm.inout.UserModifyPasswordReqeust;
import com.appscomm.plm.inout.UserRegisterRequest;
import com.appscomm.plm.inout.UserRegisterResponse;
import com.appscomm.plm.service.AccountService;
import com.appscomm.plm.vo.AccountUserVo;
import com.appscomm.plm.vo.PlmUserInfoVo;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
	@Autowired
	private  GuzzBaseDao appscmBaseDao;
	@Autowired
	private RedisOpsTemplate redisOpsTemplate;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	

	@Override
	public UserLoginResponse login(UserLoginRequest request) {
		logger.info("UserLoginRequest="+JSON.toJSON(request).toString());
		UserLoginResponse response = new UserLoginResponse(request.getSeq(),request.getVersionNo());
		try{
			//参数校验
			CalibratorChain calibratorChain = new CalibratorChain();
			Object[] existParams = new Object[]{
					new String[]{request.getSeq(),"CRM101","随机序列码不能为空"},
					new String[]{request.getVersionNo(),"CRM104","接口版本号不能为空"},
					new String[]{request.getClientType(),"CRM105","客户端类型不能为空"},
					new String[]{request.getAccountId(),"APPS-10001","账户不能为空"},
					new String[]{request.getPassword(),"APPS-10013","密码不能为空"}};
			calibratorChain.
				addCalibrator(ParamExistCalibrator.instance()).
				addCalibrator(AppClientCalibrator.instance());
			CalibratorResult calibratorResult= calibratorChain.execute(new Object[]{existParams,request.getClientType()});
			
			if(calibratorResult != null && 
					!CalibratorResult.RESULT_SUCCESS.equalsIgnoreCase(calibratorResult.getCode())){
				response = new UserLoginResponse(request.getSeq(),request.getVersionNo(),calibratorResult.getCode(),calibratorResult.getMessage());
				logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
				return response;
			}
			AccountUserVo accountUserVo = getPlmAccount(request.getAccountId());
			if(accountUserVo == null){
				response = new UserLoginResponse(request.getSeq(),request.getVersionNo(),"APPS-10006","非法账户");
				logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
				return response;
			}
			//新旧密码是否相等
			if(!request.getPassword().equals(accountUserVo.getAccountPassword())){
				response = new UserLoginResponse(request.getSeq(),request.getVersionNo(),"APPS-10006","非法账户");
				logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
				return response;
			}
			//判断密码加密方式MD5 32位
			if(request.getPassword().length()!=32){
				response = new UserLoginResponse(request.getSeq(),request.getVersionNo(),"APPS-10013","密码MD5加密方式");
				logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
				return response;
			}
			String token = AppscommTokenManager.getInstance().generateToken(request.getAccountId());
			
			PlmUser plmUser = getPlmUser(accountUserVo.getUserId().intValue());
			plmUser.setLoginToken(token);
			appscmBaseDao.update(plmUser);
			response.setToken(token);
			response.setUserId(accountUserVo.getUserId().intValue());
			response.setUserInfoId(accountUserVo.getUserInfoId().intValue());
			//登录返回的附加信息
			Map<String, Object> respMap = new HashMap<String, Object>();
			//用户个人信息
			PlmUserInfoVo userInfo = getUesrInfo(accountUserVo.getUserInfoId());
			//绑定信息
			//目标信息
			//睡眠提醒
			//事项提醒
			//久坐提醒
			//通知开关
			//固件版本号
			respMap.put("userInfo", userInfo);
			response.setUserMap(respMap);
			
		}catch(AppscommException e){
			logger.info(e.getMessage());
			response = new UserLoginResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(e.getErrCode());;
			response.setResultMessage(e.getMessage());
		}catch(Exception e){
			logger.info(e.getMessage());
			response = new UserLoginResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(BaseUserResponse.RESULT_UNKNOWN);
			response.setResultMessage(e.getMessage());
		}
		logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
		return response;
	}

	private PlmUserInfoVo getUesrInfo(Long userInfoId) {
		SearchExpression se =SearchExpression.forClass(PlmUserInfo.class) ;
		se.and(Terms.eq("userInfoId",userInfoId.intValue()));
		PlmUserInfo plmUserInfo = (PlmUserInfo)appscmBaseDao.findObject(se);
		if(plmUserInfo != null){
			PlmUserInfoVo plmUserInfoVo = new PlmUserInfoVo();
			BeanCopierUtils.copyProperty(plmUserInfo, plmUserInfoVo);
			return plmUserInfoVo;
		}
		return null;
	}

	private AccountUserVo getPlmAccount(String accountId) {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("accountId", accountId);
		return (AccountUserVo)appscmBaseDao.findObject("selectCrmAccount", params);
	}
	private PlmUser getPlmUser(Integer userId) {
		SearchExpression se =SearchExpression.forClass(PlmUser.class) ;
		se.and(Terms.eq("userId",userId));
		return (PlmUser)appscmBaseDao.findObject(se);
	}
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public UserRegisterResponse register(UserRegisterRequest request) {
		logger.info("UserRegisterRequest="+JSON.toJSON(request).toString());
		UserRegisterResponse response = new UserRegisterResponse();
		try{
			//参数校验
			CalibratorChain calibratorChain = new CalibratorChain();
			Object[] existParams = new Object[]{
					new String[]{request.getSeq(),"CRM101","随机序列码不能为空"},
					new String[]{request.getVersionNo(),"CRM104","接口版本号不能为空"},
					new String[]{request.getClientType(),"CRM105","客户端类型不能为空"},
					new String[]{request.getAccountId(),"APPS-10001","账户不能为空"},
					new String[]{request.getAccountPassword(),"APPS-10004","账户注册密码不能为空"}};
			calibratorChain.
				addCalibrator(ParamExistCalibrator.instance()).
				addCalibrator(AccountTypeCalibrator.instance()).
				addCalibrator(AppClientCalibrator.instance());
			CalibratorResult calibratorResult= calibratorChain.execute(new Object[]{existParams,request.getAccountType(),request.getClientType()});
			
			if(calibratorResult != null && 
					!CalibratorResult.RESULT_SUCCESS.equalsIgnoreCase(calibratorResult.getCode())){
				response = new UserRegisterResponse(request.getSeq(),request.getVersionNo(),calibratorResult.getCode(),calibratorResult.getMessage());
				logger.info("UserRegisterResponse="+JSON.toJSON(response).toString());
				return response;
			}
			//校验账户是否已经存在
			SearchExpression se =SearchExpression.forClass(PlmLoginAccount.class) ;
			se.and(Terms.eq("accountId",request.getAccountId()));
			PlmLoginAccount account = (PlmLoginAccount)appscmBaseDao.findObject(se);
			if(account != null){
				response = new UserRegisterResponse(request.getSeq(),request.getVersionNo(),"APPS-10003","账户已经存在");
				logger.info("UserRegisterResponse="+JSON.toJSON(response).toString());
				return response;
			}
			//判断密码加密方式MD5 32位
			if(request.getAccountPassword().length() != 32){
				response = new UserRegisterResponse(request.getSeq(),request.getVersionNo(),"APPS-10013","密码MD5加密方式");
				logger.info("UserRegisterResponse="+JSON.toJSON(response).toString());
				return response;
			}
			PlmUserInfo userInfo = new PlmUserInfo(PlmUserInfo.IS_MANAGE_YES);
			//保存用户资料
			appscmBaseDao.insert(userInfo);
			PlmUser user = new PlmUser(request.getAccountPassword(),userInfo.getUserInfoId());
			//保存系统用户资料
			user.setUserInfoId(userInfo.getUserInfoId());
			appscmBaseDao.insert(user);
			//回填关联系统用户ID
			userInfo.setRefUserId(user.getUserId());
			/**
			 * 用户基本资料
			 */
			userInfo.setBirthday(request.getBirthday());
			userInfo.setUserName(request.getUserName());
			userInfo.setSex(request.getSex());
			userInfo.setHeight(request.getHeight());
			userInfo.setHeightUnit(request.getHeightUnit());
			userInfo.setWeight(request.getWeight());
			userInfo.setWeightUnit(request.getWeightUnit());
			appscmBaseDao.update(userInfo);
			//保存账户资料
			account = new PlmLoginAccount(request.getAccountId(),user.getUserId(),request.getAccountType(),new Date());
			account.setIsActivity(PlmLoginAccount.IS_ACTIVITY_YES);
			String activityCode = AppscommTokenManager.getInstance().generateToken(request.getAccountId());
			if(AccountTypeEnum.EMAIL.getType() == request.getAccountType()){
				account.setActivityCode(activityCode);
//				account.setAccountType(PlmLoginAccount.IS_ACTIVITY_NO);
				//调用邮件发送组件,发送激活连接
//				PlmParam deployParam = paramService.getUniquePlmParam(PlmParam.KEY_DEPLOY_URL);
//				String activityUrl = deployParam.getParamValue1() + "?account="+request.getAccountId()+"&activeToken="+activityCode;
				//MailUtil.instance().postMail(new MailInfo(new String[]{request.getAccountId()}, "账户激活", activityUrl));
				/*
				 * 保存联系方式
				 */
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.EMAIL.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}else if(AccountTypeEnum.PHONE.getType() == request.getAccountType()){
				account.setActivityCode(AppscommTokenManager.getInstance().generateSmsCode());
//				account.setAccountType(PlmLoginAccount.IS_ACTIVITY_NO);
				//TODO 调用短信发送组件,发送激活码
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.PHONE.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}else if(AccountTypeEnum.WEIXIN.getType() == request.getAccountType()){
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.WEIXIN.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}else if(AccountTypeEnum.WEIBO.getType() == request.getAccountType()){
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.WEIBO.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}else if(AccountTypeEnum.QQ.getType() == request.getAccountType()){
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.QQ.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}
			account.setUserId(user.getUserId());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			appscmBaseDao.insert(account);
			
			Map<String, Object> userMap = new HashMap<String,Object>();
			userMap.put("userId", user.getUserId());
			userMap.put("userInfoId", user.getUserInfoId());
			response.setUserMap(userMap);
		}catch(AppscommException e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(e.getErrCode());;
			response.setResultMessage(e.getMessage());
		}catch(Exception e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(BaseUserResponse.RESULT_UNKNOWN);
			response.setResultMessage(e.getMessage());
		}
		logger.info("UserRegisterResponse="+JSON.toJSON(response).toString());
		return response;
	}

	@Override
	public BaseUserResponse forgotPassword(UserForgotPasswordRequest request) {
		BaseUserResponse response = new BaseUserResponse(request.getSeq(), request.getVersionNo());
		try{
			//参数校验
			CalibratorChain calibratorChain = new CalibratorChain();
			Object[] existParams = new Object[]{
					new String[]{request.getSeq(),"CRM101","随机序列码不能为空"},
					new String[]{request.getVersionNo(),"CRM104","接口版本号不能为空"},
					new String[]{request.getClientType(),"CRM105","客户端类型不能为空"},
					new String[]{request.getAccountId(),"APPS-10001","账户不能为空"}};
			calibratorChain.
				addCalibrator(ParamExistCalibrator.instance()).
				addCalibrator(AppClientCalibrator.instance());
			CalibratorResult calibratorResult= calibratorChain.execute(new Object[]{existParams,request.getClientType()});
			
			if(calibratorResult != null && 
					!CalibratorResult.RESULT_SUCCESS.equalsIgnoreCase(calibratorResult.getCode())){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),calibratorResult.getCode(),calibratorResult.getMessage());
				logger.info("forgotPassword="+JSON.toJSON(response).toString());
				return response;
			}
			
			//根据密码找回来类型进行处理
			int findType = request.getFindType();
			if(AccountTypeEnum.EMAIL.getType()==findType){
				//邮箱找回
				//TODO
			}else if(AccountTypeEnum.PHONE.getType()==findType){
				//短信找回
				//TODO
			}
			
		}catch(AppscommException e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(e.getErrCode());
			response.setResultMessage(e.getMessage());
		}catch(Exception e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(BaseUserResponse.RESULT_UNKNOWN);
			response.setResultMessage(e.getMessage());
		}
		return response;
	}

	@Override
	public BaseUserResponse modifyPassword(UserModifyPasswordReqeust request) {
		BaseUserResponse response = new BaseUserResponse(request.getSeq(), request.getVersionNo());
		try{
			//参数校验
			CalibratorChain calibratorChain = new CalibratorChain();
			Object[] existParams = new Object[]{
					new String[]{request.getSeq(),"CRM101","随机序列码不能为空"},
					new String[]{request.getVersionNo(),"CRM104","接口版本号不能为空"},
					new String[]{request.getClientType(),"CRM105","客户端类型不能为空"},
					new String[]{request.getAccountId(),"APPS-10001","账户不能为空"}};
			calibratorChain.
				addCalibrator(ParamExistCalibrator.instance()).
				addCalibrator(AppClientCalibrator.instance());
			CalibratorResult calibratorResult= calibratorChain.execute(new Object[]{existParams,request.getClientType()});
			
			if(calibratorResult != null && 
					!CalibratorResult.RESULT_SUCCESS.equalsIgnoreCase(calibratorResult.getCode())){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),calibratorResult.getCode(),calibratorResult.getMessage());
				logger.info("modifyPassword="+JSON.toJSON(response).toString());
				return response;
			}
			
			//根据账号查询账户信息
			AccountUserVo accountUserVo = getPlmAccount(request.getAccountId());
			if(accountUserVo == null){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),"APPS-10006","非法账户");
				logger.info("modifyPassword="+JSON.toJSON(response).toString());
				return response;
			}
			//旧密码是否匹配
			if(!request.getOldPassword().equals(accountUserVo.getAccountPassword())){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),"APPS-10006","非法账户");
				logger.info("modifyPassword="+JSON.toJSON(response).toString());
				return response;
			}
			//判断密码长度是否是MD5 32位
			if(request.getNewPassword().length()!=32){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),"APPS-10013","密码MD5加密方式");
				logger.info("modifyPassword="+JSON.toJSON(response).toString());
				return response;
			}
			PlmUser plmUser = getPlmUser(accountUserVo.getUserId().intValue());
			plmUser.setAccountPassword(request.getNewPassword());
			appscmBaseDao.update(plmUser);
		}catch(AppscommException e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(e.getErrCode());;
			response.setResultMessage(e.getMessage());
		}catch(Exception e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(BaseUserResponse.RESULT_UNKNOWN);
			response.setResultMessage(e.getMessage());
		}
		return response;
	}

	public void setAppscmBaseDao(GuzzBaseDao appscmBaseDao) {
		this.appscmBaseDao = appscmBaseDao;
	}

	public void setRedisOpsTemplate(RedisOpsTemplate redisOpsTemplate) {
		this.redisOpsTemplate = redisOpsTemplate;
	}
}





===
package com.appscomm.common;

import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;


public class AppscommTokenManager {
	private static AppscommTokenManager instance = new AppscommTokenManager();
	private AppscommTokenManager(){
		
	}
	public static synchronized AppscommTokenManager getInstance(){
		if(instance == null){
			instance = new AppscommTokenManager	();
		}
		return instance;
	}
	public String generateToken(String accountId) {
        return DigestUtils.sha256Hex(accountId+System.currentTimeMillis()+new Random().nextInt());
	}
	public String generateSmsCode() {
		StringBuffer smsCode = new StringBuffer();
		Random random = new Random();
		for(int i = 0;i < 6;i++){
			smsCode.append(random.nextInt(9));
		}
		return smsCode.toString();
	}
}


===
package com.appscomm.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.guzz.dao.GuzzBaseDao;
import org.guzz.orm.se.SearchExpression;
import org.guzz.orm.se.Terms;
import org.guzz.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.appscomm.common.redis.support.RedisOpsTemplate;
import com.appscomm.plm.domain.PlmParam;
import com.appscomm.plm.domain.PlmUser;
import com.appscomm.plm.service.ParamService;


public class UserAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private ParamService paramService;
    @Autowired
	private RedisOpsTemplate redisOpsTemplate;
    @Autowired
	private  GuzzBaseDao appscmBaseDao;
    
    private final String IGNORE_AUTHENTICATION_URI = "IGNORE_AUTHENTICATION_URI";
    private final String APPSCOMM_TOKEN = "appscommtoken";
    private final String APPSCOMM_ACCOUNT = "appscommaccountId";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
    	String XRequestedWithHeader = request.getHeader("X-Requested-With");
    	//一部分接口不用进行登录校验
    	List<PlmParam> ignoreUriList = getIgnoreUriConfig();
    	String uri = request.getRequestURI();
    	if(!CollectionUtils.isEmpty(ignoreUriList)){
    		for(PlmParam plmParam : ignoreUriList){
    			if(uri.indexOf(plmParam.getParamValue1())>0){
    	    		return true;
    	    	}
    		}
    	}
    	String appscommtoken = request.getHeader(APPSCOMM_TOKEN);
    	String appscommaccount = request.getHeader(APPSCOMM_ACCOUNT);
    	//未登录的判断
    	if(StringUtil.isEmpty(appscommtoken) || StringUtil.isEmpty(appscommaccount)){
    		if ("XMLHttpRequest".equalsIgnoreCase(XRequestedWithHeader)) { //AJAX请求
        		response.setStatus(601);
            } else {
            	response.sendRedirect(request.getContextPath() + "/WEB-INF/index.html");
            }
        	return false;
    	}
    	
    	
    	//非法token的判断
		String cachetoken = redisOpsTemplate.get(APPSCOMM_TOKEN);
        if(StringUtil.isEmpty(cachetoken)){
        	//缓存中没有对应的token(1、有可能缓存服务器挂掉了,那么从数据库中查找下对应的accountID)
        	SearchExpression se =SearchExpression.forClass(PlmUser.class) ;
    		se.and(Terms.eq("userId",Integer.valueOf(appscommaccount)));
    		PlmUser plmUser = (PlmUser)appscmBaseDao.findObject(se);
    		if(plmUser == null || StringUtil.isEmpty(plmUser.getLoginToken()) ||
    				!plmUser.getLoginToken().equalsIgnoreCase(appscommtoken)){
            	if ("XMLHttpRequest".equalsIgnoreCase(XRequestedWithHeader)) { //AJAX请求
            		response.setStatus(602);
                } else {
                	response.sendRedirect(request.getContextPath() + "/WEB-INF/index.html");
                }
            	return false;
            }else {
            	response.setHeader(APPSCOMM_TOKEN, appscommtoken);
            	response.setHeader(APPSCOMM_ACCOUNT, appscommaccount);
            	return true;
            }
        	
        }else if(!cachetoken.equalsIgnoreCase(appscommtoken)){
        	if ("XMLHttpRequest".equalsIgnoreCase(XRequestedWithHeader)) { //AJAX请求
        		response.setStatus(602);
            } else {
            	response.sendRedirect(request.getContextPath() + "/WEB-INF/index.html");
            }
        	return false;
        }else {
        	response.setHeader(APPSCOMM_TOKEN, appscommtoken);
        	response.setHeader(APPSCOMM_ACCOUNT, appscommaccount);
        	return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    	
    }
    private List<PlmParam> getIgnoreUriConfig(){
    	List<PlmParam> ignoreUriList = new ArrayList<PlmParam>();
    	if(CollectionUtils.isEmpty(ignoreUriList)){
    		ignoreUriList = paramService.getPlmParam(IGNORE_AUTHENTICATION_URI);
    	}
    	return ignoreUriList;
    }
	public void setParamService(ParamService paramService) {
		this.paramService = paramService;
	}
	public void setRedisOpsTemplate(RedisOpsTemplate redisOpsTemplate) {
		this.redisOpsTemplate = redisOpsTemplate;
	}

	public void setAppscmBaseDao(GuzzBaseDao appscmBaseDao) {
		this.appscmBaseDao = appscmBaseDao;
	}
}
==

var hexcase = 0;  
var b64pad  = ""; 
var chrsz   = 8;  
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
function core_md5(x, len)
{

  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);
    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);
  
}

function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}



function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

=======
/**
 * Copyright appscomm 2013. All rights reserved.
 */
package com.appscomm.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;

/**
 * @ClassName:Md5PwdEncoder.java
 * @Description:MD5密码加密
 * @author: wuxiaoxue
 * @date: 2013-11-27
 */
public class Md5PwdEncoder{
	/**
	 * @Description:密码加密
	 * @param rawPass 未加密密码,null作为空串
	 * @param salt 混淆码
	 * @return
	 */
	public static String encodePassword(String rawPass) {
		MessageDigest messageDigest = getMessageDigest();
		byte[] digest;
		try {
			digest = messageDigest.digest(rawPass.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException("UTF-8 not supported!");
		}
		return new String(Hex.encodeHex(digest));
	}

	protected static final MessageDigest getMessageDigest() {
		String algorithm = "MD5";
		try {
			return MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalArgumentException("No such algorithm [" + algorithm + "]");
		}
	}

	public static void main(String[] arg){
		System.out.println(encodePassword("123456"));
	}
}



s
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<context:annotation-config />
	<context:property-placeholder location="classpath:jdbc.properties" />
	<context:component-scan base-package="com.appscomm.sport.action" />
	<context:component-scan base-package="com.appscomm.sport.utils" />
	<context:component-scan base-package="com.appscomm.sport.service.impl" />
	<context:component-scan base-package="com.appscomm.sport.dao.impl" />
	
	<!-- spring中以dataSource方式使用proxool连接池 -->
	<bean name="abstractDataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource" abstract="true">
		<property name="driver" value="com.mysql.jdbc.Driver" />
		<property name="maximumConnectionCount" value="120" />
		<property name="minimumConnectionCount" value="1" />
		<property name="prototypeCount" value="2" />
		<property name="simultaneousBuildThrottle" value="30" />
		<property name="trace" value="${jdbc.trace}" />
	</bean>

	<bean id="mainDataSource" parent="abstractDataSource">
		<property name="driverUrl">
			<value>jdbc:mysql://${jdbc.main.database}?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull</value>
		</property>
        <property name="user" value="${jdbc.main.user}"/>
        <property name="password" value="${jdbc.main.password}"/>
        <property name="alias" value="mainDataSource"/>
        <property name="maximumActiveTime" value="6000000"/>
        <property name="testBeforeUse" value="true"/>
        <property name="houseKeepingTestSql" value="select 1"/>
	</bean>
	<bean id="oldDataSource" parent="abstractDataSource">
		<property name="driverUrl">
			<value>jdbc:mysql://${jdbc.main.old.database}?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull</value>
		</property>
        <property name="user" value="${jdbc.main.user}"/>
        <property name="password" value="${jdbc.main.password}"/>
        <property name="alias" value="oldDataSource"/>
        <property name="maximumActiveTime" value="6000000"/>
        <property name="testBeforeUse" value="true"/>
        <property name="houseKeepingTestSql" value="select 1"/>
	</bean>

	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
		<constructor-arg ref="mainDataSource" />
	</bean>
	<bean id="oldJdbcTemplate" class="com.appscomm.sport.dao.impl.OldJdbcTemplate">
		<constructor-arg ref="oldDataSource" />
	</bean>
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="mainDataSource" />
	</bean>
	<bean id="oldTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="oldDataSource" />
	</bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <tx:annotation-driven transaction-manager="oldTransactionManager"/>
    
    <!-- 配置restful template -->
    <bean id="restTemplate" class="com.appscomm.sport.service.RestTemplate">
    
    </bean>
    
    
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  
	 <property name="messageConverters">   
	          <list>   
	              <bean class = "org.springframework.http.converter.StringHttpMessageConverter">   
	                 <property name = "supportedMediaTypes">
	                       <list>
	                           <value>text/html;charset=UTF-8</value>   
	                      </list>   
	                 </property>   
	              </bean>   
	          </list>   
	    </property>  
	 </bean>
    
</beans>
BaseDao.java
package com.appscomm.sport.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.appscomm.sport.cache.CacheClient;
import com.appscomm.sport.dao.impl.JdbcTemplate;
import com.appscomm.sport.model.BaseModel;

@Service("baseDao")
public class BaseDao extends JdbcTemplate{
	
	@Autowired
	private CacheClient cacheClient;
	
	public <T> List<T> cList(BaseModel<T> model, String sql4Id, Object... args){
		List<Map<String, Object>> list = queryForList(sql4Id, args);
		List<T> result = new ArrayList<T>();
		for(Map<String, Object> map : list){
			T t = cFind(map.get(model.getIdFieldName()), model);
			result.add(t);
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public <T> T cFind(Object idValue, BaseModel<T> model){
		String cacheKey = getCacheKey(model.getModelType(), idValue);
		Object result = cacheClient.getCache(cacheKey);
		if(result!=null){
			return (T)result;
		}
		String sql = "select * from "+model.getTableName()+" where "+model.getIdFieldName()+"=?";
		T t = queryForObject(sql, model.getModelType(), idValue);
		if(t!=null){
			cacheClient.setCache(cacheKey, t);
		}
		return t;
	}
	
	public <T> void cDelete(Object idValue, BaseModel<T> model){

		String sql = "delete from "+model.getTableName()+" where "+model.getIdFieldName()+"=?";
		
		delete(sql, idValue);
		deleteCache(idValue, model);
	}
		
	public <T> void deleteCache(Object idValue, BaseModel<T> model){
		String cacheKey = getCacheKey(model.getModelType(), idValue);
		cacheClient.deleteCache(cacheKey);
	}
	
	private <T> String getCacheKey(Class<T> requiredType, Object idValue){
		String cacheKey = requiredType.getName()+"_"+idValue;
		return cacheKey;
	}
}







=====
package com.appscomm.sport.model;

public interface BaseModel<T> {
	/**
	 * 实体类对应的表名
	 * @return
	 */
	public String getTableName();
	/**
	 * 主键字段名
	 * @return
	 */
	public String getIdFieldName();
	
	/**
	 * 实体类的class
	 * @return
	 */
	public Class<T> getModelType();
}

base jdbc
package com.appscomm.sport.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.appscomm.sport.cache.CacheClient;
import com.appscomm.sport.dao.impl.JdbcTemplate;
import com.appscomm.sport.model.BaseModel;

@Service("baseDao")
public class BaseDao extends JdbcTemplate{
	
	@Autowired
	private CacheClient cacheClient;
	
	public <T> List<T> cList(BaseModel<T> model, String sql4Id, Object... args){
		List<Map<String, Object>> list = queryForList(sql4Id, args);
		List<T> result = new ArrayList<T>();
		for(Map<String, Object> map : list){
			T t = cFind(map.get(model.getIdFieldName()), model);
			result.add(t);
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public <T> T cFind(Object idValue, BaseModel<T> model){
		String cacheKey = getCacheKey(model.getModelType(), idValue);
		Object result = cacheClient.getCache(cacheKey);
		if(result!=null){
			return (T)result;
		}
		String sql = "select * from "+model.getTableName()+" where "+model.getIdFieldName()+"=?";
		T t = queryForObject(sql, model.getModelType(), idValue);
		if(t!=null){
			cacheClient.setCache(cacheKey, t);
		}
		return t;
	}
	
	public <T> void cDelete(Object idValue, BaseModel<T> model){

		String sql = "delete from "+model.getTableName()+" where "+model.getIdFieldName()+"=?";
		
		delete(sql, idValue);
		deleteCache(idValue, model);
	}
		
	public <T> void deleteCache(Object idValue, BaseModel<T> model){
		String cacheKey = getCacheKey(model.getModelType(), idValue);
		cacheClient.deleteCache(cacheKey);
	}
	
	private <T> String getCacheKey(Class<T> requiredType, Object idValue){
		String cacheKey = requiredType.getName()+"_"+idValue;
		return cacheKey;
	}
}
jdbc
/**
 * Copyright appscomm 2013. All rights reserved.
 *
 * @createDate 2013-8-27
 */
package com.appscomm.sport.dao.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

/**
 * Jdbc操作辅助类,对Sping jdbctemplate再封装。
 *
 * @author qindf
 *
 */
@Component
public class JdbcTemplate {
	private ExecutorService executor = Executors.newCachedThreadPool();
	@Resource(name = "jdbcTemplate")
	private NamedParameterJdbcTemplate jdbcTemplate;
	private Object lockObject = new Object();
	private int dbType = 0;
	
	
	/**
	 * 开启新线程批量处理
	 * 
	 * @param sql
	 * @param setter
	 * @return
	 */
	public void batchUpdate(final String sql,
			final BatchPreparedStatementSetter setter) {
		executor.submit(new Callable<int[]>() {
			@Override
			public int[] call() throws Exception {
				synchronized (lockObject) {
					return jdbcTemplate.getJdbcOperations().batchUpdate(sql,
							setter);
				}

			}
		});
	}

	/**
	 * 保存对象
	 * 
	 * @param sql
	 * @param object
	 * @return
	 */
	public int saveObject(String sql, Object object) {
		return jdbcTemplate.update(sql, new BeanPropertySqlParameterSource(
				object));
	}

	public int save(String sql, Map<String, ?> paramMap) {
		return jdbcTemplate.update(sql, paramMap);
	}
	
	/**
	 * 保存对象获取自动生成主键
	 * @param sql
	 * @param object
	 * @return
	 */
	public int saveObjectGetSeq(String sql, Object object){
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(sql, new BeanPropertySqlParameterSource(
				object),keyHolder);
		Number generatedKey = keyHolder.getKey();
		if(generatedKey!=null)
			return generatedKey.intValue();
		else
			return 0;
	}
	
	/**
	 * 保存对象获取自动生成主键 long
	 * @param sql
	 * @param object
	 * @return
	 */
	public long saveObjectGetSeqLong(String sql, Object object){
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(sql, new BeanPropertySqlParameterSource(
				object),keyHolder);
		Number generatedKey = keyHolder.getKey();
		if(generatedKey!=null)
			return generatedKey.longValue();
		else
			return 0;
	}

	/**
	 * 更新对象
	 * 
	 * @param sql
	 * @param object
	 * @return
	 */
	public int updateObject(String sql, Object object) {
		return jdbcTemplate.update(sql, new BeanPropertySqlParameterSource(
				object));
	}

	/**
	 * 更新数据
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public int update(String sql, Object... args) {
		return jdbcTemplate.getJdbcOperations().update(sql, args);
	}

	/**
	 * 删除数据
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public int delete(String sql, Object... args) {
		return jdbcTemplate.getJdbcOperations().update(sql, args);
	}

	/**
	 * 查询对象
	 * 
	 * @param <T>
	 * @param sql
	 * @param requiredType
	 *            查询的对象类型
	 * @param args
	 * @return
	 */
	public <T> T queryForObject(String sql, Class<T> requiredType,
			Object... args) {
		try {
			return jdbcTemplate.getJdbcOperations().queryForObject(sql,
					BeanPropertyRowMapper.newInstance(requiredType), args);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}
	
	/**
	 * 查询对象
	 * 
	 * @param <T>
	 * @param sql
	 * @param requiredType
	 *            查询的对象类型
	 * @param args
	 * @return
	 */
	public <T> List<T> query(String sql, Class<T> requiredType, Object... args) {
		return jdbcTemplate.getJdbcOperations().query(sql,
				BeanPropertyRowMapper.newInstance(requiredType), args);
	}
	
	public <T> List<T> query(String sql, Class<T> requiredType,  Map<String, ?> paramMap) {
		return jdbcTemplate.query(sql,paramMap,
				BeanPropertyRowMapper.newInstance(requiredType));
	}
	
	/**
	 * 查询数据,返回的键值对Map结构
	 * 
	 * @param sql
	 * @param args
	 * @return key为sql查询返回的列名称,value为对应的值。
	 */
	public Map<String, Object> queryForMap(String sql, Object... args) {
		return jdbcTemplate.getJdbcOperations().queryForMap(sql, args);
	}

	/**
	 * 批量查询数据,返回键值对Map结构
	 * 
	 * @param sql
	 * @param args
	 * @return key为sql查询返回的列名称,value为对应的值。
	 */
	public List<Map<String, Object>> queryForList(String sql, Object... args) {
		return jdbcTemplate.getJdbcOperations().queryForList(sql, args);
	}

	/**
	 * 查询整数
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public int queryForInt(String sql, Object... args) {
		return jdbcTemplate.getJdbcOperations().queryForInt(sql, args);
	}

	/**
	 * 查询长整数
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public long queryForLong(String sql, Object... args) {
		return jdbcTemplate.getJdbcOperations().queryForLong(sql, args);
	}

	/**
	 * 转换数据类型
	 * 
	 * @param object
	 * @return
	 */
	public Long toLong(Object object) {
		if (dbType == 1) {
			return ((BigDecimal) object).longValue();
		} else if (dbType == 2) {
			return (Long) object;
		}
		return null;
	}
}
ac2
package com.appscomm.plm.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.guzz.dao.GuzzBaseDao;
import org.guzz.orm.se.SearchExpression;
import org.guzz.orm.se.Terms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.appscomm.common.AccountTypeEnum;
import com.appscomm.common.AppscommException;
import com.appscomm.common.AppscommTokenManager;
import com.appscomm.common.ContactTypeEnum;
import com.appscomm.common.calibrator.AppClientCalibrator;
import com.appscomm.common.calibrator.CalibratorChain;
import com.appscomm.common.calibrator.CalibratorResult;
import com.appscomm.common.calibrator.ParamExistCalibrator;
import com.appscomm.common.redis.support.RedisOpsTemplate;
import com.appscomm.common.utils.BeanCopierUtils;
import com.appscomm.plm.common.calibrator.AccountTypeCalibrator;
import com.appscomm.plm.domain.PlmInterfaceSyn;
import com.appscomm.plm.domain.PlmLoginAccount;
import com.appscomm.plm.domain.PlmUser;
import com.appscomm.plm.domain.PlmUserContact;
import com.appscomm.plm.domain.PlmUserInfo;
import com.appscomm.plm.inout.BaseUserResponse;
import com.appscomm.plm.inout.UserForgotPasswordRequest;
import com.appscomm.plm.inout.UserLoginRequest;
import com.appscomm.plm.inout.UserLoginResponse;
import com.appscomm.plm.inout.UserModifyPasswordReqeust;
import com.appscomm.plm.inout.UserRegisterRequest;
import com.appscomm.plm.inout.UserRegisterResponse;
import com.appscomm.plm.service.AccountService;
import com.appscomm.plm.vo.AccountUserVo;
import com.appscomm.plm.vo.PlmUserInfoVo;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
	@Autowired
	private  GuzzBaseDao appscmBaseDao;
	@Autowired
	private RedisOpsTemplate redisOpsTemplate;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	

	@Override
	public UserLoginResponse login(UserLoginRequest request) {
		logger.info("UserLoginRequest="+JSON.toJSON(request).toString());
		UserLoginResponse response = new UserLoginResponse(request.getSeq(),request.getVersionNo());
		try{
			//参数校验
			CalibratorChain calibratorChain = new CalibratorChain();
			Object[] existParams = new Object[]{
					new String[]{request.getSeq(),"CRM101","随机序列码不能为空"},
					new String[]{request.getVersionNo(),"CRM104","接口版本号不能为空"},
					new String[]{request.getClientType(),"CRM105","客户端类型不能为空"},
					new String[]{request.getAccountId(),"APPS-10001","账户不能为空"},
					new String[]{request.getPassword(),"APPS-10013","密码不能为空"}};
			calibratorChain.
				addCalibrator(ParamExistCalibrator.instance()).
				addCalibrator(AppClientCalibrator.instance());
			CalibratorResult calibratorResult= calibratorChain.execute(new Object[]{existParams,request.getClientType()});
			
			if(calibratorResult != null && 
					!CalibratorResult.RESULT_SUCCESS.equalsIgnoreCase(calibratorResult.getCode())){
				response = new UserLoginResponse(request.getSeq(),request.getVersionNo(),calibratorResult.getCode(),calibratorResult.getMessage());
				logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
				return response;
			}
			AccountUserVo accountUserVo = getPlmAccount(request.getAccountId());
			if(accountUserVo == null){
				response = new UserLoginResponse(request.getSeq(),request.getVersionNo(),"APPS-10006","非法账户");
				logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
				return response;
			}
			//新旧密码是否相等
			if(!request.getPassword().equals(accountUserVo.getAccountPassword())){
				response = new UserLoginResponse(request.getSeq(),request.getVersionNo(),"APPS-10006","非法账户");
				logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
				return response;
			}
			//判断密码加密方式MD5 32位
			if(request.getPassword().length()!=32){
				response = new UserLoginResponse(request.getSeq(),request.getVersionNo(),"APPS-10013","密码MD5加密方式");
				logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
				return response;
			}
			String token = AppscommTokenManager.getInstance().generateToken(request.getAccountId());
			
			
			SearchExpression se =SearchExpression.forClass(PlmUser.class) ;
		    appscmBaseDao.list(se);
		    
		    SearchExpression se2 =SearchExpression.forClass(PlmInterfaceSyn.class) ;
		    appscmBaseDao.list(se2);
			
			PlmUser plmUser = getPlmUser(accountUserVo.getUserId().intValue());
			plmUser.setLoginToken(token);
			appscmBaseDao.update(plmUser);
			response.setToken(token);
			response.setUserId(accountUserVo.getUserId().intValue());
			response.setUserInfoId(accountUserVo.getUserInfoId().intValue());
			//登录返回的附加信息
			Map<String, Object> respMap = new HashMap<String, Object>();
			//用户个人信息
			PlmUserInfoVo userInfo = getUesrInfo(accountUserVo.getUserInfoId());
			//绑定信息
			//目标信息
			//睡眠提醒
			//事项提醒
			//久坐提醒
			//通知开关
			//固件版本号
			respMap.put("userInfo", userInfo);
			response.setUserMap(respMap);
			
		}catch(AppscommException e){
			logger.info(e.getMessage());
			response = new UserLoginResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(e.getErrCode());;
			response.setResultMessage(e.getMessage());
		}catch(Exception e){
			logger.info(e.getMessage());
			response = new UserLoginResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(BaseUserResponse.RESULT_UNKNOWN);
			response.setResultMessage(e.getMessage());
		}
		logger.info("UserLoginResponse="+JSON.toJSON(response).toString());
		return response;
	}

	private PlmUserInfoVo getUesrInfo(Long userInfoId) {
		SearchExpression se =SearchExpression.forClass(PlmUserInfo.class) ;
		se.and(Terms.eq("userInfoId",userInfoId.intValue()));
		PlmUserInfo plmUserInfo = (PlmUserInfo)appscmBaseDao.findObject(se);
		if(plmUserInfo != null){
			PlmUserInfoVo plmUserInfoVo = new PlmUserInfoVo();
			BeanCopierUtils.copyProperty(plmUserInfo, plmUserInfoVo);
			return plmUserInfoVo;
		}
		return null;
	}

	private AccountUserVo getPlmAccount(String accountId) {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("accountId", accountId);
		return (AccountUserVo)appscmBaseDao.findObject("selectCrmAccount", params);
	}
	private PlmUser getPlmUser(Integer userId) {
		SearchExpression se =SearchExpression.forClass(PlmUser.class) ;
		se.and(Terms.eq("userId",userId));
		return (PlmUser)appscmBaseDao.findObject(se);
	}
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public UserRegisterResponse register(UserRegisterRequest request) {
		logger.info("UserRegisterRequest="+JSON.toJSON(request).toString());
		UserRegisterResponse response = new UserRegisterResponse();
		try{
			//参数校验
			CalibratorChain calibratorChain = new CalibratorChain();
			Object[] existParams = new Object[]{
					new String[]{request.getSeq(),"CRM101","随机序列码不能为空"},
					new String[]{request.getVersionNo(),"CRM104","接口版本号不能为空"},
					new String[]{request.getClientType(),"CRM105","客户端类型不能为空"},
					new String[]{request.getAccountId(),"APPS-10001","账户不能为空"},
					new String[]{request.getAccountPassword(),"APPS-10004","账户注册密码不能为空"}};
			calibratorChain.
				addCalibrator(ParamExistCalibrator.instance()).
				addCalibrator(AccountTypeCalibrator.instance()).
				addCalibrator(AppClientCalibrator.instance());
			CalibratorResult calibratorResult= calibratorChain.execute(new Object[]{existParams,request.getAccountType(),request.getClientType()});
			
			if(calibratorResult != null && 
					!CalibratorResult.RESULT_SUCCESS.equalsIgnoreCase(calibratorResult.getCode())){
				response = new UserRegisterResponse(request.getSeq(),request.getVersionNo(),calibratorResult.getCode(),calibratorResult.getMessage());
				logger.info("UserRegisterResponse="+JSON.toJSON(response).toString());
				return response;
			}
			//校验账户是否已经存在
			SearchExpression se =SearchExpression.forClass(PlmLoginAccount.class) ;
			se.and(Terms.eq("accountId",request.getAccountId()));
			PlmLoginAccount account = (PlmLoginAccount)appscmBaseDao.findObject(se);
			if(account != null){
				response = new UserRegisterResponse(request.getSeq(),request.getVersionNo(),"APPS-10003","账户已经存在");
				logger.info("UserRegisterResponse="+JSON.toJSON(response).toString());
				return response;
			}
			//判断密码加密方式MD5 32位
			if(request.getAccountPassword().length() != 32){
				response = new UserRegisterResponse(request.getSeq(),request.getVersionNo(),"APPS-10013","密码MD5加密方式");
				logger.info("UserRegisterResponse="+JSON.toJSON(response).toString());
				return response;
			}
			PlmUserInfo userInfo = new PlmUserInfo(PlmUserInfo.IS_MANAGE_YES);
			//保存用户资料
			appscmBaseDao.insert(userInfo);
			PlmUser user = new PlmUser(request.getAccountPassword(),userInfo.getUserInfoId());
			//保存系统用户资料
			user.setUserInfoId(userInfo.getUserInfoId());
			appscmBaseDao.insert(user);
			//回填关联系统用户ID
			userInfo.setRefUserId(user.getUserId());
			appscmBaseDao.update(userInfo);
			//保存账户资料
			account = new PlmLoginAccount(request.getAccountId(),user.getUserId(),request.getAccountType(),new Date());
			account.setIsActivity(PlmLoginAccount.IS_ACTIVITY_YES);
			String activityCode = AppscommTokenManager.getInstance().generateToken(request.getAccountId());
			if(AccountTypeEnum.EMAIL.getType() == request.getAccountType()){
				account.setActivityCode(activityCode);
//				account.setAccountType(PlmLoginAccount.IS_ACTIVITY_NO);
				//调用邮件发送组件,发送激活连接
//				PlmParam deployParam = paramService.getUniquePlmParam(PlmParam.KEY_DEPLOY_URL);
//				String activityUrl = deployParam.getParamValue1() + "?account="+request.getAccountId()+"&activeToken="+activityCode;
				//MailUtil.instance().postMail(new MailInfo(new String[]{request.getAccountId()}, "账户激活", activityUrl));
				/*
				 * 保存联系方式
				 */
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.EMAIL.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}else if(AccountTypeEnum.PHONE.getType() == request.getAccountType()){
				account.setActivityCode(AppscommTokenManager.getInstance().generateSmsCode());
//				account.setAccountType(PlmLoginAccount.IS_ACTIVITY_NO);
				//TODO 调用短信发送组件,发送激活码
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.PHONE.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}else if(AccountTypeEnum.WEIXIN.getType() == request.getAccountType()){
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.WEIXIN.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}else if(AccountTypeEnum.WEIBO.getType() == request.getAccountType()){
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.WEIBO.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}else if(AccountTypeEnum.QQ.getType() == request.getAccountType()){
				PlmUserContact userContact = new PlmUserContact(userInfo.getUserInfoId(),ContactTypeEnum.QQ.getType(),request.getAccountId());
				appscmBaseDao.insert(userContact);
			}
			account.setUserId(user.getUserId());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			appscmBaseDao.insert(account);
			
			Map<String, Object> userMap = new HashMap<String,Object>();
			userMap.put("userId", user.getUserId());
			userMap.put("userInfoId", user.getUserInfoId());
			response.setUserMap(userMap);
		}catch(AppscommException e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(e.getErrCode());;
			response.setResultMessage(e.getMessage());
		}catch(Exception e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(BaseUserResponse.RESULT_UNKNOWN);
			response.setResultMessage(e.getMessage());
		}
		logger.info("UserRegisterResponse="+JSON.toJSON(response).toString());
		return response;
	}

	@Override
	public BaseUserResponse forgotPassword(UserForgotPasswordRequest request) {
		BaseUserResponse response = new BaseUserResponse(request.getSeq(), request.getVersionNo());
		try{
			//参数校验
			CalibratorChain calibratorChain = new CalibratorChain();
			Object[] existParams = new Object[]{
					new String[]{request.getSeq(),"CRM101","随机序列码不能为空"},
					new String[]{request.getVersionNo(),"CRM104","接口版本号不能为空"},
					new String[]{request.getClientType(),"CRM105","客户端类型不能为空"},
					new String[]{request.getAccountId(),"APPS-10001","账户不能为空"}};
			calibratorChain.
				addCalibrator(ParamExistCalibrator.instance()).
				addCalibrator(AppClientCalibrator.instance());
			CalibratorResult calibratorResult= calibratorChain.execute(new Object[]{existParams,request.getClientType()});
			
			if(calibratorResult != null && 
					!CalibratorResult.RESULT_SUCCESS.equalsIgnoreCase(calibratorResult.getCode())){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),calibratorResult.getCode(),calibratorResult.getMessage());
				logger.info("forgotPassword="+JSON.toJSON(response).toString());
				return response;
			}
			
			//根据密码找回来类型进行处理
			int findType = request.getFindType();
			if(AccountTypeEnum.EMAIL.getType()==findType){
				//邮箱找回
				//TODO
			}else if(AccountTypeEnum.PHONE.getType()==findType){
				//短信找回
				//TODO
			}
			
		}catch(AppscommException e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(e.getErrCode());
			response.setResultMessage(e.getMessage());
		}catch(Exception e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(BaseUserResponse.RESULT_UNKNOWN);
			response.setResultMessage(e.getMessage());
		}
		return response;
	}

	@Override
	public BaseUserResponse modifyPassword(UserModifyPasswordReqeust request) {
		BaseUserResponse response = new BaseUserResponse(request.getSeq(), request.getVersionNo());
		try{
			//参数校验
			CalibratorChain calibratorChain = new CalibratorChain();
			Object[] existParams = new Object[]{
					new String[]{request.getSeq(),"CRM101","随机序列码不能为空"},
					new String[]{request.getVersionNo(),"CRM104","接口版本号不能为空"},
					new String[]{request.getClientType(),"CRM105","客户端类型不能为空"},
					new String[]{request.getAccountId(),"APPS-10001","账户不能为空"}};
			calibratorChain.
				addCalibrator(ParamExistCalibrator.instance()).
				addCalibrator(AppClientCalibrator.instance());
			CalibratorResult calibratorResult= calibratorChain.execute(new Object[]{existParams,request.getClientType()});
			
			if(calibratorResult != null && 
					!CalibratorResult.RESULT_SUCCESS.equalsIgnoreCase(calibratorResult.getCode())){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),calibratorResult.getCode(),calibratorResult.getMessage());
				logger.info("modifyPassword="+JSON.toJSON(response).toString());
				return response;
			}
			
			//根据账号查询账户信息
			AccountUserVo accountUserVo = getPlmAccount(request.getAccountId());
			if(accountUserVo == null){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),"APPS-10006","非法账户");
				logger.info("modifyPassword="+JSON.toJSON(response).toString());
				return response;
			}
			//旧密码是否匹配
			if(!request.getOldPassword().equals(accountUserVo.getAccountPassword())){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),"APPS-10006","非法账户");
				logger.info("modifyPassword="+JSON.toJSON(response).toString());
				return response;
			}
			//判断密码长度是否是MD5 32位
			if(request.getNewPassword().length()!=32){
				response = new BaseUserResponse(request.getSeq(),request.getVersionNo(),"APPS-10013","密码MD5加密方式");
				logger.info("modifyPassword="+JSON.toJSON(response).toString());
				return response;
			}
			PlmUser plmUser = getPlmUser(accountUserVo.getUserId().intValue());
			plmUser.setAccountPassword(request.getNewPassword());
			appscmBaseDao.update(plmUser);
		}catch(AppscommException e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(e.getErrCode());;
			response.setResultMessage(e.getMessage());
		}catch(Exception e){
			logger.info(e.getMessage());
			response = new UserRegisterResponse(request.getSeq(),request.getVersionNo());
			response.setResultCode(BaseUserResponse.RESULT_UNKNOWN);
			response.setResultMessage(e.getMessage());
		}
		return response;
	}

	public void setAppscmBaseDao(GuzzBaseDao appscmBaseDao) {
		this.appscmBaseDao = appscmBaseDao;
	}

	public void setRedisOpsTemplate(RedisOpsTemplate redisOpsTemplate) {
		this.redisOpsTemplate = redisOpsTemplate;
	}
}
acctoutn
package com.appscomm.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.appscomm.common.AppscommException;
import com.appscomm.common.AppscommTokenManager;
import com.appscomm.common.WebContextUtils;
import com.appscomm.plm.inout.BaseUserResponse;
import com.appscomm.plm.inout.UserForgotPasswordRequest;
import com.appscomm.plm.inout.UserLoginRequest;
import com.appscomm.plm.inout.UserLoginResponse;
import com.appscomm.plm.inout.UserModifyPasswordReqeust;
import com.appscomm.plm.inout.UserRegisterRequest;
import com.appscomm.plm.inout.UserRegisterResponse;
import com.appscomm.plm.service.AccountService;
import com.appscomm.plm.vo.JsonResult;

@Controller
@RequestMapping("/platform")
public class AccountController {
	static private ConcurrentMap<String,String> tokenMap = new ConcurrentHashMap<String,String>();
	@Autowired
	private AccountService accountService;
	
	/**
	 * 用户注册
	 * 
	 * @param request - 注册信息
	 * @return - 注册后保存的有效用户userInfoid和系统用户userId
	 */
	@RequestMapping("/account/register.action")
	public @ResponseBody JsonResult register(@RequestBody UserRegisterRequest request) {
		JsonResult result = new JsonResult(true, BaseUserResponse.RESULT_SUCCESS, "OK");
		try {
			UserRegisterResponse response = this.accountService.register(request);
			if (response.getResultCode().equals(BaseUserResponse.RESULT_SUCCESS)) {
				result.setData(response.getUserMap());
			} else {
				result.setSuccess(false);
				result.setErrorCode(response.getResultCode());
				result.setMsg(WebContextUtils.getLocaleMessage(response.getResultCode(), response.getResultMessage()));
			}
		} catch (AppscommException ex) {
			result.setSuccess(false);
			result.failure(ex.getErrCode(),	WebContextUtils.getLocaleMessage(ex.getErrCode(),ex.getMessage()));
		} catch (Exception ex) {
			result.setSuccess(false);
			result.failure("unknown", ex.getMessage());
		}
		return result;
	}
	
	/**
	 * 用户登录
	 * 
	 * @param request - 登陆的用户密码
	 * @return - 返回用户的信息
	 */
	@RequestMapping("/account/login.action")
	public @ResponseBody JsonResult login(@RequestBody UserLoginRequest request) {
		JsonResult result = new JsonResult(true, BaseUserResponse.RESULT_SUCCESS, "OK");
		try {
			UserLoginResponse response = this.accountService.login(request);
			if (response.getResultCode().equals(BaseUserResponse.RESULT_SUCCESS)) {
				result.setData(response);
			} else {
				result.setSuccess(false);
				result.setErrorCode(response.getResultCode());
				result.setMsg(WebContextUtils.getLocaleMessage(response.getResultCode(), response.getResultMessage()));
			}
		} catch (AppscommException ex) {
			result.setSuccess(false);
			result.failure(ex.getErrCode(),	WebContextUtils.getLocaleMessage(ex.getErrCode(),ex.getMessage()));
		} catch (Exception ex) {
			result.setSuccess(false);
			result.failure("unknown", ex.getMessage());
		}
		return result;
	}

	
	/**
	 * 找回密码
	 * 
	 * @return - 找回成功/失败
	 */
	@RequestMapping("/password/forgot.action")
	public @ResponseBody JsonResult forgotPassword(@RequestBody UserForgotPasswordRequest request){
		JsonResult result = new JsonResult(true, BaseUserResponse.RESULT_SUCCESS, "OK");
		try {
			BaseUserResponse response = this.accountService.forgotPassword(request);
			if (response.getResultCode().equals(BaseUserResponse.RESULT_SUCCESS)) {
				result.setData("");
			} else {
				result.setSuccess(false);
				result.setErrorCode(response.getResultCode());
				result.setMsg(WebContextUtils.getLocaleMessage(response.getResultCode(), response.getResultMessage()));
			}
		} catch (AppscommException ex) {
			result.setSuccess(false);
			result.failure(ex.getErrCode(),	WebContextUtils.getLocaleMessage(ex.getErrCode(),ex.getMessage()));
		} catch (Exception ex) {
			result.setSuccess(false);
			result.failure("unknown", ex.getMessage());
		}
		return result;
	}
	
	/**
	 * 修改密码
	 * 
	 * @return - 修改成功/失败
	 */
	@RequestMapping("/password/modify.action")
	public @ResponseBody JsonResult modifyPassword(@RequestBody UserModifyPasswordReqeust request){
		JsonResult result = new JsonResult(true, BaseUserResponse.RESULT_SUCCESS, "OK");
		try {
			BaseUserResponse response = this.accountService.modifyPassword(request);
			if (response.getResultCode().equals(BaseUserResponse.RESULT_SUCCESS)) {
				result.setData("");
			} else {
				result.setSuccess(false);
				result.setErrorCode(response.getResultCode());
				result.setMsg(WebContextUtils.getLocaleMessage(response.getResultCode(), response.getResultMessage()));
			}
		} catch (AppscommException ex) {
			result.setSuccess(false);
			result.failure(ex.getErrCode(),	WebContextUtils.getLocaleMessage(ex.getErrCode(),ex.getMessage()));
		} catch (Exception ex) {
			result.setSuccess(false);
			result.failure("unknown", ex.getMessage());
		}
		return result;
	}
	

	@RequestMapping("/AppscommController/validateToken.action")
	public @ResponseBody JsonResult ValidateToken(
		@RequestParam("token") String token,
		HttpServletRequest request, HttpServletResponse response) throws Exception {
		JsonResult result = new JsonResult(true, "success","OK");
		try {
	        Cookie [] cookies = request.getCookies();
	        if (cookies != null) {
	            for(Cookie cookie : cookies) {
	                if (cookie.getName().equals("appscommaccount")) {//TODO 从缓冲中获取token
	                	String accountId = cookie.getValue();
	                	if(StringUtils.isEmpty(tokenMap.get(accountId))){
	                		//TODO 用户没有登录,找不到对应的token(或者token失效了)
	                	}else if(!token.equals(tokenMap.get(cookie.getValue()))){
	                		//TODO 缓存中的账户token与传进来的token不一致
	                	}else {
	                		//TODO 如果缓存中失败,则去数据库中的值
	            			
	            			//TODO token更新到缓存服务器
	                	}
	                    break;
	                }
	            }
	        }
		} catch (AppscommException ex) {
			result.setSuccess(false);
			result.failure(ex.getErrCode(),ex.getMessage());
		} catch (Exception ex) {
			result.setSuccess(false);
			result.failure("unknown",ex.getMessage());
		}
		return result;
	}
	@RequestMapping("/AppscommController/generateToken.action")
	public @ResponseBody JsonResult generateToken(
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JsonResult result = new JsonResult(true, "success","OK");
		try {
			Cookie [] cookies = request.getCookies();
	        if (cookies != null) {
	            for(Cookie cookie : cookies) {
	                if (cookie.getName().equals("appscommaccount")) {//TODO 从缓冲中获取token
	                	String accountId = cookie.getValue();
	                	if(StringUtils.isEmpty(tokenMap.get(accountId))){
	                		//TODO 用户没有登录
	                	}else {
	                		String token = AppscommTokenManager.getInstance().generateToken(accountId);
	             			tokenMap.put(accountId, token);
	             			//TODO 推送到缓存服务器
	             			List<String> data = new ArrayList<String>();
	             			data.add(token);
	             			result.setData(data);
	                	}
	                    break;
	                }
	            }
	        }
		} catch (AppscommException ex) {
			result.setSuccess(false);
			result.failure(ex.getErrCode(),ex.getMessage());
		} catch (Exception ex) {
			result.setSuccess(false);
			result.failure("unknown",ex.getMessage());
		}
		return result;
	}
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}
}
jquery
var urlCountry = BASE_API_REQUEST+"getCountry.action";
	$.post(urlCountry,{deviceType:"L30."},function(result){
		 result = eval(result.data);
				$.each(result,function(i,data){
					if(0==data.districtId)
						$("#country").append("<option selected value='"+data.districtId+"'>"+data.name+"</option>");
					else
						$("#country").append("<option value='"+data.districtId+"'>"+data.name+"</option>");
				});
	},'json');
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans  
	xmlns="http://www.springframework.org/schema/beans"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-3.1.xsd  
            http://www.springframework.org/schema/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop.xsd" 
    default-lazy-init="true" default-autowire="byName">
    
	<mvc:annotation-driven />
    <!-- <mvc:resources mapping="/view/**" location="/view/"/> -->
     <mvc:resources mapping="/**" location="/WEB-INF/views/"/>
     
	<context:annotation-config />
	<context:component-scan base-package="com.appscomm.controller" />
     <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**.action" />
            <bean class="com.appscomm.controller.UserAuthenticationInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors> 

    <aop:aspectj-autoproxy proxy-target-class="true" />
	<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
	            <value>text/html;charset=utf-8</value>
	            <value>apolication/json; charset=utf-8</value>
	        </list>
		</property>
	</bean>
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">  
	        <list>
	            <ref bean="mappingJacksonHttpMessageConverter"/>
	        </list>
   		</property>
	</bean>
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<ref bean="mappingJacksonHttpMessageConverter" />
		</property>
	</bean>
    	
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   
        <property name="maxUploadSize" value="1024000000"/>   
        <property name="resolveLazily" value="true"/>   
        <property name="maxInMemorySize" value="4096"/>   
    </bean>  
	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
	
	<bean id="freemarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="templateLoaderPaths" value="WEB-INF/" />
		<property name="defaultEncoding" value="utf-8" />
		<property name="freemarkerSettings">
			<props>
				<prop key="tag_syntax">auto_detect</prop>
				<prop key="template_update_delay">5</prop>
				<prop key="defaultEncoding">UTF-8</prop>
				<prop key="url_escaping_charset">UTF-8</prop>
				<prop key="locale">zh_CN</prop>
				<prop key="boolean_format">true,false</prop>
				<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
				<prop key="date_format">yyyy-MM-dd</prop>
				<prop key="time_format">HH:mm:ss</prop>
				<prop key="number_format">0.######</prop>
				<prop key="whitespace_stripping">true</prop>
				<prop key="auto_import">ftl/spring.ftl as spring</prop>
			</props>
		</property>
	</bean>
	<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
		<property name="prefix" value="/views/"/>
		<property name="suffix" value=".html" />
		<property name="contentType" value="text/html;charset=utf-8" />
		<property name="exposeRequestAttributes" value="true" />
		<property name="exposeSessionAttributes" value="true" />
		<property name="exposeSpringMacroHelpers" value="true" />
		<property name="requestContextAttribute" value="request"/>
	</bean>
	
	<bean id="messageSource"
		 class="org.springframework.context.support.ResourceBundleMessageSource" >
		 <property name="basenames">
			<list>
				<value>L30/i18n/message</value>
				<value>L30/i18n/global/country</value>
				<value>L30/i18n/validate/messages</value>
				<value>L30/config</value>
				
				<value>L31/i18n/message</value>
				<value>L31/i18n/global/country</value>
				<value>L31/i18n/validate/messages</value>
				<value>L31/config</value>
			</list>
		</property>
		 <property name="useCodeAsDefaultMessage" value="true"/>
	</bean>
	
	<bean id="localeResolver"  class="org.springframework.web.servlet.i18n.SessionLocaleResolver">  
    </bean> 
	<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> 
	
</beans>
Global site tag (gtag.js) - Google Analytics