您的位置:首页 > 编程语言 > Java开发

Java用户注册服务器发送短信验证码功能实现

2017-12-22 11:02 741 查看
<–start–>

当客户端发送了http的请求给服务器之后,服务器获取手机号然后调用短信平台给该手机号发送短信验证码。

给服务器发送请求的js代码:

<script type="text/javascript">
// 模块定义
var signupApp = angular.module("signupApp", []);
// 控制器定义
signupApp.controller("signupCtrl", ["$scope","$http",function($scope,$http) {
$scope.btnMsg = "发送验证码";
var active = true;
var second = 60; // 倒计时60秒
var secondInterval;
$scope.getCheckCode = function(telephone) {
if(active == false) {
return;
}
// 1 发送一个HTTP请求,通知服务器 发送短信给目标用户
var regex = /^1(3|5|7|8)\d{9}$/;
if(regex.test(telephone)) {
// 校验通过
$http({
method: 'GET',
url: 'customer_sendSms.action',
params : {
telephone : telephone
}
}).error(function(data, status, headers, config) {
// 当响应以错误状态返回时调用
alert("发送短信出错,请联系管理员");
});
} else {
// 校验失败
alert("手机号非法,请重新输入 ");
return;
}
</script>


在服务器端程序中的web.xml文件中要配置以下内容:

① struts2的核心拦截器StrutsPreparedAndExecuteFilter;

② spring的核心配置文件applicationContext.xml所在位置的classpath;

③ spring的核心监听器ContextLoaderListener。

完整的web.xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<!-- spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- spring核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- struts核心控制器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

</web-app>


接下来在服务器端编写CustomerAction代码,获取传递过来的手机号码参数,然后给该手机号码发送短信。 鉴于大量Action的代码比如模型驱动接收参数,压入值栈等都是重复性的操作,所以有必要将这些代码抽取成一个类,让其他的子类Action去继承。BaseAction父类的代码如下:

public abstract class BaseAction<T> extends ActionSuppor
120b7
t implements
ModelDriven<T> {

// 模型驱动
protected T model;

@Override
public T getModel() {
return model;
}

// 构造器 完成model实例化
public BaseAction() {
// 构造子类Action对象 ,获取继承父类型的泛型
Type genericSuperclass = this.getClass().getGenericSuperclass();
// 获取类型第一个泛型参数
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Class<T> modelClass = (Class<T>) parameterizedType
.getActualTypeArguments()[0];
try {
model = modelClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
System.out.println("模型构造失败...");
}
}
}


创建CustomerAction类,在类上添加相关的注解:

① struts2的注解:@ParentPackage(“json-default”),@Namespace(“/”);

② spring的注解:@Controller,@Scope(“prototype”)

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> { }


在本例中要使用到webservice的技术,CustomerAction要远程调用crm系统中crm_domain工程中的数据,因此要在CustomerAction所在项目中添加对crm_domain的依赖,具体要在pom.xml文件中实现。

<dependency>
<groupId>cn.niwotaxuexiba.maven</groupId>
<artifactId>crm_domain</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>


完整的pom.xml文件内容:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>

<parent>
<groupId>cn.niwotaxuexiba.maven</groupId>
<artifactId>common_parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>

<artifactId>bos_fore</artifactId>
<packaging>war</packaging>
<name>bos_fore</name>
<description>物流前端系统</description>

<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<version>1.1</version>
<configuration>
<port>9003</port>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency> <groupId>cn.niwotaxuexiba.maven</groupId> <artifactId>crm_domain</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency></dependencies>
</project>


在CustomerAction类中,编写一个sendSms的方法:

① 需要获取的手机号保存在Customer对象中,所以要用到webservice技术;

② 生成一个随机短信验证码,用到的是apache.commons.lang包下的RandomStringUtils类来生成随机验证码;

③ 将生成的短信验证码保存到session中,调用struts2的ServletActionContext获取request对象,然后存入session.保存到session的方法ServletActionContext.getRequest().setAttribute(model.getTelephone(),randomCode);

④ 生成要发送的短信正文内容,其实就是生成一个字符串;

⑤ 调用SMS服务发送短信(发送短信的工具类SmsUtils已经在下面提供);

⑥ 发送短信的途径有http和webservice两种,http的方式将返回000,webservice将返回16位的一个字符串,本例中使用http的方式。

完整的CustomerAction代码如下:

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction2 extends BaseAction<Customer> {
@Action(value="customer_sendSms")
public String sendSms() throws IOException{
//生成短信验证码
String randomCode = RandomStringUtils.randomNumeric(4);
//将短信验证码保存到session中
ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(),randomCode);
//编辑短信内容
String msg = "你好!本次获取的验证码位:"+randomCode;
//调用SMS服务发送短信
String result = SmsUtils.sendSmsByHTTP(model.getTelephone(),msg);
if(result.startsWith("000")){
//以"000"开头表示短信发送成功
return NONE;
}else{
//发送失败,就抛出一个运行期异常
throw new RuntimeException("短信发送失败,信息码:"+result);
}
}
}


发短信的SmsUtils工具类完整代码如下:

/**
* 调用吉信通 发短信工具类
*
* @author niwotaxuexiba
*
*/
public class SmsUtils {
private static String userid = "seawind";
private static String pass = "niwotaxuexiba123456";

/**
* 调用HTTP 协议方式发送短信
*
* @param mobile
* @param content
* @return
* @throws UnsupportedEncodingException
*/
public static String sendSmsByHTTP(String mobile, String content)
throws UnsupportedEncodingException {
HttpURLConnection httpconn = null;
String result = "Error";
StringBuilder sb = new StringBuilder();
sb.append("http://service.winic.org:8009/sys_port/gateway/index.asp?");

// 以下是参数
sb.append("id=").append(URLEncoder.encode(userid, "gb2312"));
sb.append("&pwd=").append(pass);
sb.append("&to=").append(mobile);
sb.append("&content=").append(URLEncoder.encode(content, "gb2312"));
sb.append("&time=").append("");
try {
URL url = new URL(sb.toString());
httpconn = (HttpURLConnection) url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(
httpconn.getInputStream()));
result = rd.readLine();
rd.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpconn != null) {
httpconn.disconnect();
httpconn = null;
}
}
return result;
}

/**
* 调用 WebService 协议方式发送短信
*
* @param mobiles
* @param msg
* @return
*/
public static String sendSmsByWebService(String mobiles, String msg) {
String result = "-12";
try {
Document doc;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = getSoapInputStream(userid, pass, mobiles, msg, "");
if (is != null) {
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName("SendMessagesResult");
Node n = nl.item(0);
result = n.getFirstChild().getNodeValue();
is.close();
}
return result;
} catch (Exception e) {
System.out.print("SmsSoap.sendSms error:" + e.getMessage());
return "-12";
}
}

private static String getSoapSmssend(String userid, String pass,
String mobiles, String msg, String time) {
try {
String soap = "";
soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soap:Body>"
+ "<SendMessages xmlns=\"http://tempuri.org/\">" + "<uid>"
+ userid + "</uid>" + "<pwd>" + pass + "</pwd>" + "<tos>"
+ mobiles + "</tos>" + "<msg>" + msg + "</msg>" + "<otime>"
+ time + "</otime>" + "</SendMessages>" + "</soap:Body>"
+ "</soap:Envelope>";
return soap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}

private static InputStream getSoapInputStream(String userid, String pass,
String mobiles, String msg, String time) throws Exception {
URLConnection conn = null;
InputStream is = null;
try {
String soap = getSoapSmssend(userid, pass, mobiles, msg, time);
if (soap == null) {
return null;
}
try {

URL url = new URL("http://service2.winic.org:8003/Service.asmx");

conn = url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length",
Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type",
"text/xml; charset=utf-8");
conn.setRequestProperty("HOST", "service2.winic.org");
conn.setRequestProperty("SOAPAction",
"\"http://tempuri.org/SendMessages\"");

OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
osw.write(soap);
osw.flush();
} catch (Exception ex) {
System.out.print("SmsSoap.openUrl error:" + ex.getMessage());
}
try {
is = conn.getInputStream();
} catch (Exception ex1) {
System.out.print("SmsSoap.getUrl error:" + ex1.getMessage());
}

return is;
} catch (Exception e) {
System.out.print("SmsSoap.InputStream error:" + e.getMessage());
return null;
}
}

public static void main(String[] args) throws IOException {
String randomCode = RandomStringUtils.randomNumeric(4);

System.out.println(sendSmsByWebService("xxx", "尊敬的用户您好,本次获取的验证码为:"
+ randomCode + ",服务电话:4001234567"));
}
}


<–end–>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐