在debug模式接收到验证码了但是接收的参数值依然为NULL

来源:3-5 前后端联调验证整体模块功能

慕无忌216588

2019-09-22 19:24:20

package com.study.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, "verifyCodeaActual");
		System.out.println("用户输入验证码:"+verifyCodeActual+" 后台实际验证码:"+verifyCodeExpected);
		if (verifyCodeActual == null || verifyCodeActual.equals(verifyCodeExpected)) {
			return false;
		}
		return true;
	}
}
package com.study.o2o.web.shopadmin;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.fasterxml.jackson.databind.ObjectMapper;
import com.study.o2o.dto.ShopExecution;
import com.study.o2o.entity.Area;
import com.study.o2o.entity.PersonInfo;
import com.study.o2o.entity.Shop;
import com.study.o2o.entity.ShopCategory;
import com.study.o2o.enums.ShopStateEnum;
import com.study.o2o.service.AreaService;
import com.study.o2o.service.ShopCategoryService;
import com.study.o2o.service.ShopService;
import com.study.o2o.util.CodeUtil;
import com.study.o2o.util.HttpServletRequestUtil;


@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {
	@Autowired
	private ShopService shopService;
	@Autowired
	private ShopCategoryService shopCategoryService;
	@Autowired
	private AreaService areaService;
	@RequestMapping(value = "/getshopinitinfo",method = RequestMethod.GET)
	@ResponseBody
	private Map<String,Object> getShopInitInfo(){
		Map<String, Object> modelMap = new HashMap<String, Object>();

		List<ShopCategory> shopCategoryList=new ArrayList<ShopCategory>();
		List<Area> areaList=new ArrayList<Area>();
		try {
			shopCategoryList=shopCategoryService.getShopCategoryList(new ShopCategory());
			areaList=areaService.getAreaList();
			modelMap.put("success", true);
			modelMap.put("shopCategoryList", shopCategoryList);
			modelMap.put("areaList", areaList);
		}catch(Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
		}

		return modelMap;
		
	}
	@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("errMsg", "输入了错误的验证码");
			return modelMap;
		}
		// 1.接收并转化相应的参数,包括店铺信息以及图片信息
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		ObjectMapper mapper = new ObjectMapper();
		Shop shop = null;
		try {
			shop = mapper.readValue(shopStr, Shop.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}
		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();
			owner.setUserId(1l);
			shop.setOwner(owner);
//			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 (IOException 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());
				}
			} 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 ins, File file) {
//		OutputStream os = null;
//		try {
//			os = new FileOutputStream(file);
//			int bytesRead = 0;
//			byte[] buffer = new byte[1024];
//			while ((bytesRead = ins.read(buffer)) != -1) {
//				os.write(buffer, 0, bytesRead);
//			}
//		} catch (Exception e) {
//			throw new RuntimeException("调用inputStreamToFile产生异常:" + e.getMessage());
//		} finally {
//			try {
//				if (os != null) {
//					os.close();
//				}
//				if (ins != null) {
//					ins.close();
//				}
//			} catch (IOException e) {
//				throw new RuntimeException("inputStreamToFile关闭io产生异常:" + e.getMessage());
//			}
//		}
//	}
}
/**
 * 
 */
$(function(){
	var initUrl="/o2o/shopadmin/getshopinitinfo";
	var registerShopUrl="/o2o/shopadmin/registershop";

	getShopInitInfo();
	//初始化方法
	function getShopInitInfo(){
		//获取java数据
		$.getJSON(initUrl,function(data){
			if(data.success){
				var tempHtml='';
				var tempAreaHtml='';
				data.shopCategoryList.map(function(item,index){
					tempHtml +='<option data-id="'+item.shopCategoryId+'">'
					+item.shopCategoryName+'</option>';
				});
				data.areaList.map(function(item,index) {
					tempAreaHtml +='<option data-id="'+item.areaId+'">'
					+item.areaName+'</option>';
				});
				$('#shop-category').html(tempHtml);
				$('#area').html(tempAreaHtml);
				
			}
			
			
		});
		//点击按钮提交表单
		$('#submit').click(function(){
			$.toast('提交中!');
			var shop={};
			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();
			formData.append('shopImg',shopImg);
			formData.append('shopStr',JSON.stringify(shop));
			var verifyCodeActual=$('#j_captcha').val();
			if(!verifyCodeActual){
				$.toast('请输入验证码!');
				return;
			}
			
			formData.append('verifyCodeActual',verifyCodeActual)
			$.ajax({
				url:registerShopUrl,
				type:'POST',
				data:formData,
				contentType:false,
				processData:false,
				ache:false,
				success:function(data){
					if(data.success){
						$.toast('提交成功!');
					}else{
						$.toast('提交失败!'+data.errMsg);
					}
					$.toast('3!');
					$('#captcha_img').click();
				}
			});
		});
	}

})
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	<!-- 配置SpringMVC -->
	<!-- 1.开启SpringMVC注解模式 -->
	<mvc:annotation-driven />
	<!--2.静态资源默认servlet配置 (1)1.加入对静态资源的处理:js,gif,png (2)允许使用“/”做整体映射 -->
	<mvc:resources mapping="/resources/**"
		location="/resources/" />
	<mvc:default-servlet-handler />
	<!-- 3.定义视图解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/html/" />
		<property name="suffix" value=".html" />
	</bean>
	<!-- 3.文件上传解析器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8" />
		<!-- 1024*1024*20=20M -->
		<property name="maxUploadSize" value="20971520" />
		<property name="maxInMemorySize" value="20971520" />
	</bean>
	<!--4扫描web相关的bean -->
	<context:component-scan
		base-package="com.study.o2o.controller" />
	<context:component-scan
		base-package="com.study.o2o.web" />
</beans>

spring-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">
	<display-name>Archetypecosk</display-name>
	
		
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
        <servlet-name>Kaptcha</servlet-name>
        <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
        <!-- 定义Kaptch样式 是否有边框 这里为 无 -->
        <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>black</param-value>
        </init-param>
        <!-- 图片宽度 -->
        <init-param>
            <param-name>kaptcha.image.width</param-name>
            <param-value>105</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>35</param-value>
        </init-param>
        <!-- 字体大小 -->
        <init-param>
            <param-name>kaptcha.textproducer.font.size</param-name>
            <param-value>30</param-value>
        </init-param>
        <!-- 干扰线的颜色,验证码的背景 黑色-->
        <init-param>
            <param-name>Kaptcha.noise.color</param-name>
            <param-value>black</param-value>
        </init-param>
        <!-- 字符个数 4个-->
        <init-param>
            <param-name>kaptcha.textproducer.char.length</param-name>
            <param-value>4</param-value>
        </init-param>
        <!-- 字体 宋体-->
        <init-param>
            <param-name>Kaptcha.testproducer.font.names</param-name>
            <param-value>Arial</param-value>
        </init-param>
 </servlet>
    <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/spring-*.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring-dispatcher</servlet-name>
		<!--  		默认匹配所有的请求-->
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

web.xml

http://img.mukewang.com/climg/5d8757050934a06802800052.jpgjar包也引入了

<!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">

<link rel="apple-touch-icon-precomposed"
	href="/assets/img/apple-touch-icon-114x114.png">

<script>
	//ga
</script>
<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>
						<!-- Text inputs -->
						<li>
							<div class="item-content">
								<div class="item-inner">
									<div class="item-title label">商铺名称</div>
									<div class="item-input">
										<input id="shop-name" type="text" 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">
										</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>
						<!--  详细地址 text-->
						<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>
						<!--  联系电话 text-->
						<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">缩略图a</div>
									<div class="item-input">
										<input type="file" id="shop-img" placeholder="缩略图">
									</div>
								</div>
							</div>
						</li>
						<!-- 店铺简介 textarea-->
						<li class="align-top">
							<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>
						<!--  验证码 kaptcha-->
						<li>
							<div class="item-content">
								<div class="item-inner">
									<div class="item-title label">验证码</div>
									<div class="item-input">
										<input type="text" id="j_captcha" placeholder="验证码">
									</div>
										<div class="item-input">
										<img id="captcha_img" alt="点击更换" src="../Kaptcha" onclick="changeVerifycody(this)">
									</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>


写回答

1回答

好帮手慕阿满

2019-09-23

同学你好,问一下同学说的debug模式接收到验证码是指哪一步接收到验证码呢?接收的参数值依然为NULL是指哪一点的接收值呢?建议同学截图表示一下。

祝:学习愉快~

0

0 学习 · 8263 问题

查看课程