短信验证码

短信验证码

创建web_user工程 --- 发送队列

定义页面属性

data:{
	userEntity:{
		username:'',
		password:'',
		phone:'',
		smscode:''
	},
	password2:''
},

<div class="control-group">
	<label class="control-label">用户名:</label>
	<div class="controls">
		<input type="text" placeholder="请输入你的用户名" v-model="userEntity.username" class="input-xfat input-xlarge">
	</div>
</div>
<div class="control-group">
	<label  class="control-label">登录密码:</label>
	<div class="controls">
		<input type="password" placeholder="设置登录密码" v-model="userEntity.password" class="input-xfat input-xlarge">
	</div>
</div>
<div class="control-group">
	<label class="control-label">确认密码:</label>
	<div class="controls">
		<input type="password" placeholder="再次确认密码" v-model="password2" class="input-xfat input-xlarge">
	</div>
</div>

<div class="control-group">
	<label class="control-label">手机号:</label>
	<div class="controls">
		<input type="text" placeholder="请输入你的手机号" class="input-xfat input-xlarge">
	</div>
</div>
<div class="control-group">
	<label class="control-label">短信验证码:</label>
	<div class="controls">
		<input type="text" placeholder="短信验证码" v-model="userEntity.smscode" class="input-xfat input-xlarge">
		<a href="#" @click="sendCode()">获取短信验证码</a>
	</div>
</div>

发送验证码点击

sendCode:function () {
	if(this.userEntity.phone==null || this.userEntity.phone==""){
		alert("请填写手机号码");
		return ;
	}
	axios.get('/user/sendCode.do',{params:{phone:this.userEntity.phone}}).then(function (response) {
		//获取服务端响应的结果
		console.log(response.data);
	}).catch(function (reason) {
		console.log(reason);
	});
}

添加依赖关系

<dependency>
    <groupId>com.itxk</groupId>
    <artifactId>dao</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>com.itxk</groupId>
    <artifactId>interface</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

导入配置文件

web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!-- 加载spring容器 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <!--classpath*  加载自己和自己依赖的classpath内容-->
    <param-value>classpath*:spring/applicationContext*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

spring/applicationContext-jms-producer.xml

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

    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.1.88:61616"/>
    </bean>

    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
    </bean>

    <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
        <property name="connectionFactory" ref="connectionFactory"/>
    </bean>

    <!--这个是队列目的地,点对点的  文本信息-->
    <bean id="smsDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="sms"/>
    </bean>
</beans>

spring/applicationContext-service.xml

		<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        
    <dubbo:protocol name="dubbo" port="20886"></dubbo:protocol> 

    <dubbo:application name="mystore-user-service"/>
    <dubbo:registry address="zookeeper://192.168.1.88:2181"/>
    <dubbo:annotation package="com.itxk.core.service" />
</beans>

spring/applicationContext-tx.xml

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 事务管理器  -->  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  

    <!-- 开启事务控制的注解支持 -->  
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

在common工程中导入手机号验证工具类PhoneFormatCheckUtils

public class PhoneFormatCheckUtils {
        /** 
         * 大陆号码或香港号码均可 
         */  
        public static boolean isPhoneLegal(String str)throws PatternSyntaxException {  
            return isChinaPhoneLegal(str) || isHKPhoneLegal(str);  
        }
        /** 
         * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 
         * 此方法中前三位格式有: 
         * 13+任意数 
         * 15+除4的任意数 
         * 18+除1和4的任意数 
         * 17+除9的任意数 
         * 147 
         */  
        public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {  
            String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,4,5-9])|(17[0-8])|(147))\\d{8}$";
            Pattern p = Pattern.compile(regExp);  
            Matcher m = p.matcher(str);  
            return m.matches();  
        }  
      
        /** 
         * 香港手机号码8位数,5|6|8|9开头+7位任意数 
         */  
        public static boolean isHKPhoneLegal(String str)throws PatternSyntaxException {  
            String regExp = "^(5|6|8|9)\\d{7}$";  
            Pattern p = Pattern.compile(regExp);  
            Matcher m = p.matcher(str);  
            return m.matches();  
        }
    }

在interface工程中创建UserService

public interface UserService {
	public void sendCode(String phone);
}

在service_user工程中创建UserServiceImp

@Service
public class UserServiceImp implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private ActiveMQQueue smsDestination;
    @Override
    public void sendCode(final String phone) {
        //1. 生成一个随机6为数字, 作为验证码
        StringBuffer sb = new StringBuffer();
        for (int i =1; i < 7; i++) {
            int s  = new Random().nextInt(10);
            sb.append(s);
        }
        //2. 手机号作为key, 验证码作为value保存到redis中, 生存时间为10分钟
        redisTemplate.boundValueOps(phone).set(sb.toString(), 60 * 10, TimeUnit.SECONDS);
        final String smsCode = sb.toString();

		//3. 将手机号, 短信内容, 模板编号, 签名封装成map消息发送给消息服务器
		jmsTemplate.send(smsDestination, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage message = session.createMapMessage();
				message.setString("mobile", phone);//手机号
				message.setString("template_code", "SMS_169111508");//模板编码
				message.setString("sign_name", "疯码");//签名
				Map map=new HashMap();
				map.put("code", smsCode);	//验证码
				message.setString("param", JSON.toJSONString(map));
				return (Message) message;
			}
		});
	}
}

在web_user工程创建控制器UserController

@RequestMapping("/sendCode")
public Result sendCode(String phone) {
    try {
    	if (phone == null || "".equals(phone)) {
    		return new Result(false, "手机号不能为空!");
    	}
    	if (!PhoneFormatCheckUtils.isPhoneLegal(phone)) {
    		return new Result(false, "手机号格式不正确");
    	}
    	userService.sendCode(phone);
    	return  new Result(true, "发送成功!");
    } catch (Exception e) {
    	e.printStackTrace();
    	return new Result(false, "发送失败!");
    }
}

创建SMS工程 --- 接收队列

添加依赖

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.11</version>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>com.fmjava</groupId>
	<artifactId>dao</artifactId>
	<version>1.0</version>
</dependency>
<dependency>
	<groupId>com.fmjava</groupId>
	<artifactId>interface</artifactId>
	<version>1.0</version>
</dependency>
<dependency>
	<groupId>com.aliyun</groupId>
	<artifactId>aliyun-java-sdk-core</artifactId>
	<version>4.1.0</version>
</dependency>

添加配置文件

web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <!-- 加载spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring/applicationContext*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

spring/applicationContext-jms-consumer.xml

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

    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.1.88:61616"/>
    </bean>

    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
    </bean>

    <!-- 点对点模式,接收sms消息-->
    <bean id="queueSMSDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <!--指定从这个队列中去接收SMS信息-->
        <constructor-arg value="sms"/>
    </bean>

    <!-- 点对点模式, 消息监听容器  发送短信-->
    <bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="queueSMSDestination" />
        <property name="messageListener" ref="smsListener" />
    </bean>
    <bean id="smsListener" class="com.fmjava.core.listener.PageListener"></bean>

</beans>

spring/applicationContext-service.xml

<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
	http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <dubbo:protocol name="dubbo" port="20889"></dubbo:protocol>
    <dubbo:application name="fmjava-sms-service"/>
    <dubbo:annotation package="com.fmjava.core.service" />
</beans>

创建发送短信工具类SmsUtil

public class SmsUtil {

    /**
     * 发送短信
     * @param mobile 手机号
     * @param template_code 模板号
     * @param sign_name 签名
     * @param param 验证码
     */
    public static void sendSms(String mobile,String template_code,String sign_name,String param) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIFrvvzwdyvzcK", "mjRPox3Y5opiwdV6lCZu6KEBmO0Q0M");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", sign_name);
        request.putQueryParameter("TemplateCode", template_code);
        request.putQueryParameter("TemplateParam",param);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

创建监听器, 监听短信消息

public class SMSListener implements MessageListener {
    @Override
    public void onMessage(Message message) {
        MapMessage map = (MapMessage)message;
        try {
            SmsUtil.sendSms( map.getString("mobile"),
                    map.getString("template_code"),
                    map.getString("sign_name"),
                    map.getString("param"));
        } catch (JMSException e) {
            e.printStackTrace();
        }
        System.out.println(map);
    }
}
posted @ 2019-10-21 09:56  海韵༒听心  阅读(690)  评论(0编辑  收藏  举报