【设计模式】:Dao设计模式详解及一个简单的项目(AJAX+JSP+Servlet)

迫于课程结束,老师逼着让做课程设计,就简单花了一天的时间写了个使用dao设计模式的东西~ ~ ~顺带在这里讲解下dao设计模式


把写个这个东西的源代码放上来:

http://download.csdn.net/detail/u010800530/8273915

先画一个图,这个图可能能够完整表达出dao设计模式的意思,但是可以在下边通过代码看出来:


一、完成登陆功能(未设计AJAX,等到完成显示列表的时候我们做AJAX):

首先,我们建立一个项目TestJSP

然后,我们写一个login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

  </head>
  <body>
    <div  style="border: 1px solid #ccc;width:350;height:450;margin:auto auto;">
    <br>
        <center><h3>登陆界面</h3></center>
       <br><br>
       <br>
      <form method="post" name="Login" action="login" onSubmit="return login();">
       	<table>
       		<tr>
       			<td>用户名:<input type="text" id="username" name="username"/></td>
       		</tr>
       		<tr>
       			<td>密  码:<input type="password" id="password" name="password" /></td>
       		</tr>
       		<br>
       		<tr>
       			<td><input type="submit" name="Submit" value="提交" /></td>
       		</tr>
       	</table>
     </form>
     </div>
     
     <script type="text/javascript" >
     function login()
     {
   		
     	var name = document.getElementById("username").value;
     	var pwd = document.getElementById("password").value;
  		
     	if(name.length != 0 && pwd.length != 0){
     		return true;
     	}else{
     		alert("请输入姓名或者密码!");
     		return false;
     	}
  	}
     </script>
  </body>
</html>
多余的不用看,我们看表单提交选项,我们通过post方式提交表单到login

接下来,我们配置一下web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
		
<servlet>
  <servlet-name>acceptLogin</servlet-name>
  <servlet-class>com.cn.controller.LoginAction</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>acceptLogin</servlet-name>
  <url-pattern>/login</url-pattern>
</servlet-mapping>
  
  
  <servlet>
  	<servlet-name>listAction</servlet-name>
  <servlet-class>com.cn.controller.ListAction</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>listAction</servlet-name>
    <url-pattern>/list</url-pattern>
  </servlet-mapping>
  
  <servlet>
  	<servlet-name>deleteAction</servlet-name>
  <servlet-class>com.cn.controller.DeleteAction</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>deleteAction</servlet-name>
    <url-pattern>/deleteuser</url-pattern>
  </servlet-mapping>
  
</web-app>
我们看第一个servlet,第一个servlet的路径是/login,刚好对应login.jsp中的路径。这个servlet指向com.cn.controller.LoginAction.java类,我们把这个servlet类写出来:

package com.cn.controller;

import java.io.IOException;

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

import com.cn.dao.UserDao;
import com.cn.entity.User;
import com.cn.factory.DAOFactory;

public class LoginAction extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("gb2312");
		User user = null;
		String username = req.getParameter("username").toString();
  		String password = req.getParameter("password").toString();
  		
  		if(username == null || username.equals("")){
  			resp.sendRedirect("login.jsp");
  		}
  		
  		if(password == null || password.equals("")){
  			resp.sendRedirect("login.jsp");
  		}
  		
  		try {
  			UserDao dao = DAOFactory.getUserDAOInstance();   //标记1
			user = dao.queryByName(username);     //标记2
			if(user != null){
				System.out.println("user不为空");
				if((user.getPassword().trim()).equals(password.trim())){
					System.out.println("登陆成功");
					resp.sendRedirect("main.jsp");
				}else{
					System.out.println("密码错误");
	  				resp.sendRedirect("login.jsp");
				}
			}else{
				System.out.println("登陆失败");
  				resp.sendRedirect("login.jsp");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  		
	}
	
}
我们看下doPost()方法中的try....catch代码块,这里边我写了两个标记。我们先看标记1。

1、标记1

我们先建立UserDao.java接口:

package com.cn.dao;

import java.util.List;

import com.cn.entity.User;

public interface UserDao {
	public abstract boolean insert(User user) throws Exception;
	public abstract boolean deleteById(int userid) throws Exception;
	public abstract User queryByName(String name) throws Exception;
	public abstract User queryById(int userid) throws Exception;
	public abstract List<User> findAll() throws Exception;
}
并且对这个接口进行实现UserDaoImpl.java:

package com.cn.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.cn.dao.DataBaseConnection;
import com.cn.dao.UserDao;
import com.cn.entity.User;

public class UserDaoImpl implements UserDao {
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	public UserDaoImpl(Connection conn) {
		this.conn = conn;
	}
	
	public boolean deleteById(int userid) throws Exception {
		String sql = "delete  from users where id="+userid;
		try{
			this.pstmt = this.conn.prepareStatement(sql);
			int row = this.pstmt.executeUpdate();
			if(row>0){
				this.pstmt.close();
				this.conn.close();
				System.out.println("Dao删除成功");
				return true;
			}else{
				this.pstmt.close();
				this.conn.close();
				System.out.println("Dao删除失败");
				return false;
			}
		}catch(Exception e){
			e.printStackTrace();
			this.pstmt.close();
			this.conn.close();
			return false;
		}
		
	}

	public List<User> findAll() throws Exception {
		List<User> userList = new ArrayList<User>();
		User user = null;
		String sql = "select * from users";
		try
		{
			this.pstmt = this.conn.prepareStatement(sql);
			ResultSet rs = this.pstmt.executeQuery();
			while(rs.next()){
				user = new User();
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
				System.out.println(user.getId()+" "+user.getUsername()+" "+user.getPassword());
				userList.add(user);
			}
			this.pstmt.close();
			this.conn.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return userList;
	}

	public boolean insert(User user) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	public User queryById(int userid) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public User queryByName(String name) throws Exception {
		User user = null;
		String sql = "select * from users where username=?";
		try{
			this.pstmt = this.conn.prepareStatement(sql);
			this.pstmt.setString(1,name);
			ResultSet rs = this.pstmt.executeQuery();
			if(rs.next()){
				user = new User();
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
			}
			
			this.pstmt.close();
			this.conn.close();
		}catch(Exception e){
<pre name="code" class="java"><span style="white-space:pre">			</span>e.printStackTrace();
}return user;}}


在这个类中,我们看下构造方法,这个构造方法传入了一个Connection类型参数,通过这个参数,我们在对这个类进行实例化的时候就会打开对数据库的链接。并通过这个链接执行sql语句。

2、标记2

user = dao.queryByName(username)

这句代码中的queryByName(username)方法调用的是UserDaoProxy.java代理类中的方法,这个代理类是对UserDao接口。我们写下UserDaoProxy.java:

package com.cn.daoProxy;

import java.util.ArrayList;
import java.util.List;

import com.cn.dao.DataBaseConnection;
import com.cn.dao.UserDao;
import com.cn.dao.impl.UserDaoImpl;
import com.cn.entity.User;

public class UserDaoProxy implements UserDao {
	private DataBaseConnection dbc = null;
	private UserDao dao = null;
	

	public UserDaoProxy() {
		super();
		this.dbc = new DataBaseConnection();
		this.dao = new UserDaoImpl(this.dbc.getConnection());
	}

	public boolean deleteById(int userid) throws Exception {
		Boolean bo = this.dao.deleteById(userid);
		if(bo){
			return true;
		}
		else{
			return false;
		}
	}
	
	public List<User> findAll() throws Exception {
		List<User> userList = new ArrayList<User>();
		userList = this.dao.findAll();
		return userList;
	}

	public boolean insert(User user) throws Exception {
		
		return false;
	}

	public User queryById(int userid) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public User queryByName(String name) throws Exception {
		User user = null;
		try{
			user = this.dao.queryByName(name);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			dbc.close();
		}
		return user;
	}

}
写到这里,我忘了把实体类的代码贴出来了:User.java

package com.cn.entity;

public class User {
	private int id;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
}
然后,我们回到上边控制层的LoginAction.java,通过验证是否用户密码正确,判断可以登陆系统(这里没做拦截器)


二、完成列表显示(涉及到了AJAX)

当我们打开login.jsp,并输入用户名密码登陆之后,到了main.jsp页面,在这个页面我们要实现,打开这个页面的时候能够直接显示User表。

我们看下main.jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   	<title>用户管理操作界面</title>
	<script type="text/javascript" src="js/jquery-2.1.1.js"></script>
	<script type="text/javascript" src="js/main.js"></script>
	
  </head>
  
  <body>
  	<h2 style="margin-left:44%; margin-top:9%;">用户管理操作界面</h2>
  	<form style="margin-left:42%;">
	  	<input type="text" name="userid" style="width:60px;"><input type="submit" value="按Id查询" onclick="queryById()">
	  	<input type="text" name="username" style="width:60px;"><input type="submit" value="按姓名查询" onclick="queryByName()">
	</form>
   	<table cellpadding="1" border="1" style="margin-left:43%; text-align: center;">
   		<tr>
   			<td>Id</td>
   			<td>姓名</td>
   			<td>密码</td>
   			<td>操作</td>
   		</tr>
   	</table>
   	<div id="myDiv"></div>
  </body>
</html>
在这个页面,我们定义了一个table,并写了一个main.js,我们下边把main.js的代码贴上来:

//完成AJAX
$(function()
{
	var xmlhttp;
   	if(window.XMLHttpRequest){
    	xmlhttp=new XMLHttpRequest();
   	}else{
    	xmlhttp=new ActiveObject("Microsoft.XMLHTTP");
   	}
   	xmlhttp.onreadystatechange=function(){
    	if(xmlhttp.readyState==4 && xmlhttp.status==200){          
        	var data =xmlhttp.responseText; //接收到响应回来的text文本
			var datajson=eval("("+data+")"); //把String转换成json对象
			$.each(datajson.person,function(i,item){//对json对象进行解析
				//下边这些是把每条信息解析显示出来并添加到table中
				var $tr = $("<tr></tr>");
				var $td_1 = $("<td>"+item.id+"</td>");   
    			var $td_2 = $("<td>"+item.username+"</td>");    
    			var $td_3 = $("<td>"+item.password+"</td>"); 
    			var $td_4 = $("<input type='button' value='删除' onclick='deleteUser()' />" +
    						  "<input type='button' value='更新' onclick='updateUser()'/>");

    			var $parent = $("table");                         
   
   				$parent.append($tr);             
    			$tr.prepend($td_1);         
    			$tr.append($td_2);
    			$tr.append($td_3);
    			$tr.append($td_4);
			});
    	}
   	};  
   	xmlhttp.open("POST","list",true);
   	xmlhttp.send();
});
//删除方法
function deleteUser(){
	if (!confirm("确认删除?")) {
        window.event.returnValue = false;
    }else{
    	var val = 1; //val是要删除的id,这里因为懒,直接把数据写死了
    	window.location.href="deleteuser?userid="+val;
    }
}
//更新方法,懒没写
function updateUser(){
	alert("update");
}
//通过id查询,懒没写
function queryById(){
	
}
//通过name查询,懒没写
function queryByName(){
	alert(2);
}


通过AJAX,我们在页面刷新的时候提交一个请求,并且得到请求把相应的值用jquery添加到页面上边。

这是效果图,看起来是挺简单的:




















郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。