短信验证码接口使用的是阿里云上的短信平台API,上面有很多免费的,可以拿来测试使用
本人写的稍显简单,有不足之处敬请谅解
前台jsp
<script type="text/javascript">
function sendMsg() {
var phone = $("#phone").val();//获取输入的手机号
var code = $("#code").val();//获取输入的验证码
$.ajax({
type:"post",
data:{
phone:phone,
code:code
},
url:"${pageContext.request.contextPath }/list", //使用的是绝对路径
success:function(data) {
$("#mcode").val(data)
}
});
}
//验证码判断,登录进主页面
function login() {
var code = $("#code").val();
var mcode = $("#mcode").val();
if(code == mcode)
window.location.href="${pageContext.request.contextPath }/trun"
else {
alert("验证码输入错误")
}
}
</script>
后台,大部分代码是从API复制,获取你输入的手机号,略作修改就可以了
public class SendMessage {
@RequestMapping("/list")
@ResponseBody
public String login(@RequestParam("phone") String phone,@RequestParam("code") String code,HttpServletRequest req,HttpServletResponse resp) throws IOException {
//生成6位随机验证码
Random random = new Random();
String result="";
for (int i=0;i<6;i++)
{
result=result+random.nextInt(10);
}
String host = "https://feginesms.market.alicloudapi.com";
String path = "/codeNotice";
String method = "GET";
String appcode = "你自己的appcode";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
Map<String, String> querys = new HashMap<String, String>();
querys.put("param", result);//生成的随机验证码
querys.put("phone", phone);//输入的手机号
querys.put("sign", "1");
querys.put("skin", "1");
//JDK 1.8示例代码请在这里下载: http://code.fegine.com/Tools.zip
try {
HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//System.out.println(response.toString());如不输出json, 请打开这行代码,打印调试头部状态码。
//状态码: 200 正常;400 URL无效;401 appCode错误; 403 次数用完; 500 API网管错误
//获取response的body
//System.out.println(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}