java代码的四层结构

java代码的四层结构_第1张图片

 一.util包:放共同类的包(整个项目中,可以共用的一些代码)
 例如:一些常用的字符串的非空验证,身份证或者电话号码的正则验证等等

1.JDBC类功能的封装

package util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * entity/pojo:实体类的包
 * dao:直接操作数据库的包(业务逻辑层和数据库持久化层的中间)
 * util:放共同类的包(整个项目中,可以共用的一些代码)
 * 例如:一些常用的字符串的非空验证,身份证或者电话号码的正则验证等等
 * service:业务逻辑层(对dao层再进行一次封装,相当于用来管理指挥dao层的) 
 *
 *一个重要的概念:单例模式(面试简答题):
 *	保证只有一个实例对象(主要针对数据库连接的对象)
 *步骤:
 *1.私有化构造方法(让别人不能直接new对象)
 *2.提供一个公共的访问方法(用来提供该类的唯一的一个对象)
 *-(必须有且仅有一个的静态变量)
 *
 *分支:饿汉模式/懒汉模式
 *饿汉模式:先把对象创建好,只等别人来调用
 *懒汉模式:等别人来调用的时候,再创对象
 */
public class ConfigManager {
	//一个静态的变量(该变量就是用来连接数据库的唯一对象)
	private static ConfigManager configManager 
					=new ConfigManager();//饿汉模式
	//加载以.properties结尾的配置文件的类
	private static Properties properties;
	//构造方法的作用:初始化数据(初始化database.preperties配置文件信息)
	private ConfigManager(){
		properties=new Properties();
		//数据库配置文件的名字/路径
		String configFile="database.properties";
		//通过当前ConfigManager这个类的路径来找到指定的configFile所表示的文件
		//并保存到输入流对象中
		InputStream is=ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
		try {
			properties.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				is.close();//关闭输入流
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	/**
	 * 该方法是公共的,用来返回该类中唯一的一个ConfigManager变量
	 * 
	 */
	public static ConfigManager getInstance(){
		//懒汉模式
		if(configManager==null){
			configManager=new ConfigManager();
		}
		return configManager;
		/**
		 * 该方法用来获取配置文件中的value值
		 */
		}
	
	public String getValue(String key){
		//根据方法中传入的key值来返回对应的value值
		return properties.getProperty(key);
	}//为什么这个方法加上静态
}

2.database.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/java2106?useUnicode=true&characterEncoding=UTF-8
user=root
pass=123456

二.实体类包

每一个要操作的实体对象都需要新建一个实体类

java代码的四层结构_第2张图片

三.Dao包

dao(Dept Access Object):数据存取对象专门存放操作数据库的文件
 注意:dao层中一般针对每一个表的存取操作都有一个对应的dao文件
 例如:操作dept表的,就可以专门有一个DeptDao的文件操作emp表的,就专门有一个EmpDao的文件
 dao层是位于业务逻辑层和持久化数据之间的一个层

1.baseDao

这里面提供了一种从database.properties配置文件中获取Connection对象的方法

和一种从centext.xml中获取Connection对象的方法

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import util.ConfigManager;


//基类:数据库操作通用类
public class BaseDao {
	protected Connection conn;
	protected PreparedStatement ps;
	protected Statement stmt;
	protected ResultSet rs;

	// 获取数据库连接
	public boolean getConnection() {
		// 读出配置信息
		String driver = ConfigManager.getInstance().getValue("driver");
		String url = ConfigManager.getInstance().getValue("url");
		String username = ConfigManager.getInstance().getValue("user");
		String password = ConfigManager.getInstance().getValue("pass");
		// 加载JDBC驱动
		try {
			Class.forName(driver);
			// 与数据库建立连接
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	// 获取数据库连接
	public boolean getConnection2() {
		try {
			/*
			import javax.naming.Context;
			import javax.naming.InitialContext;
			*/
			//初始化上下文
			Context cxt=new InitialContext();
			//获取与逻辑名相关联的数据源对象(拿数据源)
			DataSource ds=(DataSource)cxt.lookup("java:comp/env/jdbc/news");//jdbc/news逻辑名
			//从连接池索要连接
			conn=ds.getConnection();
		} catch (NamingException e) {
			e.printStackTrace();
			return false;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	// 增删改 delete from news_detail where id=? and title=?
	public int executeUpdate(String sql, Object[] params) {
		int updateRows = 0;
		if(getConnection()){
			try {
				ps=conn.prepareStatement(sql);
				//填充占位符
				for(int i=0;i

 每一个Dao类都只是一个接口,真正要实现这个 Dao类中的功能还需要一个实现类Impl

package dao;

import java.util.List;

import entity.Newsd;

public interface NewsdDao {
	public List selectAll();
	public List selectByCategoryId(int categoryId);
	public int insertNews(Newsd news);
	public int delNewsById(int id);
}
package dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import dao.BaseDao;
import dao.NewsDao;
import dao.NewsdDao;
import entity.News;
import entity.Newsd;


public class NewsdDaoImpl extends BaseDao implements NewsdDao{

		@Override
		public List selectAll() {
			String sql="select * from news_detail";
			Object[] params={};
			rs=executeSQL(sql,params);
			List list=new ArrayList();
			try {
				while(rs.next()){
					Newsd n=new Newsd();
					n.setId(rs.getInt("id"));
					n.setCategoryId(rs.getInt("categoryId"));
					n.setTitle(rs.getString("title"));
					n.setSummary(rs.getString("summary"));
					n.setContent(rs.getString("content"));
					n.setPicPath(rs.getString("picPath"));
					n.setAuthor(rs.getString("author"));
					n.setCreateDate(rs.getDate("createDate"));
					n.setMotifyDate(rs.getDate("modifyDate"));
					list.add(n);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			return list;
		}
		
		
		@Override
		public List selectByCategoryId(int categoryId) {
			String sql="select * from news_detail where categoryId=?";
			Object[] params={categoryId};
			rs=executeSQL(sql,params);
			List list=new ArrayList();
			try {
				while(rs.next()){
					Newsd n=new Newsd();
					n.setId(rs.getInt("id"));
					n.setCategoryId(rs.getInt("categoryId"));
					n.setTitle(rs.getString("title"));
					n.setSummary(rs.getString("summary"));
					n.setContent(rs.getString("content"));
					n.setPicPath(rs.getString("picPath"));
					n.setAuthor(rs.getString("author"));
					n.setCreateDate(rs.getDate("createDate"));
					n.setMotifyDate(rs.getDate("modifyDate"));
					list.add(n);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			return list;
		}	
		
		/*public static void main(String[] args) {
			NewsdDao nb=new NewsdDaoImpl();
			List list=nb.selectAll();
			System.out.println(list);
		}*/

	
		public int insertNews(Newsd news) {
			String sql="insert into news_detail(categoryId,title,summary,content,author,createDate)"+
					"values(?,?,?,?,?,?)";
			Object[] params={news.getCategoryId(),news.getTitle(),news.getSummary(),
					         news.getContent(),news.getAuthor(),news.getCreateDate()};
			int num=executeUpdate(sql,params);
			return num;
		}


		@Override
		public int delNewsById(int id) {
			String sql="delete from news_detail where id=?";
			Object[] params={id};
			int num=executeUpdate(sql,params);
			return num;
		}

	}

四.Service层

Service是一个业务逻辑层,相当于是Dao层的一个老板层,指挥每一个需要用到的Dao层中的功能,

同样的,Service层也有一个抽象类和一个实现类

java代码的四层结构_第3张图片

package service.impl;

import java.util.List;

import dao.NewsdDao;
import dao.impl.NewsdDaoImpl;
import entity.Newsd;
import service.NewsdService;

public class NewsdServiceImpl implements NewsdService{

	private NewsdDao newsdDao;
	public NewsdServiceImpl(){
		newsdDao=new NewsdDaoImpl();	
	}
	@Override
	public List selectAll() {
		// TODO Auto-generated method stub
		return newsdDao.selectAll();
	}
	@Override
	public List selectByCategoryId(int categoryId) {
		// TODO Auto-generated method stub
		return newsdDao.selectByCategoryId(categoryId);
	}
	@Override
	public int insertNews(Newsd news) {
		
		return newsdDao.insertNews(news);
	}
	@Override
	public int delNewsById(int id) {
		
		return newsdDao.delNewsById(id);
	}
	
	
}

你可能感兴趣的:(学习总结,java,javascript,tomcat)