当前位置: 首页 > 工具软件 > Dao Script > 使用案例 >

JSP通过ajax调用servlet,servlet调用service,service调用dao,dao调用数据库;然后数据库->dao->service->servlet-(json)->jsp

法玮
2023-12-01

一、Regist.jsp(Regist.jsp调用AccountExistsServlet)
1.获取前台传过来的username值,通过input[name=username]
2.将username传递给后台AccountExistsServlet并判断当前用户是否存在(前端把数据提交给后台通过json
3.后台返回flag,判断好值是否存在给用户一个友好的提示

  <%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
	String context = request.getContextPath();// /dt41_javaweb2
	String path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+context+"/";
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<base href="<%=path %>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link type="text/css" rel="stylesheet" href="resources/css/style.css" />
    <!--[if IE 6]>
    <script src="resources/js/easybuy/iepng.js" type="text/javascript"></script>
        <script type="text/javascript">
           EvPNG.fix('div, ul, img, li, input, a'); 
        </script>
    <![endif]-->    
    <script type="text/javascript" src="resources/js/easybuy/jquery-1.11.1.min_044d0927.js"></script>
	<script type="text/javascript" src="resources/js/easybuy/jquery.bxslider_e88acd1b.js"></script>
    
    <script type="text/javascript" src="resources/js/easybuy/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="resources/js/easybuy/menu.js"></script>    
        
	<script type="text/javascript" src="resources/js/easybuy/select.js"></script>
    
	<script type="text/javascript" src="resources/js/easybuy/lrscroll.js"></script>
    
    <script type="text/javascript" src="resources/js/easybuy/iban.js"></script>
    <script type="text/javascript" src="resources/js/easybuy/fban.js"></script>
    <script type="text/javascript" src="resources/js/easybuy/f_ban.js"></script>
    <script type="text/javascript" src="resources/js/easybuy/mban.js"></script>
    <script type="text/javascript" src="resources/js/easybuy/bban.js"></script>
    <script type="text/javascript" src="resources/js/easybuy/hban.js"></script>
    <script type="text/javascript" src="resources/js/easybuy/tban.js"></script>
    
	<script type="text/javascript" src="resources/js/easybuy/lrscroll_1.js"></script>
    
    
<title>尤洪</title>
</head>
<body>  
<!--Begin Header Begin-->
<div class="soubg">
	<div class="sou">
        <span class="fr">
        	<span class="fl">你好,请<a href="<%=path %>/pages/front/Login.jsp">登录</a>&nbsp; <a href="<%=path %>/pages/front/Regist.jsp" style="color:#ff4e00;">免费注册</a>&nbsp;</span>
            <span class="fl">|&nbsp;关注我们:</span>
            <span class="s_sh"><a href="#" class="sh1">新浪</a><a href="#" class="sh2">微信</a></span>
            <span class="fr">|&nbsp;<a href="#">手机版&nbsp;<img src="resources/images/s_tel.png" align="absmiddle" /></a></span>
        </span>
    </div>
</div>
<!--End Header End--> 
<!--Begin Login Begin-->
<div class="log_bg">	
    <div class="top">
        <div class="logo"><a href="Index.html"><img src="resources/images/logo.png" /></a></div>
    </div>
	<div class="regist">
    	<div class="log_img"><img src="resources/images/l_img.png" width="611" height="425" /></div>
		<div class="reg_c">
        	<form>
            <table border="0" style="width:420px; font-size:14px; margin-top:20px;" cellspacing="0" cellpadding="0">
              <tr height="50" valign="top">
              	<td width="95">&nbsp;</td>
                <td>
                	<span class="fl" style="font-size:24px;">注册</span>
                    <span class="fr">已有商城账号,<a href="<%=path %>/pages/front/Login.jsp" style="color:#ff4e00;">我要登录</a></span>
                </td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;用户名 &nbsp;</td>
                <td><input type="text" value="" class="l_user" name="username" placeholder="请输入2-12位数字字母下划线组合" pattern="\w{2,12}" required="required"/><span id="usernameTip"style="color:red  "></span></td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;密码 &nbsp;</td>
                <td><input type="password" value="" class="l_pwd" /></td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;确认密码 &nbsp;</td>
                <td><input type="password" value="" class="l_pwd" /></td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;邮箱 &nbsp;</td>
                <td><input type="text" value="" class="l_email" /></td>
              </tr>
              <tr height="50">
                <td align="right"><font color="#ff4e00">*</font>&nbsp;手机 &nbsp;</td>
                <td><input type="text" value="" class="l_tel" /></td>
              </tr>
              
              <tr height="50">
                <td align="right"> <font color="#ff4e00">*</font>&nbsp;验证码 &nbsp;</td>
                <td>
                    <input type="text" value="" class="l_ipt" />
                    <a href="#" style="font-size:12px; font-family:'宋体';">换一张</a>
                </td>
              </tr>
              <tr>
              	<td>&nbsp;</td>
                <td style="font-size:12px; padding-top:20px;">
                	<span style="font-family:'宋体';" class="fl">
                    	<label class="r_rad"><input type="checkbox" /></label><label class="r_txt">我已阅读并接受《用户协议》</label>
                    </span>
                </td>
              </tr>
              <tr height="60">
              	<td>&nbsp;</td>
                <td><input type="submit" value="立即注册" class="log_btn" /></td>
              </tr>
            </table>
            </form>
        </div>
    </div>
</div>
<!--End Login End--> 
<!--Begin Footer Begin-->
<div class="btmbg">
    <div class="btm">
        备案/许可证编号:蜀ICP备12009302号-1-www.dingguagua.com   Copyright © 2015-2018 尤洪商城网 All Rights Reserved. 复制必究 , Technical Support: Dgg Group <br />
        <img src="resources/images/b_1.gif" width="98" height="33" /><img src="resources/images/b_2.gif" width="98" height="33" /><img src="resources/images/b_3.gif" width="98" height="33" /><img src="resources/images/b_4.gif" width="98" height="33" /><img src="resources/images/b_5.gif" width="98" height="33" /><img src="resources/images/b_6.gif" width="98" height="33" />
    </div>    	
</div>
<!--End Footer End -->    

</body>
<script type="text/javascript">
   $("input[name=username]").blur(function(){
	   //alert("哈哈");
	   //1、获取username的值
	   //var username=$("input[name=username]").val();
	   //2、将username传递给后台判断当前的用户名是否存在
	   //这里实现只能用ajax
	   $.ajax({//前端去请求servlet
		   url:'<%=path%>/AccountExistsServlet',
		   type:'post',
		   data:{
			   username:$("input[name=username]").val() 
		   },    //前端把数据提交给后台通过json,注意ajax这里不需要添加双引号
		   dataType:'json',//是告诉ajax从Servlet中返回到jsp中ajax是什么数据类型
		   success:function(result){
			   var flag=result.flag;
			   //alert(flag);
			   if(flag){//用户名存在,则给用户一个友好的提示
				   $("#usernameTip").html("亲,此用户名已存在");
			   }else{
				   $("#usernameTip").html("");
			   }
		   }
	   });
   });
</script>

<!--[if IE 6]>
<script src="//letskillie6.googlecode.com/svn/trunk/2/zh_CN.js"></script>
<![endif]-->
</html>

二、AccountExistsServlet
1.jsp调用servlet用的是doGet方法
2.servlet获取ajax(jsp中)传递过来的信息
3.接下来servlet会调用service业务方法,通过Boolean类型判断username是否存在。
4.然后判断完之后,**再通过json方式给ajax(即jsp)
response.getOutputStream().write(json.toString().getBytes(“utf-8”));**返回
且jsp通过ajax里的json方式接收数据,放到result里面

 package cn.java.servlet;

import java.io.IOException;
import java.net.ResponseCache;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import cn.java.service.UserService;
import cn.java.service.impl.UserServiceImpl;

/**
 * Servlet implementation class AccountExistsServlet
 */
@WebServlet("/AccountExistsServlet")
public class AccountExistsServlet extends HttpServlet {
	private UserService us=new UserServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
			//1、获取ajax传递过来的参数信息
			String username=request.getParameter("username");
			//2、调用业务方法,判断username是否存在着
			boolean flag=us.isUserExists(username);
			//3、 给ajax(Regist.jsp)返回数据(必须是json类型),把flag封装成json
			JSONObject json=new JSONObject("{flag:"+flag+"}");//这里的json是个对象
			response.getOutputStream().write(json.toString().getBytes("utf-8"));//如何把字符串变成字节数组
		} catch (Exception e) { 
			e.printStackTrace();//try catch除了打印错误干不了别的,不能把错误解决掉
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

三、UserServiceImpl
1.写一个可以被AccountExistsServlet调用的Boolean类型的方法isUserExists(返回到servlet中是true或者false)
,然后在该方法中调用UserDaoImpl中的int类型的isUserExists方法

package cn.java.service.impl;

import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;

import cn.java.dao.UserDao;
import cn.java.dao.impl.UserDaoImpl;
import cn.java.service.UserService;
import cn.java.utils.JdbcUtils;

public class UserServiceImpl implements UserService{
   private UserDao ud=new UserDaoImpl();
   //判断指定的用户是否已经存在
   
    @Override
	public boolean isUserExists(String username) throws SQLException{
	      int num=ud.isUserExists(username);
	      if(num>=1){
	    	  return true;
	      }
          return false;
}
}
 

四、UserDaoImpl
1.dao层用来连接数据库,并且执行查询,然后结果是map类型的含num为整数的结果,然后通过Integer强制转换成int 类型,这样被service层调用容易判断

package cn.java.dao.impl;

import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;

import cn.java.dao.UserDao;
import cn.java.utils.JdbcUtils;

public class UserDaoImpl implements UserDao {
   private QueryRunner qr=new QueryRunner();
   //判断指定的用户是否已经存在
   /* (non-Javadoc)
 * @see cn.java.dao.impl.UserDao#isUserExists(java.lang.String)
 */
@Override
public int isUserExists(String username) throws SQLException{
	 Map<String,Object> mp=qr.query(JdbcUtils.getConnection(),
              "SELECT COUNT(*) AS num FROM `front_users` WHERE username='" + username + "'", new MapHandler());
	   return Integer.parseInt(mp.get("num")+"");
   }
}
 

 类似资料: