验证短信与验证码登陆操作ssm框架下的改进机制!

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" import="java.util.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="${pageContext.request.contextPath }/assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="${pageContext.request.contextPath }/assets/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="${pageContext.request.contextPath }/css/flaty.css">
<link rel="stylesheet" href="${pageContext.request.contextPath }/css/flaty-responsive.css">
<link href="${pageContext.request.contextPath }/css/bootstrap.min.css" rel="stylesheet">
<script src="${pageContext.request.contextPath }/js/jquery-1.12.4.min.js"></script>
<script src="${pageContext.request.contextPath }/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath }/js/jquery-confirm.min.js"></script>
<link href="${pageContext.request.contextPath }/css/jquery-confirm.min.css" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>短信验证信息</title>
<style type="text/css">
html,body{
    width:100%;
    height:100%
}

h2{
font-family: Microsoft YaHei;
font-size: large;}


</style>
</head>
<body class="login-page">


<!-- BEGIN Main Content -->
        <div class="login-wrapper">
            <!-- BEGIN Login Form -->
            <form id="form-login" action="comparecode.action" method="post">
                <h2>短信验证信息</h2>
                <div class="form-group">
                    <div class="controls">
                        <input type="text" name="phone"  id ="phone" value="${phone }" placeholder="phone"  class="form-control" />
                        ${flag }${flag1 }
                    </div>
                </div>
                <div class="form-group">
                    <div class="controls">
                    <input type="text" name="code" placeholder="请输入短信验证码"   class="form-control" onblur=" return checkpd()"/>
                    <input class="glyphicon glyphicon-send"  type="button" value="发送验证码" id="button" onclick="send()" >
                    </div>
                </div>
                
                 <div class="form-group">
                    <div class="controls">
                        <input type="text" id="user_input_verifyCode" name="user_input_verifyCode" placeholder="验证码" maxlength="4"  class="form-control" />
                        <span class="code_img"> 
                        <img src="${pageContext.request.contextPath }/login/getVerifyCode.action" width="90" height="40" id="verifyCodeImage">
		                </span> 
		               <span> 
		               <a id="changeVerifImageRegister" onclick="javascript:changeImage();">换一张</a>
		               </span>
                    </div>
                </div>
                <div class="form-group">
                    <div class="controls">
                        <button id="submit" type="button" value="登录" class="btn btn-primary form-control" onclick="login()">登&#x3000;陆</button>
                    
                    </div>
                </div>
            </form>
</div>

<!-- 

<div class="content">

<div class="jumbotron">
  <h5>短信验证信息</h5>
  
  <form action="comparecode.action" method="post">
                  手机号:<input type="text" name="phone"  id ="phone" value="${phone }">
          ${flag }${flag1 }<br><br>
                   短信码:<input type="text" name="code" placeholder="请输入短信验证码" >
           <input class="glyphicon glyphicon-send"  type="button" value="发送验证码" id="button" onclick="send()" >
           <input type="submit" value="注册">
   </form>

   <form>
   
     <div>
         <input type="text" id="user_input_verifyCode" name="user_input_verifyCode" placeholder="验证码" maxlength="4">
        
          <span class="code_img"> 
           <img src="${pageContext.request.contextPath }/login/getVerifyCode.action" width="90" height="40" id="verifyCodeImage">
		  </span> 
		  <span> 
		   <a id="changeVerifImageRegister" onclick="javascript:changeImage();">换一张</a>
		  </span>
     </div>
		 <input id="submit" type="button" value="登录" onclick="login()">
   </form>
</div>
</div>
 -->



	<script type="text/javascript">
	function send(){
		var phone= document.getElementById("phone");
		var number= phone.value;
		window.location.href="<%=path%>/sendme.action?phone="+number;
		}
	
	
	function genTimestamp() {    
        var time = new Date();    
        return time.getTime();    
    } 
	 function changeImage() {
         $('#verifyCodeImage').attr('src',
                 '${pageContext.request.contextPath }/login/getVerifyCode.action?timestamp=' + genTimestamp());
     }
	 //登录,目前只检测验证码
	 function login(){
		 var user_input_verifyCode=$("#user_input_verifyCode").val();
		 $.ajax({
				type : 'post',
				url : "${pageContext.request.contextPath}/login/login.action",
				data:{verifyCode:user_input_verifyCode},
				dataType : "json",
				success : function(data) {	
					alert(data.msg);
					if(data.success){
	                	   window.location.href='${pageContext.request.contextPath }/admin/user/index.action';
	                   }else{
	                	   alert(data.msg);
	                	   window.location.href='${pageContext.request.contextPath }/admin/user/extra.action'
	                   }
				},
				error : function() {
					alert("查询失败");
				}
			}); 
	 }
	
	 </script>

</body>
</html>

在jsp中验证机制短信机制需要发送短信的插件:

package com.hanren.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;


public class SendMessage {
	public static  HashMap<String,String> getMessageStatus(String phone) throws HttpException, IOException{
		HashMap<String,String> m = new HashMap<String,String>();
		//http协议
		HttpClient client = new HttpClient();
		//连接第三方平台
		PostMethod post = new PostMethod("http://gbk.api.smschinese.cn/");
		post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码  


		//生成六位验证码
		String charValue = "";
		for (int i = 0; i < 6; i++) {
		char c = (char) (randomInt(0, 9) + '0');
		charValue += String.valueOf(c);
		}
		//短信模板
		NameValuePair[] data ={ 
		new NameValuePair("Uid", "这里是注册的时候的用户名"),  //sms短信通 注册的用户名
		new NameValuePair("Key", "这里是注册的时候密匙"), //密匙
		new NameValuePair("smsMob",phone),//要发送的手机号
		new NameValuePair("smsText","验证码:"+charValue+",发送")//短信内容
		};  

		post.setRequestBody(data); 
		client.executeMethod(post);
		//获取http头
		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); //打印返回消息状态  
		//将返回消息和6位数验证码放入到m列表里面
		m.put("result", result);  
		m.put("code", charValue);
		//断开与第三方平台的连接
		post.releaseConnection();  

		return m;

		}
		//生成验证码
		public static  int randomInt(int from, int to) {
		Random r = new Random();
		return from + r.nextInt(to - from);
		}
}

2.在controller中接收数据:

package com.hanren.web.controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hanren.model.Phone;
import com.hanren.service.PhoneService;
import com.hanren.util.Result;
import com.hanren.util.SendMessage;




/**
 * @author 宇神
 * 从数据库查找是否被注册
 * 如果没被注册{
 * 发送短信,保存验证码到缓存
 * }else{
 * 返回注册页面
 * }
 * 
 *  将输入的验证码与缓存中的验证码比对
 *  如果一致{
 *  注册
 *  }不一致{
 *  }
 * 
 */
@Controller
public class Send {

@Resource
private PhoneService service;

@RequestMapping(value="phone")
public String phone() {
	return "phone";
}


@ResponseBody
@RequestMapping(value="sendme" ,method = RequestMethod.GET)
public ModelAndView sendme(@RequestParam(value="phone") String phone,HttpServletRequest request) throws  IOException{
     ModelAndView model = new ModelAndView();
     if(!service.checkPhone(phone)){//查找是否被注册
      HashMap<String, String> m = SendMessage.getMessageStatus(phone); //应用发送短信接口  
      String result = m.get("result");   //获取到result值  
           if (result.trim().equals("1")) {  
                 String code = m.get("code");
                 System.out.println(code+"============================================================================");

                 HttpSession  session = request.getSession(); //设置session  
                 session.setAttribute(phone+"code", code);    //将短信验证码放到session中保存  
                 session.setMaxInactiveInterval(60 * 3); //缓存设置3分钟
                 model.addObject("flag", "短信发送成功");
              }else{
                 model.addObject("flag", "短信发送失败,请重试");
             }
                 model.addObject("phone", phone);
                 model.setViewName("phone");
          }else{
               model.addObject("flag1", "该手机号已被注册");
               model.addObject("phone", phone);
               model.setViewName("phone");
           }
               return model;

}


@RequestMapping(value="comparecode" ,method = RequestMethod.POST)
public ModelAndView comparecode(@RequestParam(value="code") String code,Phone pmodel,HttpServletRequest request){
ModelAndView model = new ModelAndView();
       //从session中比对发送的验证码
       HttpSession  session = request.getSession();//设置session
       String sessioncode =(String) session.getAttribute(pmodel.getPhone()+"code");
       System.out.println(sessioncode);
     if((code).equals(sessioncode)){//比对缓存
	       //注册
          service.registUser(pmodel);
          model.addObject("result", "注册成功");
      }else{
    	  
        model.addObject("result", "验证码不正确 ,注册失败");
        model.setViewName("phone");

      }
     model.setViewName("result");
     return model;

}

@RequestMapping(value="/login/getVerifyCode.action")
public void gerenate(HttpServletResponse response ,HttpSession session) {
	ByteArrayOutputStream  output = new ByteArrayOutputStream();
	@SuppressWarnings("unused")
	String verifyCodeValue = drawImg(output);
	session.setAttribute("verifyCodeValue", verifyCodeValue);
	try {
		ServletOutputStream out = response.getOutputStream();
		output.writeTo(out);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
/**
 * 绘画验证码
 * @param output
 * @return
 */

private String drawImg(ByteArrayOutputStream output) {
	String code = "";
	for(int i = 0;i< 4;i++) {
		code+= randomChar();
	}
	int width = 70;
	int height = 35;
	BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_USHORT_555_RGB);
	Font font = new Font("Times new Roman", Font.PLAIN, 20);
//调用Graphics2d绘画验证码
	Graphics2D g = bi.createGraphics();
	g.setFont(font);
    Color color = new Color(0,0,205);
    g.setColor(color);
    g.setBackground(new Color(255,255,224));
    g.clearRect(0,0, width, height);
    FontRenderContext context = g.getFontRenderContext();
    Rectangle2D bounds = font.getStringBounds(code, context);
    double x = (width - bounds.getWidth())/2;
    double y = (height - bounds.getHeight())/2;
    double ascent = bounds.getY();
    //干扰线
    Random random = new Random();
      for(int i=0;i<8;i++){
         int x1=random.nextInt(width);
         int y1=random.nextInt(height);
         int x2=random.nextInt(width);
         int y2=random.nextInt(height);
         g.drawLine(x1, y1, x1+x2, y1+y2);
      }
    @SuppressWarnings("unused")
	double daseY = y - ascent;
    g.drawString(code, (int)x, 20);
    g.dispose();
    try {
		ImageIO.write(bi, "jpg", output);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    
	return code;
}

/**
 * 随机字符生成
 * @return
 */
private char randomChar() {
	Random r = new Random();
	String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	return s.charAt(r.nextInt(s.length()));
}

@RequestMapping(value="/login/login.action",method=RequestMethod.POST)
@ResponseBody
public Result<String> login(HttpServletRequest request ,HttpSession session ) {
	 ModelAndView model = new ModelAndView();
	String inputVerfiCode = request.getParameter("verifyCode");
	System.out.println("yanzhengmadezhi=====:"+inputVerfiCode);
	String verifyCodeValue = (String) session.getAttribute("verifyCodeValue");
    System.out.println("sessionzhongd yanzhengmadezhi"+verifyCodeValue);
    if(verifyCodeValue.equals(inputVerfiCode.toUpperCase())) {
             
    	return new Result<String>(true, "输入验证ok", null) ;
    }else {
    	
    	return new Result<String>(false, "输入验证码不正确", null) ;    }
}



}

3.另外有个工具类是resultcode:

package com.hanren.util;

/**
 * 项目结果编码
 * 
 * @author Tianyun
 *
 *
 */
public enum ResultCode {
	/** 正常 **/
	SUCCESS("0000"),
	/** 登录失效 **/
	LOGIN_INVALID("3101"),
	/** 用户TOKEN为空 **/
	LOGIN_TOKEN_NULL("3102"),
	/** 参数无效 **/
	ARGUMENT_VALID_FAIL("3201"),
	/** 参数缺失 **/
	ARGUMENT_VALID_MISSING("3202"),
	/** 请求方式错误 **/
	REQ_METHOD_NOT_SUPPORTED("3203"),
	/** 网络异常 **/
	EXCEPTION("9999"),
	/** 响应消息正常**/
	RESPONSE_TRUE("ok"),
	/** 响应消息正常**/
	RESPONSE_FALSE("网络异常请稍后再试");

	private String code;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	private ResultCode(String code) {
		this.code = code;
	}

}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值