校园商铺-4店铺注册功能模块-12引入kaptcha实现验证码
1.导入验证码需要的依赖
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2.web.xml编写负责生成验证码的服务
<?xml version="1.0" encoding="UTF-8" ?>
<web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
metadata-complete="true">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- 新增代码:定义servlet,专门为Kaptche服务的,指定了Kaptche的样式字体 -->
<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!-- 定义验证码的样式 -->
<!-- 是否有边框 -->
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>no</param-value>
</init-param>
<!-- 字体颜色 -->
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>red</param-value>
</init-param>
<!-- 图片宽度 -->
<init-param>
<param-name>kaptche.image.width</param-name>
<param-value>135</param-value>
</init-param>
<!-- 使用那些字符生成验证码 -->
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>ACDEFHKPRSTWX345679</param-value>
</init-param>
<!-- 图片高度 -->
<init-param>
<param-name>kaptcha.image.height</param-name>
<param-value>50</param-value>
</init-param>
<!-- 字体大小 -->
<init-param>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>43</param-value>
</init-param>
<!-- 干扰线的颜色 -->
<init-param>
<param-name>kaptcha.noise.color</param-name>
<param-value>black</param-value>
</init-param>
<!-- 验证码的字符个数 -->
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<!-- 字体:宋体 -->
<init-param>
<param-name>kaptcha.textproducer.font.name</param-name>
<param-value>Arial</param-value>
</init-param>
</servlet>
<!-- 新增servlet-mapping,去响应Kaptche的请求 -->
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/Kaptcha</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<!-- 默认匹配所有的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.html引入验证码的控件,以html的形式将验证码生成出来
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SUI Mobile Demo</title>
<meta name="description"
content="MSUI: Build mobile apps with simple HTML, CSS, and JS components.">
<meta name="author" content="阿里巴巴国际UED前端">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<!-- Google Web Fonts -->
<link rel="stylesheet"
href="//g.alicdn.com/msui/sm/0.6.2/css/sm.min.css">
<link rel="stylesheet"
href="//g.alicdn.com/msui/sm/0.6.2/css/sm-extend.min.css">
<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "//hm.baidu.com/hm.js?ba76f8230db5f616edc89ce066670710";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
</head>
<body>
<div class="page-group">
<div id="page-label-input" class="page">
<header class="bar bar-nav">
<a class="button button-link button-nav pull-left back"
href="/demos/form"> <span class="icon icon-left"></span> 返回
</a>
<h1 class="title">商店信息</h1>
</header>
<div class="content">
<div class="list-block">
<ul>
<!-- 商铺名称 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">商铺名称</div>
<div class="item-input">
<input type="text" id="shop-name" placeholder="商铺名称">
</div>
</div>
</div>
</li>
<!-- 商铺分类 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">商铺分类</div>
<div class="item-input">
<select id="shop-category" placeholder="商铺分类">
<option data-id="">HELLO</option>
</select>
</div>
</div>
</div>
</li>
<!-- 区域分类 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">所属区域</div>
<div class="item-input">
<select id="area">
</select>
</div>
</div>
</div>
</li>
<!-- 详细地址 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">详细地址</div>
<div class="item-input">
<input type="text" id="shop-addr" placeholder="详细地址">
</div>
</div>
</div>
</li>
<!-- 联系电话 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">联系电话</div>
<div class="item-input">
<input type="text" id="shop-phone" placeholder="联系电话">
</div>
</div>
</div>
</li>
<!-- 缩略图 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">缩略图</div>
<div class="item-input">
<input type="file" id="shop-img">
</div>
</div>
</div>
</li>
<!-- 店铺简介 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">店铺简介</div>
<div class="item-input">
<textarea id="shop-desc" placeholder="店铺简介"></textarea>
</div>
</div>
</div>
</li>
<!-- 验证码 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">验证码</div>
<input type="text" id="j_kaptcha" placeholder="请输入验证码">
<div class="item-input">
<img id="captcha_img" alt="点击更换" title="点击更换"
onclick="changeVerifyCode(this)" src="../Kaptcha" />
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="content-block">
<div class="row">
<div class="col-50">
<!-- 点击返回,返回到店铺管理页 -->
<a href="#" class="button button-big button-fill button-danger">返回</a>
</div>
<div class="col-50">
<!-- -->
<a href="#" class="button button-big button-fill button-success"
id="submit">提交</a>
</div>
</div>
</div>
</div>
</div>
</div>
<script type='text/javascript'
src='//g.alicdn.com/sj/lib/zepto/zepto.min.js' charset='utf-8'></script>
<script type='text/javascript'
src='//g.alicdn.com/msui/sm/0.6.2/js/sm.min.js' charset='utf-8'></script>
<script type='text/javascript'
src='//g.alicdn.com/msui/sm/0.6.2/js/sm-extend.min.js' charset='utf-8'></script>
<script type='text/javascript' src='../resources/js/common/common.js'
charset="utf-8"></script>
<script type='text/javascript'
src='../resources/js/shop/shopoperation.js' charset="utf-8"></script>
</body>
</html>
4.编写common.js
js新建common目录,创建common.js文件。
function changeVerifyCode(img){
img.src="../Kaptcha?" + Math.floor(Math.random()*100);
}
5.shopoperation.js接收验证码
/**
*
*/
$(function(){
var initUrl = '/o2o/shopadmin/getshopinitinfo';//获取店铺的初始信息,还未定义
var registerShopUrl = '/o2o/shopadmin/registershop';//注册店铺
alert(initUrl);//调试弹窗,证明js文件被加载
getShopInitInfo();//调用方法
// 定义第一个方法getShopInitInfo:获取商铺分类、区域的列表信息
function getShopInitInfo(){
$.getJSON(initUrl,function(data){ //访问的URL,回调方法
if(data.success){ //true
var tempHtml = '';//存放店铺类别列表
var tempAreaHtml = '';//存放区域列表
data.shopCategoryList.map(function(item,index){//用map遍历店铺类别列表,生成如<option data-id="1">盖浇饭</option>的列表
tempHtml += '<option data-id="' + item.shopCategoryId + '">' +item.shopCategoryName + "</option>";
});
data.areaList.map(function(item,index){//用map遍历区域列表,生成如<option data-id="1">东苑</option>的列表
tempAreaHtml += '<option data-id="' + item.areaId + '">' + item.areaId + '</option>';
});
//完成遍历之后,将获取到的信息,塞进前台定义好的id里面 #是css的用法,代表id
$('#shop-category').html(tempHtml);
$('#area').html(tempAreaHtml);
}
});
//第二个方法:点击提交,获取到表单信息,通过ajax转发到后台
$('#submit').click(function(){//点击id为submit的空间,调用方法
var shop={};//json对象
//获取控件的信息
shop.shopName = $('#shop-name').val();
shop.shopAddr = $('#shop-addr').val();
shop.phone = $('#shop-phone').val();
shop.shopDesc = $('#shop-desc').val();
shop.shopCategory = {
shopCategoryId:$('#shop-category').find('option').not(function(){//返回被选中的
return !this.selected;
}).data('id')
};
shop.area = {
areaId:$('#area').find('option').not(function(){
return !this.selected;
}).data('id')
};
var shopImg = $('#shop-img')[0].files[0];
var formData = new FormData();//定义表单,用于接收
fromData.append('shopImg',shopImg);
formData.append('shopStr',JSON.stringify(shop));//将json转换成字符流
var verifyCodeActual = $('#j_captcha').val();
if(!verifyCodeActual){
$.toast('请输入验证码!');
return;
}
formData.append('verifyCodeActural', verifyCodeActural);
$.ajax({
url:registerShopUrl,
type:'POST',
data:formData,
contentType:false,//既要传文件,又要传文字,设为false
processData:false,
cache:false,
success:function(data){
if(data.success){
$.toast("提交成功!");
}else{
$.toast("提交失败:"+data.errMsg);
}
$('#captcha_img').click()
}
});
});
}
})
6.创建工具类,判断验证码是否符合预期
package com.csj2018.o2o.util;
import javax.servlet.http.HttpServletRequest;
public class CodeUtil {
public static boolean checkVerifyCode(HttpServletRequest request) {
String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
String verifyCodeActual = HttpServletRequestUtil.getString(request,"verifyCodeActual");
if(verifyCodeActual == null || !verifyCodeActual.equals(verifyCodeExpected)) {
return false;
}
return true;
}
}
7.将工具类引入店铺注册,做验证码比对
package com.csj2018.o2o.web.shopadmin;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.csj2018.o2o.dto.ShopExecution;
import com.csj2018.o2o.entity.PersonInfo;
import com.csj2018.o2o.entity.Shop;
import com.csj2018.o2o.enums.ShopStateEnum;
import com.csj2018.o2o.service.ShopService;
import com.csj2018.o2o.util.CodeUtil;
import com.csj2018.o2o.util.HttpServletRequestUtil;
import com.csj2018.o2o.util.ImageUtil;
import com.csj2018.o2o.util.PathUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
// 首先在Controller里面定义了SpringMVC相关的标签,这个标签包含了Controller的访问路径以及registerregisterShop方法的访问路径,
@Controller
@RequestMapping("/shopadmin")
public class ShopManagerController {
// 同时给它在执行的时候通过Spring容器注入之前实现好的ShopService实现类,用来提供addShop的服务。
@Autowired
private ShopService shopService;
@RequestMapping(value = "/registershop", method = RequestMethod.POST)
@ResponseBody
private Map<String, Object> registerShop(HttpServletRequest request) {
// 先定义一个返回值
Map<String, Object> modelMap = new HashMap<String, Object>();
if(!CodeUtil.checkVerifyCode(request)) {
modelMap.put("success", "false");
modelMap.put("message", "输入了错误的验证码");
return modelMap;
}
// 1.接收并转换相应的参数,包括店铺信息以及图片信息
// 获取请求头的店铺信息
String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
// 将json转换为Shop实例
ObjectMapper mapper = new ObjectMapper();
Shop shop = null;
try {
shop = mapper.readValue(shopStr, Shop.class);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMeg", e.getMessage());
return modelMap;
}
// 将请求中的文件流剥离出来,通过CommonsMultipartFile去接收
CommonsMultipartFile shopImg = null;
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
if (commonsMultipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
} else {
modelMap.put("success", false);
modelMap.put("errMsg", "上传图片不能为空");
return modelMap;
}
// 2.注册店铺
if (shop != null && shopImg != null) {
PersonInfo owner = new PersonInfo();
// 预期从Session获取,目前自定义,以后完善
owner.setUserId(1L);
shop.setOwner(owner);
// 由于addShop的第二个参数是File类型的,而传入的ShopImg是CommonsMultipartFile这样的一个类型,因此需要将CommonsMultipartFile转换成File类型
File shopImgFile = new File(PathUtil.getImgBasePath() + ImageUtil.getRandomFileName());
try {
shopImgFile.createNewFile();
} catch (IOException e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
return modelMap;
}
try {
inputStreamToFile(shopImg.getInputStream(), shopImgFile);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
return modelMap;
}
// 注册店铺
ShopExecution se;
try {
se = shopService.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
if (se.getState() == ShopStateEnum.CHECK.getState()) {
modelMap.put("success", true);
} else {
modelMap.put("success", false);
modelMap.put("errMsg", se.getStateInfo());
return modelMap;
}
return modelMap;
} catch (IOException e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
return modelMap;
}
} else {
modelMap.put("success", false);
modelMap.put("errMsg", "请输入店铺信息");
return modelMap;
}
}
private static void inputStreamToFile(InputStream inputStream, File file) {
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
throw new RuntimeException("调用inputStreamToFile产生异常:" + e.getMessage());
} finally {
try {
if (os != null) {
os.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
throw new RuntimeException("调用inputStreamToFile产生异常:" + e.getMessage());
}
}
}
}
页面效果: