C3p0数据源的操作:
- 通过ComboPooledDATa Source构造方法创建数据源对象
package com.study.dao;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.SQLException;
public class Example03 {
public static DataSource dataSource=null;
//初始化c3p0 数据源
static {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
try {
comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/jdbc");
comboPooledDataSource.setUser("root");
comboPooledDataSource.setPassword("root");
//设置连接池的参数
comboPooledDataSource.setInitialPoolSize(5);
comboPooledDataSource.setMaxPoolSize(15);
dataSource=comboPooledDataSource;
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
System.out.println(dataSource.getConnection());
}
}
- 通过读取配置文件创建数据源对象
<?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/jdbc
</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="checkoutTimeout">3000</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="teng">
<property name="driverClass">
com.mysql.jdbc.Driver
</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/jdbc
</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">15</property>
</named-config>
</c3p0-config>
package com.study.dao;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.SQLException;
public class Example04 {
public static DataSource dataSource=null;
static {
//使用c3p0-config.xml配置文件中 的name-config 节点中name 属性的值
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("teng");
dataSource=comboPooledDataSource;
}
public static void main(String[] args) throws SQLException {
System.out.println(dataSource.getConnection());
}
}
MVC三层架构设计模式
实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserBean {
private String name;
private String password;
private String email;
}
RegisterFormBean类:
package com.study.pojo;
import java.util.HashMap;
import java.util.Map;
public class RegisterFormBean {
private String name;
private String password;
private String password2;
private String email;
private Map<String,String> errors=new HashMap<String, String>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean validate(){
boolean flag=true;
if (name==null||name.trim().equals("")){
errors.put("name","请输入姓名.");
flag=false;
}
if (password==null||password.trim().equals("")){
errors.put("password","请输入密码.");
flag=false;
}else if (password.length()>12 || password.length()<6){
errors.put("password","请输入6-12个字符");
flag=false;
}
if (password!=null&&!password.equals(password2)){
errors.put("password2","两次输入的密码不一致.");
flag=false;
}
if (email==null||email.trim().equals("")){
errors.put("email","请输入邮箱.");
flag=false;
}else if (!email.matches("([a-zA-Z]|[0-9])(\\w|\\-)+@[a-zA-Z0-9]+\\.([a-zA-Z]{2,4})$")){
errors.put("email","邮箱格有误.");
flag=false;
}
return flag;
}
//向 Map 集合 errors 中添加 错误信息
public void setErrorMsg(String err,String errMsg){
if ((err!=null)&&(errMsg!=null)){
errors.put(err,errMsg);
}
}
//获取errors集合
public Map<String,String> getErrors(){
return errors;
}
}
创建工具类:
package com.study.Utils;
import com.study.pojo.UserBean;
import java.util.HashMap;
public class DBUtils {
private static DBUtils instance=new DBUtils();
private HashMap<String, UserBean> users=new HashMap<String, UserBean>();
private DBUtils(){
UserBean userBean = new UserBean();
userBean.setName("Jack");
userBean.setPassword("121212");
userBean.setEmail("Ser0994@163.com");
users.put("jack",userBean);
UserBean userBean1 = new UserBean();
userBean1.setName("Rose");
userBean1.setPassword("22222");
userBean1.setEmail("Ser0994@163.com");
users.put("Rose",userBean1);}
public static DBUtils getInstance(){return instance;}
//获取数据库 (users)中的数据
public UserBean getUser(String userName){
return (UserBean) users.get(userName);
}
//向数据库(users)插入数据
public boolean insertUser(UserBean userBean){
if (userBean==null){return false;}
String userName=userBean.getName();
if (users.get(userName)!=null){return false;}
users.put(userName,userBean);
return true;
}
}
Servlet类
package com.study.Servlet;
import com.study.Utils.DBUtils;
import com.study.pojo.RegisterFormBean;
import com.study.pojo.UserBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/ControllerServlet")
public class ControllerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Content-type","text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取用户注册时表单提交的参数信息
String name = new String(req.getParameter("name").getBytes("ISO-8859-1"),"utf-8");
System.out.println(name);
String password = req.getParameter("password");
String password2 = req.getParameter("password2");
String email = req.getParameter("email");
//将获取的参数封装到注册表单相关的registerFormbean类中
RegisterFormBean registerFormBean = new RegisterFormBean();
registerFormBean.setName(name);
registerFormBean.setPassword(password);
registerFormBean.setPassword2(password2);
registerFormBean.setEmail(email);
//验证参数填写是否符合要求,如果不符合,转发到 register.jsp重新填写
if (!registerFormBean.validate()){
req.setAttribute("formBean",registerFormBean);
req.getRequestDispatcher(req.getContextPath()+"/jsp/register.jsp").forward(req,resp);
return;
}
//参数复合要求,将参数封装到 User Bean
UserBean userBean = new UserBean();
userBean.setName(name);
userBean.setPassword(password2);
userBean.setEmail(email);
//调用DBUtil 的insertUser()方法 执行添加操作,并返回一个boolean 类型的标注
boolean b = DBUtils.getInstance().insertUser(userBean);
if (!b){
req.setAttribute("DbMes",registerFormBean);
req.setAttribute("formBean",registerFormBean);
req.getRequestDispatcher(req.getContextPath()+"/jsp/register.jsp").forward(req,resp);
return;
}
resp.getWriter().println("恭喜您注册成功,3秒钟后自动跳转");
//将成功注册的用户信息添加到session中
req.getSession().setAttribute("userBean",userBean);
//注册成功后,3秒钟跳转到登录成功页面 loginsuccess.jsp中
resp.setHeader("refresh","3,url=/jsp/loginSuccess.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
jsp页面:
<%--
Created by IntelliJ IDEA.
User: Teng
Date: 2021/12/13
Time: 15:02
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
<title>用户注册</title>
<link rel="shortcut icon" href="../static/1.png" />
<style>
h3{margin-left: 100px;}
#outer{width: 750px;}
span{color: #ff0000;}
div{height: 20px;margin-bottom: 10px;}
.ch{width: 80px;text-align: right;float: left;}
.ip{width: 500px;float: left;}
.ip>input{margin-right: 20px;}
#bt{margin-left: 50px;}
#bt>input{margin-right: 30px;}
</style>
</head>
<body>
<form action="/ControllerServlet" method="post">
<h3>用户注册</h3>
<div id="outer">
<div>
<div class="ch">姓名:</div>
<div class="ip">
<input type="text" name="name" value="${formBean.name}">
<span>${formBean.errors.name}${DBMes}</span></div></div><div>
<div class="ch">密码:</div>
<div class="ip">
<input type="password" name="password">
<span>${formBean.errors.password}</span></div></div>
<div>
<div class="ch">确认密码:</div>
<div class="ip">
<input type="password" name="password2">
<span>${formBean.errors.password2}</span>
</div>
</div>
<div>
<div class="ch">邮箱:</div>
<div class="ip">
<input type="email" name="email" value="${formBean.email}">
<span>${formBean.errors.email}</span>
</div>
</div>
<div id="bt">
<input type="reset" value="重置">
<input type="submit" value="注册">
</div>
</div>
</form>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: Teng
Date: 2021/12/13
Time: 15:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
<title>登录成功</title>
<link rel="shortcut icon" href="../static/1.png" />
<style>
#main{
width: 500px;
height: auto;
}
#main div{
width: 400px;
height: auto;
}
ul{
padding-top: 1px;
padding-left: 1px;
list-style: none;
}
</style>
</head>
<body>
<%
if (session.getAttribute("userBean")==null){
%>
<jsp:forward page="register.jsp" />
<%
return;
}
%>
<div id="main">
<div id="welcome">恭喜你,登陆成功</div>
<hr/>
<div>您的信息</div>
<div>
<ul>
<li>您的姓名:${userBean.name}</li>
<li>您的邮箱:${userBean.email}</li>
</ul>
</div>
</div>
</body>
</html>
el表达式和jstl:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="">
num1 : <input type="text" name="num1" /> <br/>
num2 : <input type="text" name="num" /> <br/>
num3 : <input type="text" name="num" /> <br/>
<input type="submit" value="提交" />
<input type="submit" value="重置">
<hr/>
num1 :${param.num1} <br/>
num2 :${paramValues.num[0]} <br/>
num3 :${paramValues.num[1]} <br/>
</form>
</body>
</html>
JDBC
搭建数据库环境:
create database jdbc;
user jdbc;
create table user(
id int primary key auto_increment,
name varchar(40),
password varchar(40),
email varchar(60),
birthday date
)
编写JDBC程序:
package com.study.dao;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class Example01 {
public static void main(String[] args) {
Statement statement = null;
ResultSet resultSet = null;
Connection connection = null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?useSSL=true&useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
connection = DriverManager.getConnection(url, username, password);
//通过Connection 获取statement对象
statement = connection.createStatement();
//实现statement对象执行sql语句
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
//操作ResultSet 结果集
System.out.println("id | name |password | email | birthday");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String psw = resultSet.getString("password");
String email = resultSet.getString("email");
Date birthday = resultSet.getDate("birthday");
System.out.println(id + " | " + name + " | " + psw + " | " + email + " | " + birthday);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
resultSet = null;//如果释放失败,就GC回收
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
connection = null;//如果释放失败,就GC回收
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
插入:
package com.study.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Example02 {
public static void main(String[] args) {
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?useSSL=true&useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
connection=DriverManager.getConnection(url,username,password);
String sql="INSERT INTO users(NAME,PASSWORD,email,birthday) VALUES(?,?,?,?);";
//预加载sql语句,防止sql注入
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1,"ooyys");
preparedStatement.setString(2,"1122");
preparedStatement.setString(3,"ESer0994@163.com");
preparedStatement.setString(4,"2021-11-23");
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
preparedStatement = null;//如果释放失败,就GC回收
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
connection = null;//如果释放失败,就GC回收
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
查询值:
package com.study.dao;
import javax.swing.plaf.nimbus.State;
import java.sql.*;
public class Example03 {
public static void main(String[] args) {
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc?useSSL=true&useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
//获取 Connection 对象
connection= DriverManager.getConnection(url,username,password);
//编写sql语句
String sql="select * from users";
//创建statement 对象并设置常量
statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
//执行sql语句
resultSet = statement.executeQuery(sql);
System.out.println("第二条数据的name值为:");
resultSet.absolute(2);//将指针定位到2
System.out.println(resultSet.getString("name"));
System.out.println("第一条数据的name值为:");
resultSet.beforeFirst();//将指针定位到第一行之前
resultSet.next();//将指针向红滚动
System.out.println(resultSet.getString("name"));
System.out.println("第四条数据的name值为:");
resultSet.afterLast();//将指针定位到结果集中最后一条数据之后
resultSet.previous();//将指针先前滚
System.out.println(resultSet.getString("name"));
} catch (Exception e) {
e.printStackTrace();
}finally {
if (statement != null) {
try {
statement.close();
statement = null;//如果释放失败,就GC回收
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
connection = null;//如果释放失败,就GC回收
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
resultSet = null;//如果释放失败,就GC回收
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}