近來由于項目需要,需要用到手機短信驗證碼的功能,其中最主要的是用到了第三方提供的短信平台接口WebService用戶端接口,下面我把我在項目中用到的記錄一下,以便給大家提供個思路,由于本人的文采有限,還請大家見諒!
一:首先上幾張案例截圖,以便大家可以了解一下短信驗證碼的流程,這裡我在做的過程中也參考了很多網站的短信驗證碼,比如:58同城,汽車之家等。
1.點選擷取驗證碼之前的樣式:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiQ3chVEa0V3bT9CX5RXa2Fmcn9CXwczLcVmds92czlGZvwVP9EUTDZ0aRJkSwk0LcxGbpZ2LcBDM08CXlpXazRnbvZ2LcRlMMVDT2EWNvwFdu9mZvwVP4cFZuVzVhRTOXl1bwhEZrh2MjZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DOxcjNzETM1ETNyYDM0EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
2.輸入正确的手機号後點選擷取驗證碼之後的樣式:
3.如果手機号已經被注冊的樣式:
4.如果一個手機号一天發送超過3次就提示不能發送:
二:前台的注冊頁面的代碼:reg.jsp
[html] view plain copy
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@taglib prefix="s" uri="/struts-tags"%>
- <%@page import="cn.gov.csrc.base.action.FindAllData"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://"
- + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>中國證券會證券期貨違法違規舉報中心-注冊</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <link rel="shortcut icon" type="image/x-icon" href="<%=request.getContextPath()%>/images/favicon.ico" />
- <link rel="stylesheet" type="text/css"
- href="<%=request.getContextPath()%>/css/main.css">
- <link
- href="<%=request.getContextPath()%>/formValidator1/style/validator.css"
- rel="stylesheet" type="text/css" />
- <style type="text/css">
- button {
- background: #F0F0F0 repeat-x;
- padding-top: 3px;
- border-top : 1px solid #708090;
- border-right: 1px solid #708090;
- border-bottom: 1px solid #708090;
- border-left: 1px solid #708090;
- width: auto;
- line-height: 12pt;
- font-size : 10pt;
- cursor: hand;
- font-size: 10pt;
- border-top: 1px solid #708090;
- }
- </style>
- <script src="<%=request.getContextPath()%>/js/jquery-1.7.2.min.js"
- type="text/javascript"></script>
- <script src="<%=request.getContextPath()%>/formValidator1/formValidator-4.0.1.js"
- type="text/javascript"></script>
- <script src="<%=request.getContextPath()%>/formValidator1/formValidatorRegex.js"
- type="text/javascript"></script>
- <script src="<%=request.getContextPath()%>/js/register.js"
- type="text/javascript"></script>
- <script src="<%=request.getContextPath()%>/js/sms.js"
- type="text/javascript"></script>
- <script type="text/javascript">
- function changeCheckNum() {
- var checkNumImage_ = document.getElementById("checkNumImage");
- checkNumImage_.src = "${pageContext.request.contextPath}/image.jsp?timeStamp="+ new Date().getTime();
- }
- </script>
- <script type="text/javascript">
- var msg = "${message}";
- if (msg != "") {
- alert(msg);
- }
- </script>
- </head>
- <body>
- <%@include file="/statics/top.jspf"%>
- <div class="center_division">
- <div class="center_body">
- <div class="center_menu">
- <font color="#000000">目前位置:</font>
- <a href="<%=request.getContextPath()%>/statics/reg.jsp"><font color="#000000">使用者注冊</font></a>
- </div>
- </div>
- <div class="center_body_menu">
- <s:form action="RegisterAction_register" id="form1" name="form1" method="post" namespace="/">
- <table id="tb">
- <tr>
- <td colspan="3" align="center" bgcolor="#DDDFE1">舉報人基本資訊</td>
- </tr>
- <tr>
- <td align="center" width="30%"> <img src="images/new_reg_xing.gif"/>使用者名:</td>
- <td align="center" width="40%">
- <s:textfield name="username" id="username" cssStyle="width:160px;height:24px;" onblur="checkusername()"/>
- </td>
- <td align="left" width="30%">
- <span id="usernameTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>username</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>登入密碼:</td>
- <td align="center" width="40%">
- <s:password name="password" id="password" cssStyle="width:160px;height:24px;" onblur="checkpassword()"/>
- </td>
- <td align="left" width="30%">
- <span id="passwordTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>password</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>确認密碼:</td>
- <td align="center" width="40%">
- <s:password name="passwordRepeat" id="passwordRepeat" cssStyle="width:160px;height:24px;" onblur="checkpasswrodb()"/>
- </td>
- <td align="left" width="30%">
- <span id="passwordRepeatTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>passwordRepeat</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>姓 名:</td>
- <td align="center" width="40%">
- <s:textfield name="nickname" id="nickname" cssStyle="width:160px;height:24px;" onblur="checknickname()"/>
- </td>
- <td align="left" width="30%">
- <span id="nicknameTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>nickname</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%">性 别:</td>
- <td align="center" width="40%">
- <s:radio list="#application.dataMap.get('10001')" name="jbSex" cssStyle="height:24px;"/>
- </td>
- <td align="left" width="30%"></td>
- </tr>
- <tr>
- <td align="center" width="30%">聯系位址:</td>
- <td align="center" width="40%">
- <s:textfield name="jbAddress" id="jbAddress" cssStyle="width:160px;height:24px;" />
- </td>
- <td align="left" width="30%">
- <span id="jbAddressTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>jbAddress</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>聯系手機:</td>
- <td align="center" width="40%">
- <s:textfield id="jbPhone" name="jbPhone" cssStyle="width:160px;height:24px;" onblur="checkjbPhone()"/>
- </td>
- <td align="left" width="30%">
- <span id="jbPhoneTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>jbPhone</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center"><img src="images/new_reg_xing.gif"/>短信驗證碼:</td>
- <td align="left" colspan="2" style="padding-left: 112px;">
- <s:textfield id="SmsCheckCode" name="SmsCheckCode" cssStyle="width:80px;height:24px;" maxLength="6" />
- <span><input type="button" id="btnSendCode" name="btnSendCode" value="免費擷取驗證碼" onclick="sendMessage()" /></span>
- <span id="SmsCheckCodeTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>SmsCheckCodeTip</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>證件類型:</td>
- <td align="center" width="40%">
- <s:select list="#application.dataMap.get('10002')" label=""
- headerKey="" headerValue="--請選擇--" value="1" listValue="value" onchange="enableCredentialsCode(this)"
- name="jbCredentialsName" id="jbCredentialsName" cssStyle="width:160px;height:24px;"/>
- </td>
- <td align="left" width="30%">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>jbCredentialsName</s:param>
- </s:fielderror>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>證件号碼:</td>
- <td align="center" width="40%">
- <s:textfield name="jbCredentialsCode" id="jbCredentialsCode" cssStyle="width:160px;height:24px;" onblur="checkjbCredentialsCode()"/>
- </td>
- <td align="left" width="30%">
- <span id="jbCredentialsCodeTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>jbCredentialsCode</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%">機關名稱:</td>
- <td align="center" width="40%">
- <s:textfield name="jbCompanyName" id="jbCompanyName" cssStyle="width:160px;height:24px;" />
- </td>
- <td align="left" width="30%">
- <span id="jbCompanyNameTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>jbCompanyName</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%"><img src="images/new_reg_xing.gif"/>所在地區:</td>
- <td align="center" width="40%">
- <s:select list="#application.dataMap.get('10003')" label=""
- headerKey="" headerValue="--請選擇--" listKey="key"
- cssStyle="width:160px;height:24px;" listValue="value" id="jbSourceArea"
- name="jbSourceArea" onblur="checkjbSourceArea()"/>
- </td>
- <td align="left" width="30%">
- <span id="jbSourceAreaTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>jbSourceArea</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td align="center" width="30%"> <img src="images/new_reg_xing.gif"/>驗證碼:</td>
- <td align="center" width="40%">
- <s:textfield id="checkNum" name="checkNum" cssStyle="width:60px;height:24px;" onblur="checkNumber()" maxLength="4"/>
- <img id="checkNumImage" src="${pageContext.request.contextPath}/image.jsp">
- <a onClick="changeCheckNum()" title="點選換一張" style="cursor:hand;"> 換一張</a>
- </td>
- <td align="left" width="30%">
- <span id="checkNumTip">
- <s:fielderror cssStyle="color:red;padding-left:10px;">
- <s:param>checkNumTip</s:param>
- </s:fielderror>
- </span>
- </td>
- </tr>
- <tr>
- <td colspan="3" style="vertical-align: top; padding-top: 5px;padding-bottom: 5px;">
- <input type="submit" value="注冊" style="width:50px; height:24px;"/>
- <input type="reset" value="重置" style="width:50px; height:24px;"/>
- </td>
- </tr>
- </table>
- </s:form>
- </div>
- </div>
- <%@include file="/common/buttom.jspf"%>
- </body>
- </html>
三:前台擷取短信驗證碼的js:sms.js
[javascript] view plain copy
- var InterValObj; //timer變量,控制時間
- var count = 120; //間隔函數,1秒執行
- var curCount;//目前剩餘秒數
- var code = ""; //驗證碼
- var codeLength = 6;//驗證碼長度
- function sendMessage() {
- curCount = count;
- var jbPhone = $("#jbPhone").val();
- var jbPhoneTip = $("#jbPhoneTip").text();
- if (jbPhone != "") {
- if(jbPhoneTip == "√ 該手機号碼可以注冊,輸入正确" || jbPhoneTip == "√ 短信驗證碼已發到您的手機,請查收"){
- // 産生驗證碼
- for ( var i = 0; i < codeLength; i++) {
- code += parseInt(Math.random() * 9).toString();
- }
- // 設定button效果,開始計時
- $("#btnSendCode").attr("disabled", "true");
- $("#btnSendCode").val("請在" + curCount + "秒内輸入驗證碼");
- InterValObj = window.setInterval(SetRemainTime, 1000); // 啟動計時器,1秒執行一次
- // 向背景發送處理資料
- $.ajax({
- type: "POST", // 用POST方式傳輸
- dataType: "text", // 資料格式:JSON
- url: "UserAction_sms.action", // 目标位址
- data: "jbPhone=" + jbPhone +"&code=" + code,
- error: function (XMLHttpRequest, textStatus, errorThrown) {
- },
- success: function (data){
- data = parseInt(data, 10);
- if(data == 1){
- $("#jbPhoneTip").html("<font color='#339933'>√ 短信驗證碼已發到您的手機,請查收</font>");
- }else if(data == 0){
- $("#jbPhoneTip").html("<font color='red'>× 短信驗證碼發送失敗,請重新發送</font>");
- }else if(data == 2){
- $("#jbPhoneTip").html("<font color='red'>× 該手機号碼今天發送驗證碼過多</font>");
- }
- }
- });
- }
- }else{
- $("#jbPhoneTip").html("<font color='red'>× 手機号碼不能為空</font>");
- }
- }
- //timer處理函數
- function SetRemainTime() {
- if (curCount == 0) {
- window.clearInterval(InterValObj);// 停止計時器
- $("#btnSendCode").removeAttr("disabled");// 啟用按鈕
- $("#btnSendCode").val("重新發送驗證碼");
- code = ""; // 清除驗證碼。如果不清除,過時間後,輸入收到的驗證碼依然有效
- }else {
- curCount--;
- $("#btnSendCode").val("請在" + curCount + "秒内輸入驗證碼");
- }
- }
- $(document).ready(function() {
- $("#SmsCheckCode").blur(function() {
- var SmsCheckCodeVal = $("#SmsCheckCode").val();
- // 向背景發送處理資料
- $.ajax({
- url : "UserAction_checkCode.action",
- data : {SmsCheckCode : SmsCheckCodeVal},
- type : "POST",
- dataType : "text",
- success : function(data) {
- data = parseInt(data, 10);
- if (data == 1) {
- $("#SmsCheckCodeTip").html("<font color='#339933'>√ 短信驗證碼正确,請繼續</font>");
- } else {
- $("#SmsCheckCodeTip").html("<font color='red'>× 短信驗證碼有誤,請核實後重新填寫</font>");
- }
- }
- });
- });
- });
四:驗證碼使用者名和手機号碼的js:register.js
[javascript] view plain copy
- //去掉前後空格
- function trim(str) {
- var strnew = str.replace(/^\s*|\s*$/g, "");
- return strnew;
- }
- //使用者名
- function checkusername() {
- var username = document.form1.username.value;
- if (username == "" || !isNaN(username.charAt(0))) {
- document.getElementById("usernameTip").innerHTML = "<font color='red'>× 首字母不能為數字或者使用者名不能為空</font>";
- return false;
- } else if (username.length < 6 || username.length > 30) {
- document.getElementById("usernameTip").innerHTML = "<font color='red'>× 使用者名長度為6-30位字元</font>";
- return false;
- } else {
- document.getElementById("usernameTip").innerHTML = "<font color='#339933'>√ 使用者名合格</font>";
- // 向背景發送處理資料
- $.ajax({
- url : "UserAction_checkUserName.action",// 目标位址
- data : {username : username}, // 目标參數
- type : "POST", // 用POST方式傳輸
- dataType : "text", // 資料格式:text
- success : function(data) {
- data = parseInt(data, 10);
- if (data != 0) {
- $("#usernameTip").html("<font color='red'>× 該使用者名已經被注冊,請重新輸入</font>");
- } else {
- $("#usernameTip").html("<font color='#339933'>√ 該使用者名可以注冊,輸入正确</font>");
- }
- }
- });
- return true;
- }
- }
- // 登入密碼
- function checkpassword() {
- var password = document.form1.password.value;
- if (password.length < 6 || password.length > 30) {
- document.getElementById("passwordTip").innerHTML = "<font color='red'>× 密碼長度不能小于6位,大于30位</font>";
- return false;
- } else if (!isNaN(password)) {
- document.getElementById("passwordTip").innerHTML = "<font color='red'>× 密碼不能全是數字</font>";
- return false;
- } else {
- document.getElementById("passwordTip").innerHTML = "<font color='#339933'>√ 密碼合格</font>";
- return true;
- }
- }
- // 确認密碼
- function checkpasswrodb() {
- var password = document.form1.password.value;
- var passwordRepeat = document.form1.passwordRepeat.value;
- if (trim(password) != trim(passwordRepeat)) {
- document.getElementById("passwordRepeatTip").innerHTML = "<font color='red'>× 兩次密碼輸入必須一緻</font>";
- return false;
- } else {
- document.getElementById("passwordRepeatTip").innerHTML = "<font color='#339933'>√ 密碼輸入一緻</font>";
- return true;
- }
- }
- // 姓名
- function checknickname() {
- var nickname = document.form1.nickname.value;
- if (trim(nickname) == "") {
- document.getElementById("nicknameTip").innerHTML = "<font color='red'>× 姓名不能為空</font>";
- return false;
- } else {
- document.getElementById("nicknameTip").innerHTML = "<font color='#339933'>√ 姓名輸入正确</font>";
- return true;
- }
- }
- // 聯系手機(ajax驗證手機号碼是否已經存在)
- function checkjbPhone() {
- var jbPhone = document.form1.jbPhone.value;
- var re= /(^1[3|5|8][0-9]{9}$)/;
- if (trim(jbPhone) == "") {
- document.getElementById("jbPhoneTip").innerHTML = "<font color='red'>× 手機号碼不能為空</font>";
- return false;
- } else if(trim(jbPhone) != ""){
- if(!re.test(jbPhone)){
- document.getElementById("jbPhoneTip").innerHTML = "<font color='red'>× 請輸入有效的手機号碼</font>";
- return false;
- }else{
- document.getElementById("jbPhoneTip").innerHTML = "<font color='#339933'>√ 手機号碼輸入正确</font>";
- // 向背景發送處理資料
- $.ajax({
- url : "UserAction_checkPhone.action",// 目标位址
- data : {jbPhone : jbPhone}, // 目标參數
- type : "POST", // 用POST方式傳輸
- dataType : "text", // 資料格式:text
- success : function(data) {
- data = parseInt(data, 10);
- if (data != 0) {
- $("#jbPhoneTip").html("<font color='red'>× 該手機号碼已經被注冊,請重新輸入</font>");
- } else {
- $("#jbPhoneTip").html("<font color='#339933'>√ 該手機号碼可以注冊,輸入正确</font>");
- }
- }
- });
- return true;
- }
- }
- }
- // 證件号碼
- function checkjbCredentialsCode() {
- var jbCredentialsCode = document.form1.jbCredentialsCode.value;
- var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
- if (trim(jbCredentialsCode) == "") {
- document.getElementById("jbCredentialsCodeTip").innerHTML = "<font color='red'>× 證件号碼不能為空</font>";
- return false;
- } else if(trim(jbCredentialsCode) != ""){
- if(!reg.test(jbCredentialsCode)){
- document.getElementById("jbCredentialsCodeTip").innerHTML = "<font color='red'>× 請輸入合法的證件号碼</font>";
- return false;
- }else{
- document.getElementById("jbCredentialsCodeTip").innerHTML = "<font color='#339933'>√ 證件号碼輸入正确</font>";
- // 向背景發送處理資料
- $.ajax({
- url : "UserAction_checkCredentialsCode.action",// 目标位址
- data : {jbCredentialsCode : jbCredentialsCode}, // 目标參數
- type : "POST", // 用POST方式傳輸
- dataType : "text", // 資料格式:text
- success : function(data) {
- data = parseInt(data, 10);
- if (data != 0) {
- $("#jbCredentialsCodeTip").html("<font color='red'>× 該證件号碼已經被注冊,請重新輸入</font>");
- } else {
- $("#jbCredentialsCodeTip").html("<font color='#339933'>√ 該證件号碼可以注冊,輸入正确</font>");
- }
- }
- });
- return true;
- }
- }
- }
- // 所在地區
- function checkjbSourceArea() {
- var jbSourceArea = document.form1.jbSourceArea.value;
- if (trim(jbSourceArea) == "") {
- document.getElementById("jbSourceAreaTip").innerHTML = "<font color='red'>× 請選擇所在地區</font>";
- return false;
- } else {
- document.getElementById("jbSourceAreaTip").innerHTML = "<font color='#339933'>√ 所在地區選擇正确</font>";
- return true;
- }
- }
- // 驗證碼
- function checkNumber() {
- var checkNum = document.form1.checkNum.value;
- if (trim(checkNum) == "") {
- document.getElementById("checkNumTip").innerHTML = "<font color='red'>× 驗證碼不能為空</font>";
- return false;
- } else {
- document.getElementById("checkNumTip").innerHTML = "<font color='#339933'>√ 驗證碼合格</font>";
- // 向背景發送處理資料
- $.ajax({
- url : "UserAction_checkNum.action",// 目标位址
- data : {checkNum : checkNum}, // 目标參數
- type : "POST", // 用POST方式傳輸
- dataType : "text", // 資料格式:text
- success : function(data) {
- data = parseInt(data, 10);
- if (data != 0) {
- $("#checkNumTip").html("<font color='red'>× 驗證碼錯誤</font>");
- } else {
- $("#checkNumTip").html("<font color='#339933'>√ 驗證碼正确</font>");
- }
- }
- });
- return true;
- }
- }
五:背景action的代碼:UserAction.java(這裡隻是調用了我們的第三方給提供的用戶端代碼的發送短信的方法,如果是調用其他的短信平台,可以換成他們的發送短信的方法,這裡隻是給大家做個參考)
[java] view plain copy
- package cn.gov.csrc.base.systemmanager.action;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.List;
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.log4j.Logger;
- import org.apache.struts2.convention.annotation.Action;
- import org.apache.struts2.convention.annotation.Result;
- import org.apache.struts2.convention.annotation.Results;
- import org.springframework.context.annotation.Scope;
- import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.stereotype.Controller;
- import cn.gov.csrc.base.action.BaseAction;
- import cn.gov.csrc.base.log.service.LogService;
- import cn.gov.csrc.base.report.util.CommonUtil;
- import cn.gov.csrc.base.report.util.Env;
- import cn.gov.csrc.base.systemmanager.model.Count;
- import cn.gov.csrc.base.systemmanager.model.User;
- import cn.gov.csrc.base.systemmanager.service.CountService;
- import cn.gov.csrc.base.systemmanager.service.UserService;
- import cn.gov.csrc.base.util.WebContextUtil;
- import com.sms.webservice.client.SmsReturnObj;
- import com.sms.webservice.client.SmsWebClient;
- @Controller()
- @Scope("prototype")
- @Results({
- @Result(name = "success", location = "/statics/report.jsp"),
- @Result(name = "modifyPassword", location = "/statics/modifyPassword.jsp")
- })
- public class UserAction extends BaseAction<User> {
- private static final long serialVersionUID = 1214696686677691191L;
- private static Logger log = Logger.getLogger(UserAction.class);
- private static final String url = Env.getInstance().getProperty("url");
- private static final String userName = Env.getInstance().getProperty(
- "username");
- private static final String passWord = Env.getInstance().getProperty(
- "password");
- private Integer id;
- private String username;// 使用者名
- private String password;// 密碼
- private String passwordRepeat;// 确認密碼
- private String jbPhone;//手機号碼
- private String jbCredentialsCode;//身份證号碼
- private String checkNum;//圖檔驗證碼
- private String newPassword;
- private String confirmPassword;
- private Integer[] ownRoleIds;
- private UserService userService;
- private CountService countService;
- private LogService logService;
- private Count count = new Count();
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getPasswordRepeat() {
- return passwordRepeat;
- }
- public void setPasswordRepeat(String passwordRepeat) {
- this.passwordRepeat = passwordRepeat;
- }
- public String getJbPhone() {
- return jbPhone;
- }
- public void setJbPhone(String jbPhone) {
- this.jbPhone = jbPhone;
- }
- public String getJbCredentialsCode() {
- return jbCredentialsCode;
- }
- public void setJbCredentialsCode(String jbCredentialsCode) {
- this.jbCredentialsCode = jbCredentialsCode;
- }
- public String getCheckNum() {
- return checkNum;
- }
- public void setCheckNum(String checkNum) {
- this.checkNum = checkNum;
- }
- public Integer[] getOwnRoleIds() {
- return ownRoleIds;
- }
- public void setOwnRoleIds(Integer[] ownRoleIds) {
- this.ownRoleIds = ownRoleIds;
- }
- public String getNewPassword() {
- return newPassword;
- }
- public void setNewPassword(String newPassword) {
- this.newPassword = newPassword;
- }
- public String getConfirmPassword() {
- return confirmPassword;
- }
- public void setConfirmPassword(String confirmPassword) {
- this.confirmPassword = confirmPassword;
- }
- @Resource
- public void setUserService(UserService userService) {
- this.userService = userService;
- }
- public UserService getUserService() {
- return userService;
- }
- @Resource
- public void setCountService(CountService countService) {
- this.countService = countService;
- }
- public CountService getCountService() {
- return countService;
- }
- public LogService getLogService() {
- return logService;
- }
- @Resource
- public void setLogService(LogService logService) {
- this.logService = logService;
- }
- public Count getCount() {
- return count;
- }
- public void setCount(Count count) {
- this.count = count;
- }
- public void prepareToUpdatePage() {
- model = userService.getEntity(id);
- }
- @Action(value = "UserAction_login")
- public String login() {
- Object u = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- if (u instanceof User && u != null) {
- WebContextUtil.getSession().setAttribute("user", u);
- User user = (User)u;
- //使用資料庫表TBL_BASE_LOG添加使用者登入的日志資訊
- logService.saveTblBaseLog(WebContextUtil.getRequest(),"目前操作人【"+user.getNickname()+"】登入系統");
- } else {
- // 防止繞過登陸頁面直接執行Action
- return "login";
- }
- return SUCCESS;
- }
- @Action(value = "UserAction_updateUser")
- public String updateUser() {
- if (!newPassword.equals(confirmPassword)) {
- this.setMessage("新密碼與确認密碼不一緻!");
- return "modifyPassword";
- }
- User u = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("md5");
- String psw = encoder.encodePassword(newPassword, null);
- userService.modifyPassword(u, psw);
- this.setMessage("儲存成功!");
- return "modifyPassword";
- }
- @Action(value = "UserAction_checkUserName")
- public void checkUserName(){
- String result = "0";
- try {
- List<User> list = userService.findUserByUserName(username);
- if(list != null && list.size() > 0){
- result = "1";
- }else{
- result = "0";
- }
- HttpServletResponse response = WebContextUtil.getResponse();
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- PrintWriter out = response.getWriter();
- out.write(result.toString());
- } catch (IOException e) {
- throw new RuntimeException("驗證身份證号碼出錯", e);
- }
- }
- @Action(value = "UserAction_checkPassWord")
- public void checkPassWord() throws Exception {
- String result = "0";
- MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("md5");
- String pwd = encoder.encodePassword(password, null);
- List<User> user = userService.findUserByPassWord(pwd);
- if (user != null && user.size() > 0) {
- result = "1";
- }else{
- result = "0";
- }
- HttpServletResponse response = WebContextUtil.getResponse();
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- PrintWriter out = response.getWriter();
- out.write(result.toString());
- }
- @Action(value = "UserAction_checkPhone")
- public void checkPhone(){
- String result = "0";
- try {
- List<User> list = userService.findUserByPhone(jbPhone);
- if(list != null && list.size() > 0){
- result = "1";
- }else{
- result = "0";
- }
- HttpServletResponse response = WebContextUtil.getResponse();
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- PrintWriter out = response.getWriter();
- out.write(result.toString());
- } catch (IOException e) {
- throw new RuntimeException("驗證手機号碼出錯", e);
- }
- }
- @Action(value = "UserAction_checkCredentialsCode")
- public void checkCredentialsCode(){
- String result = "0";
- try {
- List<User> list = userService.findUserByCredentialsCode(jbCredentialsCode);
- if(list != null && list.size() > 0){
- result = "1";
- }else{
- result = "0";
- }
- HttpServletResponse response = WebContextUtil.getResponse();
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- PrintWriter out = response.getWriter();
- out.write(result.toString());
- } catch (IOException e) {
- throw new RuntimeException("驗證身份證号碼出錯", e);
- }
- }
- @Action(value = "UserAction_checkNum")
- public void checkNum(){
- try {
- String result = "0";
- String check_number_key = (String)WebContextUtil.getSession().getAttribute("CHECK_NUMBER_KEY");
- if(checkNum != check_number_key && !checkNum.equals(check_number_key)){
- result = "1";
- }else{
- result = "0";
- }
- HttpServletResponse response = WebContextUtil.getResponse();
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- PrintWriter out = response.getWriter();
- out.write(result.toString());
- } catch (IOException e) {
- throw new RuntimeException("驗證驗證碼出錯", e);
- }
- }
- @Action(value = "UserAction_checkCode")
- public void checkCode() throws Exception{
- String result = "0";
- String SmsCheckCode = WebContextUtil.getRequest().getParameter("SmsCheckCode");
- String code = (String) WebContextUtil.getSession().getAttribute("code");
- try {
- if(SmsCheckCode != code && !SmsCheckCode.equals(code)){
- result = "0";
- }else{
- result = "1";
- }
- } catch (Exception e) {
- throw new RuntimeException("短信驗證失敗", e);
- }
- HttpServletResponse response = WebContextUtil.getResponse();
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- PrintWriter out = response.getWriter();
- out.write(result.toString());
- }
- @Action(value = "UserAction_sms")
- public void sms() throws Exception {
- String result = "0";
- String jbPhone = WebContextUtil.getRequest().getParameter("jbPhone");
- String code = WebContextUtil.getRequest().getParameter("code");
- WebContextUtil.getSession().setAttribute("code", code);
- if(!initClient()) {
- return;
- }
- // 手機号碼
- String mobilephone = jbPhone;
- // 短信内容+随機生成的6位短信驗證碼
- String content = "根據中國證監會舉報中心委托,特向您發送此條短信。您的注冊驗證碼為:" + code;
- // 操作使用者的ID
- Integer operId = Integer.parseInt(Env.getInstance().getProperty("operId"));
- // 定時發送的的發送時間(預設為空,如果即時發送,填空)
- String tosend_time = "";
- // 應用系統的短信ID,使用者查詢該短信的狀态報告(預設為0,即不需查詢短信的狀态報告)
- int sms_id = 0;
- // 黑名單過濾(0:不需要黑名單過濾,1:需要黑名單過濾,預設為0)
- short backlist_filter = 0;
- // 禁止語過濾(0:不需要禁止語過濾,1:需要禁止語過濾,預設為0)
- short fbdword_filter = 0;
- // 優先級(值越大優先級越高,0:普通,1,:優先,2:最高,預設為0)
- short priority = 0;
- // 短信有效時間(格式為:YYYY-MM-DD HH:mm:ss目前為空)
- String valid_time = "";
- int messageCount = countService.findAllRecord(mobilephone);
- log.info("已發短信條數為:" +messageCount);
- if(messageCount < 5){
- if (!sendMessage(mobilephone, content, operId, tosend_time, sms_id,
- backlist_filter, fbdword_filter, priority, valid_time)) {
- result = "0";// 失敗
- } else {
- result = "1";// 成功
- count.setPhone(mobilephone);// 手機号碼
- count.setCaptcha(code);// 短信驗證碼
- count.setSendTime(CommonUtil.getNowDate());// 短信發送時間
- if(count != null){
- countService.saveEntity(count);
- log.info("短信驗證碼發送記錄儲存成功!");
- }
- }
- }else{
- result = "2";//一個手機号碼最多發送5條短信驗證碼
- log.info("該手機号碼今天發送驗證碼過多");
- }
- HttpServletResponse response = WebContextUtil.getResponse();
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- PrintWriter out = response.getWriter();
- out.write(result.toString());
- }
- public static boolean initClient() {
- if (!SmsWebClient.enable()) {
- int ret = 0;
- try {
- ret = SmsWebClient.init(url, userName, passWord);
- if (ret == -1 || !SmsWebClient.enable()) {
- log.info("短信平台接口初始化失敗!");
- return false;
- }
- log.info("短信平台接口初始化成功!" + ret + "-----");
- } catch (Exception ex) {
- ex.printStackTrace();
- log.info("短信平台接口初始化過程中異常!");
- }
- }
- return true;
- }
- public static boolean sendMessage(java.lang.String mobilephone,
- java.lang.String content, int operId, java.lang.String tosend_time,
- int sms_id, short backlist_filter, short fbdword_filter,
- short priority, java.lang.String valid_time) {
- // 單個手機号碼發送
- try {
- SmsReturnObj retObj = SmsWebClient.webSendMessage(mobilephone,
- content, operId, tosend_time, sms_id, backlist_filter,
- fbdword_filter, priority, valid_time);
- if (retObj.getReturnCode() != 1) {
- log.info("短信發送失敗,原因為:" + retObj.getReturnMsg());
- return false;
- } else {
- log.info("短信發送成功!傳回結果為:" + retObj.getReturnMsg());
- return true;
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- log.info("短信發送過程發生異常!");
- }
- return true;
- }
- }
六:具體的短信接口demo到這裡下,這裡你下載下傳了也不能成功的發送短信,因為你必須要短信平台商給你提供:url,userName,passWord,operId,以及短信平台商還要綁定你的外網ip位址,這樣才能真正的發送短信。
Demo下載下傳連結: http://pan.baidu.com/s/1qWt1Qdm
=============================================================================
WebService執行個體3:利用WebService給手機發短信 執行個體說明 通過程式設計方式實作短資訊的發送對很多人來說是一件比較繁雜的事情,目前一般的解決方法是通過計算機和手機的連線,通過對手機程式設計的語言編寫相關的手機短資訊程式來實作,而這種方法對于一般人來說是很難達到的,因為此種方法不僅要有很多必備的硬體裝置,也要懂得手機程式設計的相關知識。本執行個體将通過WebService技術發送手機短信,執行個體運作效果如圖17.10所示。
關鍵技術 本執行個體利用一個現有的可發送短信的WebService,這個 WebService是新浪網提供的可供使用者直接調用的發送短消息的WebService。這個WebService的位址是http://smsinter.sina.com.cn/ws/smswebservice0101.wsdl。在 這個Service中,提供了一個發送短消息的方法sendXml,此方法的文法如下: string sendXml (carrier , userid , password , mobilenumber , content , msgtype ) sendXml方法中的6個參數均為string類型,并且sendXml方法的傳回值也是string類型。 sendXml方法中的參數說明如表16.3所示。
設計過程 (1)建立一個網站,将其命名為MobileNote,預設首頁為Default.aspx。在該頁面中主要添加一個GridView 控件和一個Button控件,分别用來顯示資料和執行查詢操作。 (2)Default.aspx頁面中主要控件的類型、名稱及用途如表17.3所示。
(3)執行個體中單擊Button1按鈕完成短信發送,代碼如下:
=============================================================================
這個是方法是使用中國網建提供的SMS短信平台(http://sms.webchinese.cn)進行實作。
是以在做這個的時候需要在中國網建SMS短信平台注冊個用于測試的使用者名,拿到使用者名和密鑰
需引用的jar包
commons-logging-1.1.1.jar
commons-httpclient-3.1.jar
commons-codec-1.4.jar
第一部分:SMS短信通編碼接口
GBK編碼發送接口位址:
http://gbk.sms.webchinese.cn/?Uid=本站使用者名&Key=接口安全密碼&smsMob=手機号碼&smsText=短信容
UTF-8編碼發送接口位址:
http://utf8.sms.webchinese.cn/?Uid=本站使用者名&Key=接口安全密碼&smsMob=手機号碼&smsText=短信内容
擷取短信數量接口位址(UTF8):
http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num&Uid=本站使用者名&Key=接口安全密碼
擷取短信數量接口位址(GBK):
http://sms.webchinese.cn/web_api/SMS/GBK/?Action=SMS_Num&Uid=本站使用者名&Key=接口安全密碼
提示:HTTP調用URL接口時, 參數值必須URL編碼後再調用
提示:①、多個手機号請用半角,隔開如:13888888886,13888888887,1388888888 一次最多對100個手機發送。 ②、短信内容支援長短信,最多300個字,普通短信66個字/條,長短信64個字/條計費
| ||||||||||||||||||||||||||||||||||||
注意:①、調用API接口,需登入中國網建SMS短信通平台,申請106網關發送,即發即到! ②、發送測試短信請勿輸入:短信測試等詞語,請直接送出您要發送的短信内容; ③、接口發送短信時請在内容後加簽名:【XX公司或XX網名稱】,否者會被屏蔽。 ④、短信簽名可在使用者平台平台上設定,也可以在短信内容後,直接加入。 |
JAVA語言發送短信核心代碼:
[java] view plain copy
- import java.io.UnsupportedEncodingException;
- import org.apache.commons.httpclient.Header;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.NameValuePair;
- import org.apache.commons.httpclient.methods.PostMethod;
- public class SendMsg_webchinese {
- public static void main(String[] args)throws Exception{
- HttpClient client = new HttpClient();
- PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");
- post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在頭檔案中設定轉碼
- NameValuePair[] data ={
- new NameValuePair("Uid", "本站使用者名"),
- new NameValuePair("Key", "接口安全密碼"),
- new NameValuePair("smsMob","手機号碼"),
- new NameValuePair("smsText","短信内容")
- };
- post.setRequestBody(data);
- client.executeMethod(post);
- Header[] headers = post.getResponseHeaders();
- int statusCode = post.getStatusCode();
- System.out.println("statusCode:"+statusCode);
- for(Header h : headers){
- System.out.println(h.toString());
- }
- String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
- System.out.println(result);
- post.releaseConnection();
- }
- }
[java] view plain copy