1、添加jar包
在springMVC中使用json必须引入以下jar包,当然其他的一些包必不可少。
<!-- 引入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!--阿里fastjson包--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.18</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency>
前端页面请求:表单内标签
<li><label>账户:</label><input type="text" name="userId" id="userId" class="form-control" value=""></li>
$("#userId").change(function () { // alert("事件触发!"); var userId=$("#userId").val(); $.ajax({ // 向后台请求的url url:'/GXDC/user/selectID.do', // 向后台传的数据 data:{userId:userId}, // 该请求是否为异步 async:false, // 返回数据类型 dataType:"JSON", // 请求方法 type:"POST", // 请求成功响应后的处理 success:function (data) { console.log(data); if(data==true){ alert("该账户已经存在!"); flag=false; console.log("账户存在"); }else if (data==false){ if($("#userId").val().length>=5){ alert("该账户可以使用!"); flag=true; } console.log("账户不存在"); }else { flag=false; console.log("账户ajax验证出错!!"); } }, error:function () { console.log("ajax请求失败!") } }); });
后台接收请求:
需要在接受请求的对应方法前加@ResponseBody注解,
这个注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
当返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;
@ResponseBody @RequestMapping(value = "/selectID",method = RequestMethod.POST,produces ="test/plain;charset=UTF-8" ) public boolean selectUserId(String userId){ System.out.println("开始执行======================================================================>>>>>>"); // 查询数据库中是否有对应的userId即账户 String a=daoService.selectUserId(userId); System.out.println("return string=====================>>>>>>"+a); if (a!=null){ //如果有,返回true,不可以使用该账户 return true; }else{ //没有 返回false,可以使用该账户 return false; } }
mapper.xml文件中sql语句:
<!--查对应的用户名--> <select id="selectUserId" parameterType="String" resultType="String"> SELECT U_ID FROM ADMIN_USER WHERE 1=1 <if test="_parameter !='' and _parameter !=null"> AND BINARY U_ID=#{userId} </if> </select>