jsp之jstl
jstl:
jsp标准的标签库语言,apache的,是用来替代java脚本
使用步骤:
1.导入jar包 (jstl.jar和standard.jar)
2.在页面上导入标签库
<%@taglib prefix="" uri=""%>
例如: <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
jstl的分类:
core:核心类库 ★
fmt:格式化|国际化
xml:过时了
sql:过时了
函数库:很少使用
core:掌握
★c:if
★c:forEach
c:set 往域中设置值
c:choose c:when c:otherwise 分支
★c:if 判断
<c:if test="${el表达式}">满足的时候输出的内容</c:if>
例如:
<c:if test="${3>4 }">
3大于4
</c:if>
<c:if test="${3<=4 }">
3不大于4
</c:if>
案例--c:if:
cif.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>c:if指令</title>
</head>
<body>
<c:if test="${3>4 }">
3大于4
</c:if>
<c:if test="${3<=4 }">
3小于4
</c:if>
</body>
</html>
浏览器访问以下url,页面显示:
c:forEach 循环
格式1:
<c:forEach begin="从那里开始" end="到那里结束" step="步长" var="给变量起个名字" varStatus="循环状态变量">
${i }--${vs.count }--${vs.current }<br>
</c:forEach>
varStatus:用来记录循环的状态
常用的属性:
count:记录次数
current:当前遍历的内容
例如:
<c:forEach begin="1" end="20" step="2" var="i" varStatus="vs">
${i }--${vs.count }--${vs.current }<br>
</c:forEach>
案例1---forEach格式一:forEach1.jsp
forEach1.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>forEach指令</title>
</head>
<body>
<c:forEach begin="1" end="10" var="i" step="1" varStatus="vs" >
${i }---${vs.count }---${vs.current }<br>
</c:forEach>
</body>
</html>
访问页面,显示如下:
forEach格式2:
<c:forEach items="${el获取域中的容器}" var="n">
${n }
</c:forEach>
例如:
//遍历list
<c:forEach items="${list }" var="n">
${n }
</c:forEach>
//遍历map
<c:forEach items="${map }" var="en">
${en.key }-- ${en.value }<br/>
</c:forEach>
案例forEach格式2:forEach2.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>forEach指令</title>
</head>
<body>
<%
//1、往request域中放入一个list集合
List list = new ArrayList();
list.add("111");
list.add("222");
list.add("333");
request.setAttribute("list", list);
//2、往request域中放入一个set集合
Set set = new HashSet();
set.add("111");
set.add("222");
set.add("333");
request.setAttribute("set", set);
//2、往request域中放入一个map集合
Map map = new HashMap();
map.put("username","hjh");
map.put("password","12345");
request.setAttribute("map", map);
%>
<%-- 1、遍历lilst--%>
<c:forEach items="${list }" var="list">
${list }
</c:forEach>
<hr>
<%-- 2、遍历set --%>
<c:forEach items="${set }" var="set" varStatus="vs">
${set }--${vs.count }<br>
</c:forEach>
<hr>
<c:forEach items="${map }" var="map">
${map.key }--${map.value }<br>
</c:forEach>
</body>
</html>
访问浏览器,页面显示如下:
扩展:
c:set 和 c:choose
函数库:
案例1---c:set 和 c:choose
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>c:set指令</title>
</head>
<body>
<%--c:set如果有value属性,标签对中就不能再设置body,不然会报错 --%>
<c:set var="day" value="2" />
<c:choose>
<c:when test="${day==1 }">周一</c:when>
<c:when test="${day==2 }">周二</c:when>
<c:when test="${day==3 }">周三</c:when>
<c:otherwise>其他</c:otherwise>
</c:choose>
</body>
</html>
启动tomcat,浏览器中输入url,回车:
案例2---函数库:
function.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>函数库</title>
</head>
<body>
${fn:toUpperCase("hello") }
</body>
</html>
启动tomcat,浏览器输入以下url,页面内容显示如下:
案例一:显示所有的商品
数据库的初始化操作:
create database hjh;
use hjh;
create table product(
id int primary key auto_increment,
pname varchar(20),
price double,
pdesc varchar(20)
);
insert into product values (null,'电视机',3200,'液晶曲面大电视');
insert into product values (null,'韭菜盒子',3,'味重请小心食用');
insert into product values (null,'益达',10,'韭菜伴侣');
insert into product values (null,'十三香',12,'守义牌');
步骤分析:
新建一个项目
导入jar包:
驱动 dbutils c3p0 jstl
导入c3p0配置文件 和工具类
实体类:
private int id;
private String pname;
private double price;
private String pdesc;
2.index.jsp中添加一个连接
<a href="/day1201/findAll">展示所有商品</a>
3.FindAllServlet:
调用ProductService.findAll() 返回一个集合 List<Product>
将list放入request域中
请求转发到product_list.jsp
4.ProductService.findAll() 调用dao.findAll()
5.dao.findAll() 使用beanListHandler()
6.在product_list.jsp展示所有商品
使用 c:forEach
使用javabean导航获取里面的数据
项目结构:
web.xml配置
<servlet>
<servlet-name>FindAllServlet</servlet-name>
<servlet-class>com.hjh.servlet.FindAllServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FindAllServlet</servlet-name>
<url-pattern>/findAll</url-pattern>
</servlet-mapping>
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/findAll">展示所有商品</a>
</body>
</html>
product_list.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>商品展示页面</title>
</head>
<body>
<table border="1px solid #96c2f1" background="#eff7ff" align="center">
<tr>
<td>id</td>
<td>商品名称</td>
<td>单价</td>
<td>描述</td>
</tr>
<c:forEach items="${list }" var="product">
<tr>
<td>${product.id }</td>
<td>${product.pname }</td>
<td>${product.price }</td>
<td>${product.pdesc }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
c3p0-config.xml
<c3p0-config>
<!-- 默认配置,如果没有指定则使用这个配置 -->
<default-config>
<!-- 基本配置 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost/hejh?characterEncoding=UTF-8 </property>
<property name="user">root</property>
<property name="password">root</property>
<!--扩展配置-->
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!-- 命名的配置 -->
<named-config name="XXX">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/xxxx</property>
<property name="user">root</property>
<property name="password">1234</property>
<!-- 如果池中数据连接不够时一次增长多少个 -->
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">20</property>
<property name="minPoolSize">10</property>
<property name="maxPoolSize">40</property>
<property name="maxStatements">20</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
DataSourseUtils.java
package com.hjh.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DataSourseUtils {
//建立连接池ds
private static ComboPooledDataSource ds = new ComboPooledDataSource();
//获取数据源
public static DataSource getDataSourse() {
return ds;
}
//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void closeResourse(Connection conn,Statement st) {
try {
if(st!=null) {
st.close();
}else {
st = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) {
conn.close();
}else {
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**释放资源closeResourse(conn,ps)*/
public static void closeResourse(Connection conn,PreparedStatement ps) {
try {
if(ps!=null) {
ps.close();
}else {
ps = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) {
conn.close();
}else {
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**释放资源closeResourse(rs)*/
public static void closeResourse(ResultSet rs) {
try {
if(rs!=null) {
rs.close();
}else {
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
FindAllServlet.java
package com.hjh.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hjh.bean.Product;
import com.hjh.service.ProductService;
/**
*展示所有商品
*/
public class FindAllServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、调用service,返回list
List<Product> list = null;;
try {
list = new ProductService().findAll();
} catch (SQLException e) {
e.printStackTrace();
}
//2、将list放入request域中
request.setAttribute("list", list);
//3、请求转发
request.getRequestDispatcher("/show/product_list.jsp").forward(request, response);
//response.sendRedirect(request.getContextPath()+"/show/product_list.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
ProductService.java
package com.hjh.service;
import java.sql.SQLException;
import java.util.List;
import com.hjh.dao.ProductDao;
public class ProductService {
public List findAll() throws SQLException {
return new ProductDao().findAll();
}
}
ProductDao.java
package com.hjh.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.hjh.bean.Product;
import com.hjh.util.DataSourseUtils;
public class ProductDao {
public List<Product> findAll() throws SQLException {
//创建queryRunner
QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
//编写sql
String sql = "select * from product";
//执行sql
return qr.query(sql, new BeanListHandler<Product>(Product.class));
}
}
Product.java
package com.hjh.bean;
public class Product {
private int id;
private String pname;
private double price;
private String pdesc;
public Product() {}
public Product(int id,String pname,double price,String pdesc) {
this.id = id;
this.pname = pname;
this.price = price;
this.pdesc = pdesc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
}
案例2-重写登录案例
需求:
在页面上填写用户名和密码及验证码,点击提交,先校验验证码是否一致.若一致后再去找数据库.顺便记住用户名
技术:
表单
验证码
servlet
request
session
cookie
步骤分析:
1.数据库和表
create table user(
id int primary key auto_increment,
username varchar(20),
password varchar(20)
);
2.创建一个项目
包结构
jar包
工具类和配置文件
3.表单 login.jsp
4.表单提交 loginServlet
loginServlet:
获取验证码(从前台传过来和session中)
判断两个验证码是否一致
若不一致:
填写错误信息,请求转发到login.jsp
若一致:获取用户名和密码
调用userService的getuserbyusernameandpassword 返回值 User user
判断user是否为空
若为空:填写错误信息,请求转发到login.jsp
若不为空:
继续判断是否勾选了记住用户名
若勾选:
创建cookie 将用户名放入cookie写回浏览器
将user对象放入session中
页面重定向 index.jsp 展示 xxx:欢迎回来
项目结构:
数据库数据:
eclipse项目结构:
web.xml配置:
<servlet>
<servlet-name>CodeServlet</servlet-name>
<servlet-class>com.login.CodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CodeServlet</servlet-name>
<url-pattern>/code</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.login.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${user.username }:欢迎回来!
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/login" method="post">
会员登录:<span width="20px" heigth="30px"><font color="red">${sessionScope.msg }</font></span><br>
用户名:<input type="text" name="username" value="${cookie.saveName.value }"><br>
密码:<input type="password" name="password"><br>
验证码:<input type="text" placeholder="请输入验证码" name="checkCode">
<img alt="验证码" src="${pageContext.request.contextPath }/code" title="看不清,换一张" οnclick="changeImg(this)"><br>
<input type="submit" value="登录">
<input type="checkbox" name="saveName" value="ok">记住用户名
</form>
</body>
<script type="text/javascript">
function changeImg(obj){
//操作src属性
obj.src="/Jsp/code?i="+Math.random();
}
</script>
</html>
LoginServlet.java
package com.login;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
//设置编码
request.setCharacterEncoding("utf-8");
//接收生成和用户输入的2个验证码
String uCode = request.getParameter("checkCode");//用户输入的验证码
String sCode = (String) request.getSession().getAttribute("securityCode");//代码生成的验证码
System.out.println(sCode);
System.out.println(uCode);
//一次性验证码用完以后,页面刷新就会失效,所以要移除
//request.getSession().removeAttribute("securityCode");
//比较2个验证码是否一致
if(uCode==null||uCode.trim().length()==0||sCode==null) {
//验证码输入或生成有问题,提示后,跳转到login.jsp页面
request.getSession().setAttribute("msg", "请重新输入验证码");
request.getRequestDispatcher("/login/login.jsp").forward(request, response);
return ;
}else if(uCode.equalsIgnoreCase("sCode")){
//验证码不一致
request.getSession().setAttribute("msg", "验证码输入错误");
request.getRequestDispatcher("/login/login.jsp").forward(request, response);
return ;
}
//获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//调用userService getUserByUsernameAndPassword(),返回user
User user=null;
try {
user = new UserService().getUserByUsernameAndPassword(username,password);
} catch (SQLException e) {
e.printStackTrace();
}
//判断user
if(user==null) {
//若user为空,提示用户,然后跳转到login.jsp
request.getSession().setAttribute("msg", "用户名和密码不对");
request.getRequestDispatcher("/login/login.jsp").forward(request, response);
return;
}else {
//若用户不为空,判断是否记住用户名,将username放入session中
if("ok".equals(request.getParameter("saveName"))) {
//创建cookie,username不能为中文
Cookie cookie = new Cookie("saveName",username);
cookie.setPath(request.getContextPath()+"/");
cookie.setMaxAge(3600);
//写回浏览器
response.addCookie(cookie);
}
request.getSession().setAttribute("user", user);
}
//页面重定向到index.jsp
request.getRequestDispatcher("/login/index.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doGet(request, response);
}
}
CodeServlet.java
package com.login;
import javax.servlet.http.HttpServlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
// 使用java图形界面技术绘制一张图片
int charNum = 4;
int width = 30 * 4;
int height = 30;
// 1. 创建一张内存图片
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 2.获得绘图对象
Graphics graphics = bufferedImage.getGraphics();
// 3、绘制背景颜色
graphics.setColor(Color.YELLOW);
graphics.fillRect(0, 0, width, height);
// 4、绘制图片边框
graphics.setColor(Color.BLUE);
graphics.drawRect(0, 0, width - 1, height - 1);
// 5、输出验证码内容
graphics.setColor(Color.RED);
graphics.setFont(new Font("宋体", Font.BOLD, 20));
// 随机输出4个字符
Graphics2D graphics2d = (Graphics2D) graphics;
String s = "ABCDEFGHGKLMNPQRSTUVWXYZ23456789";
Random random = new Random();
//session中要用到
String msg="";
int x = 5;
for (int i = 0; i < 4; i++) {
int index = random.nextInt(32);
String content = String.valueOf(s.charAt(index));
msg+=content;
double theta = random.nextInt(45) * Math.PI / 180;
//让字体扭曲
graphics2d.rotate(theta, x, 18);
graphics2d.drawString(content, x, 18);
graphics2d.rotate(-theta, x, 18);
x += 30;
}
//将验证码放入session域中
request.getSession().setAttribute("securityCode",msg);
// 6、绘制干扰线
graphics.setColor(Color.GRAY);
for (int i = 0; i < 5; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1, y1, x2, y2);
}
// 释放资源
graphics.dispose();
// 图片输出 ImageIO
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doGet(request, response);
}
}
UserService.java
package com.login;
import java.sql.SQLException;
public class UserService {
public User getUserByUsernameAndPassword(String username, String password) throws SQLException {
return new UserDao().getUserByUsernameAndPassword(username, password);
}
}
UserDao.java
package com.login;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.hjh.util.DataSourseUtils;
public class UserDao {
public User getUserByUsernameAndPassword(String username, String password) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
String sql = "select * from user where username=? and password=?";
return qr.query(sql, new BeanHandler<>(User.class),username,password) ;
}
}
user.java
package com.login;
public class User {
private String id;
private String username;
private String password;
public User() {}
public User(String id,String username,String password) {
this.id = id;
this.username = username;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String 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;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
DataSourseUtils.java
package com.hjh.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DataSourseUtils {
//建立连接池ds
private static ComboPooledDataSource ds = new ComboPooledDataSource();
//获取数据源
public static DataSource getDataSourse() {
return ds;
}
//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void closeResourse(Connection conn,Statement st) {
try {
if(st!=null) {
st.close();
}else {
st = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) {
conn.close();
}else {
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**释放资源closeResourse(conn,ps)*/
public static void closeResourse(Connection conn,PreparedStatement ps) {
try {
if(ps!=null) {
ps.close();
}else {
ps = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) {
conn.close();
}else {
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**释放资源closeResourse(rs)*/
public static void closeResourse(ResultSet rs) {
try {
if(rs!=null) {
rs.close();
}else {
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
c3p0-config.xml
<c3p0-config>
<!-- 默认配置,如果没有指定则使用这个配置 -->
<default-config>
<!-- 基本配置 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost/hejh?characterEncoding=UTF-8 </property>
<property name="user">root</property>
<property name="password">root</property>
<!--扩展配置-->
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!-- 命名的配置 -->
<named-config name="XXX">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/xxxx</property>
<property name="user">root</property>
<property name="password">1234</property>
<!-- 如果池中数据连接不够时一次增长多少个 -->
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">20</property>
<property name="minPoolSize">10</property>
<property name="maxPoolSize">40</property>
<property name="maxStatements">20</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>