继续上次J2EE的学习,将新的一些知识点进行总结如下:
1:WEB开发中的四个域对象(在笔试和面试中比较常见,要熟悉它们四个的区别和对应的域范围,每个对象得生命周期,及其适用的情况)
(1)PageContext (称之为page域,是一种页对象,虽然它能够得到八种对象,但是用得其实并不多,因为在JSP中,那些对象其实在底层就已经被初始化了,所以没必要自己还重新去拿)
(2)ServletContext (称之为applictaion域,是属于一种全局对象,用得不多,所有的客户端都共享信息,注意同步,数据能不能取到,关键看是不是从同一个地方获取)
(3)HttpSession (称之为session域,用于比较常用的数据保存,,每次请求和响应都需要共享的数据,比如登录信息)
(4)ServletRequest (称之为request域,请求范围得数据,用的多,显示一次数据就没有用了,可以考虑把数据放到该范围中)
2:JSP中的页标签
(1)Page ,适用方式:<%@ Page ………………….%>,这个一般是放在JSP页面的最开始位置
(2)include , 适用方式:<%@ include file = ‘/2.jsp’ %> ,这个是一种静态包含标签,和JSP中的动态包含功能类似
(3)taglib ,适用方式:<%@ taglib %> ,这个是一种引用标签库,比如<%@ taglib uri=“http://java.sun.com/jsp/jstl/core” prefix=” c” %>
3.JSP常用的标签
(1)<jsp:include>标签,是一种动态包含标签
(2)<jsp:forward>标签,是一种请求转发标签,功能类似request对象的请求转发功能
(3)<jsp:param>标签,是一种添加请求参数的标签,类似于在地址URL中添加额外的参数传递一样。
4:JavaWeb的开发模型
(1)模型一;JavaBean+JSP,
这种模型很简单,适合简单项目的开发,不适合企业级开发
(2)模型二:MVC(Model + View + Controller)即,模型+视图+控制器
其中,Model表示:JavaBean
View表示:JSP显示
Controller表示:Servlet控制器
三层架构是分为:表现层,业务逻辑层,数据访问层,其中MVC主要就是在表现层的形式
5:EL表达式的作用
(1)对数据对象导航的支持 , 比如${user.name} ,其中的user是JavaBean中的一个类对象,name是类中的一个属性,这样就可以拿到类对象的属性的值
(2)对运算符的支持,比如${3+4} ,其中包括一元,二元,三元,比较运算,逻辑运算,对empty运算的支持,比如${empty list } ,其中list是一个集合,还可以判断对象是否为null
(3)EL中要对其中的11个隐式对象深刻的理解,与JSP中的进行区别。
(4)支持自定义函数功能(需要会自己定义和使用sun公司写好的)
6.自定义标签,这个内容需要熟练
这里就是注意一下,在写自定义标签函数的时候,在执行doTag()函数之前,需要先执行三个函数,分别是void setJspBody(….),和void setJspContext(…… .),和void setParent(……)
7:JSP实现自定义标签的步骤
(1)首先在JSP页面中进行设置你要自定义的标签名字,比如:<my:demo1>,但是注意一点,自定义的缩写不能是以JSP开头(比如其中的my)
(2)写一个tld的后缀XML文件,比如:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>my</short-name>
<uri>http://java.sun.com/myjstl</uri>
<tag>
<name>demo1</name>
<tag-class>com.hnu.scw.jstl.Demo1</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
解释一下:<taglib>开始标签前面都是必须的,在下面中的<uri>只有后面的是需要进行修改,比如/myjstl,这里是可以自己修改,而前面的是要一样就可以。
其中<tag>就是标签的意思,<name>就是标签的名字,和(1)中要对应,<tag-class>就是你的标签功能的类的路径+类名,<body-content>这是用来控制标签内容,如果不需要在标签中有内容就可以用empty,当然还有其他的格式。
(3)引用自定义标签。。在JSP页面中进行引用,比如
<%@ taglib uri = "http://java.sun.com/myjstl" prefix="my" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
解释一下:其中的<taglib>,意思就是引用,然后<uri>就是你之前在tld文件中进行设置的,必须一样,然后prefix属性就是你这个标签的开始部分的缩写,这个可以随便写,除了jsp之外,因为这个已经给Sun公司专属。好了,这就是所有的过程。是不是挺简单的。慢慢掌握,可以有开发出很多方便的标签内容的。
8:实现存储图片到MySQL数据库中,并且进行读取
/*
* 从数据库中读取图片的二进制内容
*/
public void readPictureContext() throws Exception{
// 获得链接对象
Connection conn = JdbcUtils.getConnection();
// 创建预处理命令对象
PreparedStatement pstmt = conn.prepareStatement("select * from t1");
// 执行sql语句
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
InputStream is = rs.getBinaryStream("image");
// 需要再建一个文件
File f = new File("src/b.jpg");
OutputStream os = new FileOutputStream(f);
byte[] bs = new byte[1024];
int b = 0;
while ((b = is.read(bs)) != -1) {
os.write(bs, 0, b);
}
//关闭资源
is.close();
os.close();
rs.close();
pstmt.close();
conn.close();
}
}
/*
* 将图片格式的文件写入到数据库(以二进制格式)
*/
public void writePictureContext() throws Exception{
//获得链接对象(这里就用了个工具类进行链接,之前已经写好了的)
Connection conn = JdbcUtils.getConnection() ;
//创建预处理命令对象
PreparedStatement pstmt = conn.prepareStatement("insert into t1 values(?,?)") ;
pstmt.setString(1, "1");
File file = new File("src/a.png");
InputStream io = new FileInputStream(file);
//注意这里要将第三个参数转为Int型,因为Mysql中不支持long型,否则会报错
pstmt.setBinaryStream(2, io , (int)file.length());
pstmt.executeUpdate();
//关闭数据流
io.close();
pstmt.close();
conn.close();
}
其中,上面的数据库很简单,就是两个字段,然后第一个就是varchar型的Id,第二个就是BLOB(用来存储二进制文件)类型的img字段
9:实现存储大文本数据到MySQL数据库中,并且进行读取
@Test
public void testSave() throws Exception{
//获得链接对象
Connection conn = JdbcUtils.getConnection() ;
//创建预处理命令对象
PreparedStatement pstmt = conn.prepareStatement("insert into t2 values(?,?)") ;
//指定?的值
pstmt.setInt(1, 1) ;
File file = new File("src/a.txt") ;
FileReader fr = new FileReader(file) ;
pstmt.setCharacterStream(2,fr,(int)file.length()) ;
//执行sql语句
pstmt.executeUpdate() ;
//释放资源
JdbcUtils.release(null, pstmt, conn) ;
}
@Test
public void testQuery() throws Exception{
//获得链接对象
Connection conn = JdbcUtils.getConnection() ;
//创建预处理命令对象
PreparedStatement pstmt = conn.prepareStatement("select * from t2") ;
//执行sql语句
ResultSet rs = pstmt.executeQuery() ;
if(rs.next()){
int id = rs.getInt("id") ;
Reader reader = rs.getCharacterStream("txt") ;
//需要再建一个文件
File f = new File("src/b.txt") ;
BufferedWriter bw = new BufferedWriter(new FileWriter(f)) ;
BufferedReader br = new BufferedReader(reader) ;
String s = "" ;
while((s = br.readLine()) != null){
bw.write(s) ;
bw.newLine() ;
}
br.close() ;
bw.close() ;
}
//释放资源
JdbcUtils.release(rs, pstmt, conn) ;
}
这个数据库也很简单,就是两个字段,一个字段为id,另外一个为txt类型的字段,用来存储大文本
10:在JSP中获取项目的路径
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
使用的话,就比如下面的这个ajax进行请求。(直接用<%=basePath%>即可,这个其实就是相当于$(pageContext.request.contextPath))
$.post("<%=basePath%>customer/delete.action",{"id":id},function(data){
alert("客户删除更新成功!");
window.location.reload();
});
11:自定义数据源(主要是对连接池的应用)
步骤:
(1)导入mysql连接的包
(2)编写数据库的配置文件properties
driverClass=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/使用的数据库
user=数据库账号
password=数据库密码
(3)编写数据库连接工具类
package com.hnu.scw.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
//专门用于数据库的工具类
public class JdbcUtils {
private static String driverClass = "" ;
private static String url = "" ;
private static String user = "" ;
private static String password = "";
static{
ResourceBundle rb = ResourceBundle.getBundle("dbcfg") ;
driverClass = rb.getString("driverClass") ;
url = rb.getString("url") ;
user = rb.getString("user") ;
password = rb.getString("password") ;
try {
Class.forName(driverClass) ;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url, user, password) ;
} catch (SQLException e) {
e.printStackTrace();
}
return null ;
}
public static void release(ResultSet rs ,Statement stmt,Connection conn){
if(rs != null){
try {
rs.close() ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close() ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close() ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
(4)编写自定义数据源类
package com.hnu.scw.pool;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;
import javax.sql.DataSource;
import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.Proxy;
import com.heima.utils.JdbcUtils;
public class MyDataDource implements DataSource{
//默认开始有10个数据库连接
private static LinkedList<Connection> pool = new LinkedList<Connection>() ;
static{
for (int i = 0; i < 10; i++) {
Connection conn = JdbcUtils.getConnection() ;
pool.add(conn) ;
}
}
@Override
public Connection getConnection() throws SQLException {
if(pool.size() > 0 ){
final Connection conn = pool.removeFirst() ; //右边: com.mysql.jdbc.Connection
//采用动态代理,主要是因为要解决当使用完连接之后,不能向之前使用connect一样,就直接关闭,而是应该将使用的放回到连接池中,这样来减少资源消耗(当然,不只这个方法,还可以通过包装类来实现,下面会额外说一下)
Connection ProxyConn = (Connection)Proxy.newProxyInstance(conn.getClass().getClassLoader(),
conn.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object arg0, Method method, Object[] args)
throws Throwable {
if(method.getName().equals("close")){
//不要关闭,而是放回池中,这是关键的地方
pool.add(conn) ;
return null ;
}
Object retVal = method.invoke(conn, args) ;
return retVal ;
}
}) ;
return ProxyConn;
}else
throw new RuntimeException("对不起,服务器忙") ;
}
//-----------------------------------------
@Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
(5)使用方式(Dao层)
package com.hnu.scw.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
import com.heima.pool.MyConnectionPool1;
import com.heima.pool.MyDataDource2;
import com.heima.utils.JdbcUtils;
//模拟使用自定义的数据源连接池
public class DaoImpl {
@Test
public void add(){
DataSource ds = new MyDataDource() ; ;
//拿到连接
Connection conn = null ;
PreparedStatement pstmt = null ;
try {
conn = ds.getConnection() ; //通过数据源去拿取连接
System.out.println(conn.getClass().getName());//这里打印出来的就是动态代理实现的连接
pstmt = conn.prepareStatement("") ;
//.......进行需要的业务操作
} catch (Exception e) {
e.printStackTrace() ;
}finally{
if(pstmt != null){
try {
pstmt.close() ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close() ; //一定要还回池中,此时需要改写close方法.就是动态代理的方法了
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
备注:上面提到的是通过动态代理的方式来解决,当使用完数据库连接之后的close方法的编写,这也就是为什么要使用连接池来管理连接对象,而不是向最初的时候,需要使用的时候就创建一个连接,那么大大的浪费资源了。此外,不只可以通过动态代理来实现,还可以通过包装类来实现,比如下面的方法:
方法一:通过包装类
package com.hnu.scw.pool;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
/**
* 采用包装类扩展已知类的功能
* 口诀:
* a. 写一个类,实现和被包装类相同的接口 (使他们具有相同的行为)
* b. 创建一个实例变量,引用被包装类对象 (最好做到与具体类无关)
* c. 编写一个构造函数,传入被包装类对象 (注入: DI)
* d. 对于需要改写的方法,写自己的代码
* e. 对于不需要改写的方法,引用被包装类的对象的对应方法即可
* @author scw
*
*/
public class MyConnection implements Connection{
private Connection conn ;
private LinkedList<Connection> pool ;
public MyConnection3(Connection conn,LinkedList<Connection> pool){
this.conn = conn ;
this.pool = pool ;
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return conn.prepareStatement(sql);
}
//重点就是重写这个close方法
@Override
public void close() throws SQLException {
//需要将连接还回池中
pool.addLast(conn) ;
}
//-------------------后面的还是采用本身的connection的方法即可,这里就不多写了------------------------------
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public Statement createStatement() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public String nativeSQL(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void commit() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void rollback() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void setCatalog(String catalog) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setHoldability(int holdability) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
// TODO Auto-generated method stub
}
@Override
public void setClientInfo(Properties properties)
throws SQLClientInfoException {
// TODO Auto-generated method stub
}
@Override
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
使用方法的话,就是将自定义的数据源中的获取到的connection,来转为上面写的类即可,比如:
@Override
public Connection getConnection() throws SQLException {
if(pool.size() > 0 ){
Connection conn = pool.removeFirst() ; //右边: com.mysql.jdbc.Connection
//采用包装类
MyConnection3 mconn = new MyConnection3(conn, pool) ;
return mconn ;
}else
throw new RuntimeException("对不起,服务器忙") ;
}
方法二:同样是通过包装类,但是运用适配器设计模式来实现
package com.hnu.scw.pool;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
/**
* 创建一个适配器
* 口诀:
* a. 写一个类,实现和被包装类相同的接口 (使他们具有相同的行为)
* b. 创建一个实例变量,引用被包装类对象 (最好做到与具体类无关)
* c. 编写一个构造函数,传入被包装类对象 (注入: DI)
* e. 对所有的方法方法,引用被包装类的对象的对应方法即可
* @author Administrator
*
*/
public class MyConenctionFirst implements Connection {
private Connection conn ;
public MyConenctionFirst(Connection conn) {
this.conn = conn ;
}
//不需要重写的方法,直接调用connection的方法即可,这里不多说,主要是关注close()方法
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return conn.prepareStatement(sql);
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return conn.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public Statement createStatement() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public String nativeSQL(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void commit() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void rollback() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void close() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void setCatalog(String catalog) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setHoldability(int holdability) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
// TODO Auto-generated method stub
}
@Override
public void setClientInfo(Properties properties)
throws SQLClientInfoException {
// TODO Auto-generated method stub
}
@Override
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
继承适配器类:
package com.hnu.scw.pool;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;
//让包装类继承适配器类
//只需要重写需要改写的方法即可
/**
* 创建一个适配器
* 口诀:
* a. 写一个类,继承适配器类 (使他们具有相同的行为)
* b. 创建一个实例变量,引用被包装类对象 (最好做到与具体类无关)
* c. 编写一个构造函数,传入被包装类对象 (注入: DI)
* e. 对需要改写的方法重写代码即可
* @author Administrator
*
*/
public class MyConnectionSecond extends MyConenctionFirst {
private Connection conn ;
private LinkedList<Connection> pool ;
public MyConnectionSecond(Connection conn,LinkedList<Connection> pool) {
super(conn) ;
this.pool = pool ;
}
//只需要重写close()方法即可,因为只有这里需要彼变化处理方式。
@Override
public void close() throws SQLException {
//将连接放回池中
pool.add(conn) ;
}
}
使用的话,还是和方法一一样:比如
@Override
public Connection getConnection() throws SQLException {
if(pool.size() > 0 ){
Connection conn = pool.removeFirst() ; //右边: com.mysql.jdbc.Connection
//采用包装类+适配器模式
MyConnectionSecond mconn = new MyConnectionSecond(conn, pool) ;
return mconn;
}else
throw new RuntimeException("对不起,服务器忙") ;
}
12:使用DBCP数据源
步骤:(1)导包
(2)编写properties文件,并且命令为dbcpconfig.properties
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/填写要使用的数据库
username=填写自己的mysql账号
password=填写自己的mysql密码
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=gbk
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=false
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
(3)编写DBCP工具类
package com.hnu.scw.utils;
import java.awt.image.DataBuffer;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DBCPUtils {
private static DataSource ds ;
static {
//将配置文件加载进来
InputStream in = DBCPUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties") ;
Properties props = new Properties() ;
try {
props.load(in) ;
ds = BasicDataSourceFactory.createDataSource(props) ;
} catch (Exception e) {
throw new RuntimeException("服务器忙") ;
}
}
//提供获取连接的方法
public static Connection getConnection(){
try {
return ds.getConnection() ;
} catch (SQLException e) {
throw new RuntimeException("服务器忙") ;
}
}
}
13:使用C3P0数据源
(1)导包
(2)编写xml文件,并且命名为:c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/填写要使用的数据库</property>
<property name="user">mysql账号</property>
<property name="password">mysql密码</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day16</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</named-config>
<named-config name="oracle">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day16</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</named-config>
</c3p0-config>
(3)编写C3P0工具类
package com.hnu.scw.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3p0Utils {
private static DataSource ds ;
static{
ds = new ComboPooledDataSource() ;
}
//提供获取连接的方法
public static Connection getConnection(){
try {
return ds.getConnection() ;
} catch (SQLException e) {
throw new RuntimeException("服务器忙") ;
}
}
}
14:Servlet3.0新特性中的异步处理———-(逐渐变Ajax的异步交互方式给替换)
package com.hnu.scw.java.async;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns={"/async"},asyncSupported=true)
public class AsyncServlet extends HttpServlet {
public void doGet(HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
// 设置响应类型及编码格式
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("马上开始:<br/>");
// 刷新缓冲区
response.getWriter().flush();
final AsyncContext context = request.startAsync(request, response);
context.start(new Runnable() {
@Override
public void run() {
try {
for (char ch = 'A'; ch <= 'Z'; ch++) {
response.getWriter().print(ch);
response.getWriter().flush();
Thread.sleep(250);
}
// 表示异步处理完毕
context.complete();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
内容会持续的进行更新的哦,,,下次会对JavaWeb中的框架进行整合哦。。欢迎大家的阅读和学习交流!!!!!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/12444.html