SpringMVC + MyBatis + Ajax+验证码

需要相关的jar包

jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>验证码</title>
<script type="text/javascript" src="js/jquery-3.1.0.min.js"></script>
<link href="css/index.css" rel="stylesheet">
    <script type="text/javascript"> 
	    function changeImg() { 
	        var imgSrc = $("#imgObj");
	        imgSrc.attr("src", chgUrl("code.html")); 
	    } 
	    function chgUrl(url) { 
	        var timestamp = (new Date()).valueOf(); 
	        if ((url.indexOf("&") >= 0)) { 
	            url = url + "×tamp=" + timestamp; 
	        } else { 
	            url = url + "?timestamp=" + timestamp; 
	        } 
	        return url; 
	    } 
	    
	    
	    $(function() {
	    	 //文本框点击事件
	    	 $("input[name='code']").blur(function(){
	    		 //发送ajax请求
	    		 $.ajax({
	    			 type:"POST",
	    			 url:"checkCode",
	    			 data:{
	    				 code:$("input[name='code']").val()
	    			 },
	    			 dataType:"json",
	    			 success:function(data){
	    				 //清空
	    				 $("#showRet").empty();
	    				 if(data.admin=="1"){
	    					 //将接收到的数据显示到文本框
	    				 	$("#showRet").text("验证码正确").css("color","black");
	    				 }else if(data.admin=="0"){
	     				 	$("#showRet").text("请输入验证码").css("color","red");
	    				 }else{
	    					 $("#showRet").text("验证码错误").css("color","red"); 
	    				 }
	    			 },
	    		 })
	    	 })
			
		})
	</script>
</head>
<body>
	<form action="toAccess" method="post">
		<div id="box">
			<ul>
				<li class="center">SpringMVC4.0 + MyBatis3.2 + 验证码</li>
			</ul>
			<ul>
				<li class="left">输入您的邮箱:<input type="text" name="sendto" value=""/></li>
			</ul>
			<ul>
				<li class="left">输入消息内容:<input type="text" name="content" value=""/></li>
			</ul>
			<ul>
				<li class="left">输入验证码吧:
				<input type="text" name="code" />
				<img id="imgObj" οnclick="javascript:changeImg()" src="code.html" />
				
				</li>
			</ul>
			<ul>
				<li class="left">后台返回数据:<input type="text" value="" readonly="readonly"/></li>
			</ul>
			<input type="submit" id="send" value="发送邮件" />
			<span id="showRet"></span>
		</div>
	</form>
    
</body>
</html>
CodeController页面

package com.cng.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CodeController {
	private int width = 90;//定义图片的width  
    private int height = 24;//定义图片的height  
    private int codeCount = 4;//定义图片上显示验证码的个数  
    private int xx = 15; 
    private int fontHeight = 18; 
    private int codeY = 18; 
    char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 
            'X', 'Y', 'Z', '0', '2', '3', '4', '5', '6', '7', '8', '9' }; 
 
    @RequestMapping("code") 
    public void getCode(HttpServletRequest req, HttpServletResponse resp) 
            throws IOException { 
 
    	// randomCode用于保存随机产生的验证码,以便用户登录后进行验证。  
        StringBuffer randomCode = new StringBuffer(); 
       
        
        // 定义图像buffer  
        BufferedImage buffImg = new BufferedImage(width, height, 
                BufferedImage.TYPE_INT_RGB); 
        Graphics gd = buffImg.getGraphics(); 
        // 创建一个随机数生成器类  
        Random random = new Random(); 
        // 将图像填充为白色  
        gd.setColor(Color.WHITE); 
        gd.fillRect(0, 0, width, height); 
 
        // 创建字体,字体的大小应该根据图片的高度来定。  
        Font font = new Font("Fixedsys", Font.BOLD, fontHeight); 
        // 设置字体。  
        gd.setFont(font); 
 
        // 画边框。  
        gd.setColor(Color.BLACK); 
        gd.drawRect(0, 0, width - 1, height - 1); 
 
        // 随机产生40条干扰线,使图象中的认证码不易被其它程序探测到。  
        gd.setColor(Color.BLACK); 
        for (int i = 0; i < 10; i++) { 
            int x = random.nextInt(width); 
            int y = random.nextInt(height); 
            int xl = random.nextInt(6); 
            int yl = random.nextInt(6); 
            gd.drawLine(x, y, x + xl, y + yl); 
        } 
        
        int red = 0, green = 0, blue = 0; 
 
        // 随机产生codeCount数字的验证码。  
        for (int i = 0; i < codeCount; i++) { 
            // 得到随机产生的验证码数字。  
            String code = String.valueOf(codeSequence[random.nextInt(34)]); 
            // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。  
            red = random.nextInt(255); 
            green = random.nextInt(255); 
            blue = random.nextInt(255); 
 
            // 用随机产生的颜色将验证码绘制到图像中。  
            gd.setColor(new Color(red, green, blue)); 
            gd.drawString(code, (i + 1) * xx, codeY); 
 
            // 将产生的四个随机数组合在一起。  
            randomCode.append(code); 
        } 
        // 将四位数字的验证码保存到Session中。  
        HttpSession session = req.getSession(); 
        //System.out.println(randomCode.toString());
        session.setAttribute("code", randomCode.toString()); 
        // 禁止图像缓存。  
        resp.setHeader("Pragma", "no-cache"); 
        resp.setHeader("Cache-Control", "no-cache"); 
        resp.setDateHeader("Expires", 0); 
 
        resp.setContentType("image/gif"); 
 
        // 将图像输出到Servlet输出流中。  
        ServletOutputStream sos = resp.getOutputStream(); 
        ImageIO.write(buffImg, "gif", sos); 
        sos.close(); 
    } 
    
    @RequestMapping("codeimg")
	public String codeimg(){
		return "codeimg";
	}
	
	@ResponseBody
	@RequestMapping("checkCode")
	public Map<String,String> checkCode(String code,HttpSession session){
		Map<String, String> adminMap = new HashMap<String,String>();
		String flag = "0";
				//toLowerCase()变小写
				//toUpperCase()变大写
				//(s1).equalsIgnoreCase(s2)忽略大小写比较
		if(code.equalsIgnoreCase(session.getAttribute("code").toString())){
			flag="1";
		}else if(code.length()==0){
			flag="0";
		}else{
			flag="-1";
		}
		adminMap.put("admin", flag);
		System.out.println("打印这句话说明,Ajax Asynchronous request 发送成功...");
		return adminMap;
	}
}
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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">
  <display-name>jd7</display-name>
  <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>
  
<!-- mybatis -->
  <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mybatis.xml</param-value>
	</context-param>
	<!-- 监听 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
  
<!-- springMVC -->  	
  <servlet>
  	<servlet-name>spring</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- ====================================== -->
  	<!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-servlet.xml</param-value>  默认
    </init-param> -->
    <!-- ====================================== -->
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
<servlet-mapping>
	<servlet-name>spring</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>  

 
  <!-- 编码过滤器 -->
  <filter>
		<filter-name>characterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
    	<filter-name>characterEncodingFilter</filter-name>
    	<url-pattern>/*</url-pattern>
  	</filter-mapping>
  	
  	
  

</web-app>



spring-servlet.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:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:p="http://www.springframework.org/schema/p"  
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    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
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
    <!-- 启用spring mvc 注解 -->
    <mvc:default-servlet-handler/>
    <!-- ****改包名**** --><!-- 设置使用注解的类所在的jar包 -->
    <context:component-scan base-package="com.jingdong.controller"/>
    <context:component-scan base-package="com.jingdong.service"/>
    <context:component-scan base-package="com.jingdong.dao"/>
	<mvc:annotation-driven/> 
	<!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->   
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    	p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
    
</beans> 





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章