一、安装与环境
1.idea中tomcat乱码:
a. file - settings - 搜File Encodings,改为utf-8
b.打开idea工作目录,在idea64.exe.vmoptions和idea.exe.vmoptions最后追加-Dfile.encoding=UTF-8
c.配置tomcat的页面中:VM option设置:-Dfile.encoding=UTF-8
2.热部署问题(jsp+java)
Update:更新操作(经我测试,很多时候无效)
Frame:idea失去焦点时触发
推荐选项:
Update:任意
Frame:update classes and resources
idea:热部署,如果是run启动,仅JSP等静态资源有效
如果是debug启动,java和jsp等均有效
总结 热部署:
a. Frame:update classes and resources
b. 以debug模式启动
注意:编写servlet前 需要先加入tomcat环境
3.JNDI:java命名与目录接口
pageContext < request< session< application(一个项目运行期间都有效)
String jndiName = "jndiValue" ;
abc 对象(资源....)
jndi:将某一个资源(对象),以配置文件(tomcat/conf/context.xml)的形式写入;
实现步骤:
tomcat/conf/context.xml配置:
<Environment name="jndiName" value="jndiValue" type="java.lang.String" />
jsp中用:
<%
Context ctx = new InitialContext() ;
String testJndi = (String)ctx.lookup("java:comp/env/jndiName");
out.print(testJndi);
%>
4.连接池
常见连接池:Tomcat-dbcp、dbcp、c3p0、druid
可以用数据源(javax.sql.DataSource)管理连接池
Tomcat-dbcp:
a.类似jndi,在context.xml中配置数据库
<Resource name="student" auth="Container" type="javax.sql.DataSource"
maxActive="400"
maxIdle="20" maxWait="5000" username="scott" password="tiger"
driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@127.0.0.1:1521:ORCL" />
b.在项目的web.xml中
<resource-ref>
<res-ref-name>student</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
c.使用数据源
更改 连接对象Connection的获取方式 :
传统Jdbc方式
connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
数据源方式:
Context ctx = new InitialContext() ;//context.xml
DataSource ds = (DataSource)ctx.lookup("java:comp/env/student") ;
connection = ds.getConnection();
tomcat-dbcp数据源总结: a.配置数据源(context.xml) b.指定数据源(web.xml) c.用数据源 :通过数据库获取Connection
5.dbcp连接池
连接池:
怎么用?
不用连接池
Class.forName();
Connection connection = DriverManager.getConnection();//连接指向数据库
用连接池的核心:将连接的指向改了,现在指向的是数据源 而不是数据库。
....-> DataSource ds = ....
Connection connection =ds.getConnection();//指向的是数据源的连接
数据库访问核心 -> pstmt/stmt ->connection ->1.直接数据库 2.数据源 ds.getConnection()
PreparedStatemnt pstmt = connection.preparedStatement();
commons-dbcp-1.4.jar、commons-pool.jar
dbcp获取ds: BasicDataSource、BasicDataSourceFactory