前端时间做网站,客户对用户帐户安全要求比较高,要求账户登录需要有短信提醒,下面是实现的一些核心代码分享给大家:
这里面用到的短信接口,是第三方短信接口服务商—动力思维乐信,如果对调用接口不太了解的可以,到他们的网站(www.lx598.com )看下API文档和demo。
主要代码如下:
1.action:
/**
* 登录
*
* @return
*/
@Action(value = "login")
public void login() {
PrintWriter out;
String result = "0";
try{
boolean bCaptcha=validCaptcha();
if(bCaptcha){
dailiUser.setFloginpwd(MD5.getMd5String(dailiUser.getFloginpwd()).toUpperCase());
DailiUserLogin getUser = sysService.login(dailiUser);
if (null != getUser) {
System.out.println("=======登录成功");
request.getSession().setAttribute(ConstValues.WEB_SESSION_DAILI_KEY,getUser);
result = "0";
// 这里执行短信发送
String content = "欢迎" + getUser.getACCMOB()+"登陆【短信签名】";//getUser.getACCMOB() 用户名为电话号
SendSmsReply sendSmsReply = smsUnit.sendSms(accName,accPwd ,getUser.getACCMOB(),content,"");
//调用第三方接口发送短信
}else{
result = "1";
}
}else{
result = "2";
}
}catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
out = response.getWriter();
out.write(result);
} catch (IOException e) {
e.printStackTrace();
logger.warn("", e);
}
}
}
2.service:
public DailiUserLogin login(DailiUser user) {
if (user == null || user.getFloginname() == null
| user.getFloginpwd() == null)
return null;
DailiUserLogin dailiUserLogin=dailiUserMapper.selectByNameAndPwd(user);
dailiUserLogin.setCacheId(HashUtil.getRandomUUID());
memCachedClient.set(dailiUserLogin.getCacheId(), dailiUserLogin,8*60*60*1000);
return dailiUserLogin;
//return null;
}
3.第三方短信发送平台:
/**
* 发送短信
* @param accName 乐信账号用户名
* @param accPwd 乐信账号密码
* @param seed 当前时间 格式:YYYYMMDD HHMISS 例如:20130806102030
* @param aimcodes 手机号多个手机号之间英文半角逗号隔开
* @param content 内容后加签名
* @param schTime 定时时间格式如:2010-01-01 08:00:00
* @return 服务端返回的结果 ok:业务id 或者 错误代码
*/
public static String sendSms(String accName,String accPwd,String mobies,String content,String schTime){
StringBuffer sb = new StringBuffer("http://sdk.lx198.com/sdk/send2?");
try {
String seed=new SimpleDateFormat(dateFormatStr).format(new Date());
sb.append("&accName="+accName);
sb.append("&seed="+seed);
sb.append("&accPwd="+MD5.getMd5String(MD5.getMd5String(accPwd)+seed));
sb.append("&aimcodes="+mobies);
sb.append("&schTime="+URLEncoder.encode(schTime,"UTF-8")); //空格标点符号做encode转换
sb.append("&content="+URLEncoder.encode(content,"UTF-8")); //中文做encode转换
URL url = new URL(sb.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
return in.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}