本帖最后由 小石姐姐 于 2018-6-29 18:12 编辑
1.关于自定义连接池的知识点:
连接池的概述:
连接池是创建和管理一个连接的缓冲池的技术,这些连接准备好被任何需要他们的线程使用.
连接池是装有连接的容器,使用连接的话,可以从连接池中进行获取,使之完成之后的将连接池归还给连接池
连接池的优点:
从内存中获取和归还的效率要远远高于创建和销毁的效率。(提升性能)。
自定义连接池:
1.编写一个类实现DataSource接口;
2.重写getConnection方法;
3.初始化多个连接在内存中;
4.编写归还连接的方法;
5.自定义连接池的实现代码;
自定义连接池的简单代码实现:
[Java] 纯文本查看 复制代码
public class MyDataSource implements DataSource {
// 将一些连接存入到内存中,可以定义一个集合,用于存储连接对象。
private List<Connection> connList = new ArrayList<Connection>();
// 在初始化的时候构造方法中提供一些连接
public MyDataSource() {
// 初始化连接:
for(int i = 1;i<=3;i++){
// 向集合中存入连接:
connList.add(JDBCUtils.getConnection());
}
}
// 从连接池中获得连接的方法
@Override
public Connection getConnection() throws SQLException {
Connection conn = connList.remove(0);
// 增强连接:
MyConnectionWrapper connWrapper = new MyConnectionWrapper(conn, connList);
return connWrapper;
}
// 编写一个归还连接的方法:
public void addBack(Connection conn){
connList.add(conn);
}
//(还有其他方法,不需要重写,直接调用父类)...
}
自定义连接池的问题及解决分析:
使用接口的实现类完成构造:
MyDataSource dataSource = new MyDataSource();
***这种方法不方便程序的扩展
额外提供归还连接的方法:
dataSource.addback();
解决这种问题的思路:
原来在Connection中是有一个close方法的,colse方法完成了连接的销毁。
现在要将原有的close方法的逻辑改为归还。(增强一个类中的方法)。
方法一:采用继承的方式:
继承的增强使用条件为:必须能够控制这个类的构造!!!
示例:
[Java] 纯文本查看 复制代码 class Man{
public void run(){
System.out.println(“跑…”);
}
}
class SuperMan extends Man{
public void run(){
System.out.println(“飞…”);
}
}
方法二:采用装饰者模式:
装饰者模式使用条件:
1.增强的类和被增强的类实现相同的接口
2.在增强的类中获得被增强的类的引用
示例:
[Java] 纯文本查看 复制代码 interface Waiter{
public void server();
}
public class Waitress implements Waiter{
public void server(){
System.out.println(“服务中…”);
}
}
public class WaitressWrapper implements Waiter{
private Waiter waiter;
public WaitressWrapper(Waiter waiter){
this.waiter = waiter;
}
public void server(){
System.out.println(“微笑…”)
waiter.server();
}
}
方法三:动态代理方式:(C3P0和Druid方法都是用的这种方法)
我的理解性总结:
1.SQL中JDBC中的Connection是接口,MySQL的Connection是SQL中Connection的实现类
2.自定义增强colse()方法,是对MySQL中的Connection进行的修改
3.SQL中的JDBC只是实行多种数据库和Java程序连接的一套规则
4.Druid和C3P0都是对MySQL中connection中close()方法的增强(修改)
5.Druid和C3P0都是用的动态代理的方式进行的close()方法的增强
6.DBUtils是对jdbc的一个封装,简化开发步骤,是一个工具类
2.关于Servlet中的知识点:
Servlet的执行流程:
1.localhost:8080/day09/ServletDemo1 ---> 从配置文件web.xml中找ServletDemo1
2.---> <servlet-mapping>下标签为:<url-pattern>/ServletDemo1</url-pattern>
3.---> <servlet-mapping>下标签为:<serclet-name>test1</servlet-name>
4.---> <servlet>下标签为:<servlet-name>test1</serclet-name>
5.---> <serclet>下标签为:<servlet-class>com.itheima.a_servlet.ServletDemo1</servlet-class>
6.---> 已经编写的ServletDemo1实现类
7.---> 通过重写的service方法,将内容传输到web页面
Servlet生命周期:Servlet从创建到销毁的过程.Servlet对象有且只有一个,单例的(必须自己会用自己的方式描述出来)
何时创建:用户第一次访问Servlet创建Servlet的实例:Serclet调用Init方法
何时销毁:当项目从服务器中移除的时候,或者关闭服务器的时候.结束Servlet服务器的时候调用destroy方法
1.用户第一次访问Servlet的时候,服务器会创建一个Servlet的实例,那么Servlet中init方法就会执行.
2.任何一次请求服务器都会创建一个新的线程访问Servlet中的service的方法.
在service方法内部根据请求的方式的不同调用doXXX的方法.(get请求调用doGet,post请求调用doPost).
3.当Servlet中服务器中移除掉,或者关闭服务器,Servlet的实例就会被销毁,那么destroy方法就会执行.
服务器的代码层次:EE典型的三层架构
web层/Controller层:
控制器的角色(流程的控制)具体业务分配给方法去完成
Servlet所在的层次
service层:业务逻辑层
各个方法:业务逻辑的具体的处理流程
如果涉及到数据库,调用Dao
Dao层:Data access Object数据访问层
和数据库进行交互
Servlet的实现关系:
HttpServlet --(继承)--> GenericeServlet:通用的Servlet(和协议无关) --(实现)--> Servlet:接口
编写一个类继承HttpServlet,重写HttpServlet的doGet和doPost方法
HttpServlet中的service方法先判断是什么方式提交的,在调用doGet或者doPost方法
用户登陆的小案例代码实现:
[Java] 纯文本查看 复制代码 public class UserServlet extends HttpServlet {
private static final long serialVersionUID = -1287011149634093674L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
resp.setContentType("text/html;charset=UTF-8")
// 1.接收表单提交的参数.
String username = req.getParameter("username");
String password = req.getParameter("password");
// 2.封装到实体对象中.
User user = new User();
user.setUsername(username);
user.setPassword(password);
// 3.调用业务层处理数据.
UserService userService = new UserService();
User existUser = userService.login(user);
// 4.根据处理结果显示信息(页面跳转).
if (existUser == null) {
resp.getWriter().println("<h1><font color='red'>登录失败</font></h1>");
}else{
resp.getWriter().println("<h1><font color='green'>登陆成功</font></h1>");
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
//UserServlet类
public class UserService {
public User login(User user) throws SQLException {
UserDao userDao = new UserDao();
return userDao.login(user);
}
}
//UserDao类
public class UserDao {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
public User login(User user) throws SQLException {
QueryRunner queryRunner = new QueryRunner(dataSource);
User user2 = queryRunner.query("select * from user where username = ? and password = ?",
new BeanHandler<User>(User.class),user.getUsername(),user.getPassword());
return user2;
}
}
3.关于JdbcUtils工具类的抽取,编写:
JdbcUtils工具类中提取一些常用的对象的方法:
[Java] 纯文本查看 复制代码
//创建一个用于提取的工具类:
public class JdbcUtils {
//在c3p0-config.xml文件配置好的情况下,通过此方法获取c3p0的DataSource的方法:
public static DataSource getC3P0DataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
return dataSource;
}
//获取Druid的DataSource的方法:
public static DataSource getDruidDataSource(){
Properties pp = new Properties();
DataSource dataSource = null;
try {
dataSource = DruidDataSourceFactory.createDataSource(pp);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
//获取用c3p0方式连接时的获取连接的方法:
public static Connection getC3P0Connection(){
Connection conn = null;
try {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
conn = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//获取用Druid方式连接时的获取连接的方法:
public static Connection getDruidConnection(){
Connection conn = null;
try {
Properties pp = new Properties();
pp.load(new FileInputStream("src/name.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(pp);
conn = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//资源释放的方法:(conn的close方法已经是增强过得了,是将连接存放会连接池的方法,不是销毁)
public static void release(Connection conn,Statement stmt){
JdbcUtils.release(conn, stmt,null);
}
public static void release(Connection conn,Statement stmt,ResultSet rs){
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
conn = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
stmt = null;
}
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
}
}
用DBUtils工具类对数据库的增删改查方法:
[Java] 纯文本查看 复制代码 public class DbUtils {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
@Test
public void showInsert() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
queryRunner.update("insert into account values(null,?,?)","huaye",12000);
}
@Test
public void showUpdate() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
queryRunner.update("update account set name = ?,money = ? where id = 1","mengjinghua",5000);
}
@Test
public void showDelete() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
queryRunner.update("delete from account where id = ?",1);
}
@Test
public void showSelectOne() throws SQLException {
QueryRunner queryRunner = new QueryRunner(dataSource);
Account account = queryRunner.query("select * from account where id = ?", new ResultSetHandler<Account>(){
@Override
public Account handle(ResultSet rs) throws SQLException {
Account account = new Account();
if (rs.next()) {
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getDouble("money"));
}
return account;
}
},1);
System.out.println(account);
}
@Test
public void showSelectAll() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
List<Account> list = queryRunner.query("select * from account", new ResultSetHandler<List<Account>>(){
@Override
public List<Account> handle(ResultSet rs) throws SQLException {
List<Account> list = new ArrayList<Account>();
while(rs.next()){
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getDouble("money"));
list.add(account);
}
return list;
}
});
System.out.println(list);
}
@Test
public void showArrayHandler() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
Object[] objs = queryRunner.query("select * from account where id = ?",new ArrayHandler(),1);
System.out.println(Arrays.toString(objs));
}
@Test
public void showArrayListHandler() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
List<Object[]> list = queryRunner.query("select * from account",new ArrayListHandler());
for (Object[] objects : list) {
System.out.println(Arrays.toString(objects));
}
}
@Test
/**
* 重点
*/
public void showBeanHandler() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
Account account = queryRunner.query("select * from account where id = ?",
new BeanHandler<Account>(Account.class),1);
System.out.println(account);
}
@Test
/**
* 重点
*/
public void showBeanListHandler() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
List<Account> list = queryRunner.query("select * from account",
new BeanListHandler<Account>(Account.class));
for (Account account : list) {
System.out.println(account);
}
}
@Test
public void showMapHandler() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
Map<String,Object> map = queryRunner.query("select * from account where id = ?", new MapHandler(),1);
System.out.println(map);
}
@Test
public void showMapListHandler() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
List<Map<String, Object>> list = queryRunner.query("select * from account",new MapListHandler());
for (Map<String, Object> map : list) {
System.out.println(map);
}
}
@Test
public void showColumnListHandler() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
List<Object> list = queryRunner.query("select name from account", new ColumnListHandler("name"));
for (Object object : list) {
System.out.println(object);
}
}
@Test
/**
* 重点
*/
public void showScalarHandler() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
Object obj = queryRunner.query("select count(*) from account", new ScalarHandler());
System.out.println(obj);
}
@Test
public void showKeyedHandler() throws SQLException{
QueryRunner queryRunner = new QueryRunner(dataSource);
Map<Object, Map<String, Object>> map = queryRunner.query("select * from account",new KeyedHandler("name"));
for (Object key: map.keySet()) {
System.out.println(key+"\t"+map.get(key));
}
}
}
|
|