模块设计
数据库
搭建项目
创建maven项目
配置tomcat
测试项目能否运行
引入项目依赖 pom.xml
创建项目包结构
编写实体类 :
ORM映射: 表 - 类 映射
编写基础公共类
数据库配置文件 db.properties
driver=com.mysql.jdbc.Driver
# useSSL=false SQL版本大于connect版本,就要设置成false
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456
编写数据库的公共类
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
//操作数据库的公共类
public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;
//静态代码块在类加载的同时初始化
static {
Properties properties = new Properties();
//通过类加载,读取对应的资源
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
}
//获取连接
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver); //驱动只用加载一次
conn = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//编写查询公共方法
public static ResultSet execute(Connection conn,PreparedStatement pst,String sql,Object[] params,ResultSet rs) throws SQLException {
pst = conn.prepareStatement(sql);
for (int i = 0; i <params.length ; i++) {
//setObject 占位符从1开始,但数组从0开始;
pst.setObject(i+1,params[i]);
}
rs = pst.executeQuery();
return rs;
}
//编写增删改公共方法
public static int execute(Connection conn,PreparedStatement pst,String sql,Object[] params) throws SQLException {
pst = conn.prepareStatement(sql);
for (int i = 0; i <params.length ; i++) {
//setObject 占位符从1开始,但数组从0开始;
pst.setObject(i+1,params[i]);
}
int updateRows = pst.executeUpdate();
return updateRows;
}
//关闭连接 释放资源
public static boolean relrase(Connection conn, PreparedStatement pst, ResultSet rs){
boolean flag = true;
if(rs != null){
try {
rs.close();
//GC回收
rs = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag = false;
}
}
if(pst != null){
try {
pst.close();
//GC回收
pst = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag = false;
}
}
if (conn != null){
try {
conn.close();
//GC回收
conn = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag = false;
}
}
return flag;
}
}
字符编码过滤器
<!-- 字符编码过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.lantian.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
导入静态资源
原文:https://www.cnblogs.com/lantianya/p/15187196.html