1.创建数据库(创建表)
2.导入需要的jar包(导入WebContent目录下的WEB-INF下的bin目录里面)
3.创建包:com.cg.entity(装实体类)
com.cg.dao(装dao类)
com.cg.service(装service类)
com.cg.servlet(装servlet类)
com.cg.util(装工具类)
4.创建JDBC工具类(使用Druid数据库连接池)
5.配置数据库及连接池参数(放于src下)
6.实体类层:用来封装属性及其get set方法 toString方法,有参构造方法,无参构造方法等。
7.Dao层:对数据库的增删改查方法的封装(操作数据库)也是属于业务逻辑
8.Servlet(Controller):流程控制
9.Service:处理业务逻辑
10.jsp(View)页面(位于WebContent目录下)
1.创建数据库及表(tb_brand)
图片:
2.jar包的导入(导入WebContent目录下的WEB-INF下的bin目录里面)
3.包的创建(创建在src下)
我们用的druid所以我们同时也需把druid文件放入src下
代码片
.
1.工具类(位于com.cg.util包下)
创建JDBCUtil类
package com.cg.util;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.*;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
/**
* JDBC工具类(使用Druid数据库连接池)
*
*/
public class JDBCUtil {
// 数据库连接池
private static DataSource ds;
// 静态代码块,用户初始化类,只会执行一次
static {
try {
// 加载druid.properties属性文件
Properties properties = new Properties();
properties.load(JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
// 获取数据库连接池对象
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取工具类实例
public static JDBCUtil getInstance() {
return new JDBCUtil();
}
// 数据库连接
private Connection connection;
// statement对象,执行SQL
private PreparedStatement preparedStatement;
// 查询结果集
private ResultSet resultSet;
/**
* 从数据库连接池中获取连接,因为是内部使用,所以设为private不暴露给外界使用
*
* @return 从数据库连接池中获取连接
*/
private Connection getConnection() {
connection = null;
try {
connection = ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 释放数据库资源
*/
public void close() {
// 释放数据库资源
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 执行增删改sql语句
*
* @param sql
* SQL语句,其中使用?占位符表示参数
* @param params
* SQL中需要的参数值,需要按照SQL中?的顺序,将参数值放入List中
* @return 是否执行成功
*/
public boolean update(String sql, List<Object> params) {
// 获取连接
getConnection();
int rows = 0;
if (connection != null) {
try {
// 获取PreparedStatement对象
preparedStatement = connection.prepareStatement(sql);
// 循环设置参数
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i));
}
// 这一步非常必要,帮助我们查看执行的sql到底是什么样!用于解决问题
guessPreparedSql(sql, params);
// 执行SQL语句
rows = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rows > 0;
}
/**
* 执行select语句
*
* @param sql
* SQL语句,其中使用?占位符表示参数
* @param params
* SQL中需要的参数值,需要按照SQL中?的顺序,将参数值放入List中
* @return 查询结果集
*/
public ResultSet query(String sql, List<Object> params) {
// 获取连接
getConnection();
if (connection != null) {
try {
// 获取PreparedStatement对象
preparedStatement = connection.prepareStatement(sql);
// 循环设置参数
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i));
}
// 这一步非常必要,帮助我们查看执行的sql到底是什么样!
guessPreparedSql(sql, params);
// 执行sql,并获取结果集
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 需要返回ResultSet需要提供给外部使用
return resultSet;
}
/**
* 执行无参select语句
*
* @param sql
* SQL语句
* @return 结果集
*/
public ResultSet query(String sql) {
return query(sql, Collections.emptyList());
}
/**
* 获得PreparedStatement向数据库提交的SQL语句
*
* @param sql
* @param params
* @return
*/
private String guessPreparedSql(String sql, List<Object> params) {
int paramNum = 0;
// 如果参数集不为空,取得其长度
if (null != params) {
paramNum = params.size();
}
// 如果没有参数,说明不是动态SQL语句,直接返回原sql
if (1 > paramNum) {
System.out.println(LocalDateTime.now() + "\tprepared sql: " + sql);
return sql;
}
// 如果有参数,则是动态SQL语句,需要构造并返回新sql
StringBuffer returnSQL = new StringBuffer();
String[] subSQL = sql.split("\\?");
// 开始循环替换问号为参数值
for (int i = 0; i < paramNum; i++) {
Object value = params.get(i);
if (value == null) {
System.err.printf("第 %d 个参数的值为 null %n", i + 1);
returnSQL.append(subSQL[i]).append(value);
continue;
}
if (value instanceof Number) {
// 数值不需要引号
returnSQL.append(subSQL[i]).append(value);
} else {
// 非数值需要引号,遇到特殊字符将其转义输出
String str = value.toString().replaceAll("(['\\\\])", "\\\\$1");
returnSQL.append(subSQL[i]).append(" '").append(str).append("' ");
}
}
// 如果问号不是原sql的最后一个字符,则将改问号后的部分添加到returnSQL中
if (subSQL.length > params.size()) {
returnSQL.append(subSQL[subSQL.length - 1]);
}
String formatSql = returnSQL.toString();
System.out.println(LocalDateTime.now() + "\tprepared sql: " + formatSql);
return formatSql;
}
}
5.配置数据库及连接池参数。
druid.properties:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
username=root //这里是你自己Navicat的用户名
password=123456 //这里是你自己Navicat的秘密
#初始化连接数量
initialSize=5
#最大连接数
maxActive=10
#最大等待时间
maxWait=3000
代码片
.
6.实体类层(位于com.cg.entity包下)
用来封装属性及其get set方法 toString方法,有参构造方法,无参构造方法等。
创建一个Brand类
package com.cg.entity;
import com.sun.xml.internal.bind.v2.model.core.ID;
/**
* 品牌实体类
* @author user
*
*/
public class Brand {
private int id;
private String brandName;
private String companyName;
private int ordered;
private String description;
private int status;
public Brand() {
super();
}
public Brand(int id, String brandName, String companyName, int ordered, String description, int status) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
this.status = status;
}
public int getId() {
return id;
}
public String getBrandName() {
return brandName;
}
public String getCompanyName() {
return companyName;
}
public int getOrdered() {
return ordered;
}
public String getDescription() {
return description;
}
public int getStatus() {
return status;
}
public void setId(int id) {
this.id = id;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public void setOrdered(int ordered) {
this.ordered = ordered;
}
public void setDescription(String description) {
this.description = description;
}
public void setStatus(int status) {
this.status = status;
}
}
7.创建Dao类(位于com.cg.dao包下)
(1)创建BrandDao(里面有增加、查找、修改、删除)
package com.cg.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.cg.entity.Brand;
import com.cg.util.JDBCUtil;
import com.mysql.jdbc.Util;
/**
* 品牌数据访问类
* @author user
*
*/
public class BrandDao {
public List<Brand> selectList() {
try {
//获取实例
JDBCUtil util = JDBCUtil.getInstance();
String sql = "select * from tb_brand";
ResultSet rs = util.query(sql);
//数据封装到一个集合
List<Brand> brands = new ArrayList<Brand>();
//遍历集合
while(rs.next()){
//数据
int id = rs.getInt("id");
String brandName = rs.getString("brand_name");
String companyName = rs.getString("company_name");
int ordered = rs.getInt("ordered");
String des = rs.getString("description");
int status = rs.getInt("status");
Brand brand = new Brand();
//数据放入到brand中
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(ordered);
brand.setId(id);
brand.setDescription(des);
brand.setStatus(status);
//品牌放到集合里面
brands.add(brand);
}
util.close();
return brands;//把品牌返回出去
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 新增品牌
* @param brand 品牌信息
* @return 是否成功
*/
public boolean insertBrand(Brand brand) {
JDBCUtil util = JDBCUtil.getInstance();//获取实例
String sql = "insert into tb_brand(brand_name,company_name,ordered,description,status)"
+"values(?,?,?,?,?)";
//实例化一个集合
List<Object> params = new ArrayList<>();
//放参数
params.add(brand.getBrandName());
params.add(brand.getCompanyName());
params.add(brand.getOrdered());
params.add(brand.getDescription());
params.add(brand.getStatus());
boolean flag = util.update(sql, params);
util.close();
return flag;
}
/**
* 根据id查询品牌
* @param id 主键id
* @return 品牌信息
*/
public Brand getBrandById(int id) {
JDBCUtil util = JDBCUtil.getInstance();
try {
String sql= "select * from tb_brand where id=?";
//为参数赋值
List<Object> params = new ArrayList<>();
params.add(id);
//执行
ResultSet rs = util.query(sql,params);
if(rs.next()){
//数据
String brandName = rs.getString("brand_name");
String companyName = rs.getString("company_name");
int ordered = rs.getInt("ordered");
String des = rs.getString("description");
int status = rs.getInt("status");
Brand brand = new Brand();
//数据放入到brand中
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(ordered);
brand.setId(id);
brand.setDescription(des);
brand.setStatus(status);
return brand;
}else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}finally {
util.close();//finally 无论是否报异常都要释放资源
}
}
/**
* 根据id更新品牌
* @param brand 品牌信息
* @return 是否更新成功
*/
public boolean updateBrand(Brand brand) {
JDBCUtil util = JDBCUtil.getInstance();
String sql = "update tb_brand set brand_name=?,company_name=?,ordered=?,description=?,status=?"
+ "where id=?";
//实例化一个集合
List<Object> params = new ArrayList<>();
//放参数
params.add(brand.getBrandName());
params.add(brand.getCompanyName());
params.add(brand.getOrdered());
params.add(brand.getDescription());
params.add(brand.getStatus());
params.add(brand.getId());
boolean flag = util.update(sql, params);
util.close();
return flag;
}
/**
* 根据id删除数据
* @param id 品牌id
* @return 是否成功
*/
public boolean deleteBrand(int id) {
JDBCUtil util = JDBCUtil.getInstance();
String sql ="delete from tb_brand where id=?";
List<Object> params = new ArrayList<>();
params.add(id);
boolean flag = util.update(sql, params);
util.close();
return flag;
}
}
8.service类(位于com.cg.service包下)
创建BrandService类(依旧有增加、查找、修改、删除)
package com.cg.service;
import java.util.List;
import com.cg.dao.BrandDao;
import com.cg.entity.Brand;
import com.sun.scenario.effect.Blend;
/**
* 品牌业务逻辑类
* @author user
*
*/
public class BrandService {
/**
* 获取品牌列表
* @return 品牌列表
*/
public List<Brand> getList() {
BrandDao brandDao = new BrandDao();//实例化
return brandDao.selectList();
}
/**
* 新增品牌列表
* @param brand 品牌信息
* @return 是否成功
*/
public boolean addBrand(Brand brand) {
BrandDao brandDao = new BrandDao();
return brandDao.insertBrand(brand);
}
/**
* 根据id查询品牌
* @param id 品牌id
* @return品牌信息
*/
public Brand getBrandById(int id) {
BrandDao brandDao = new BrandDao();
return brandDao.getBrandById(id);
}
/**
* 编辑品牌信息
* @param brand 品牌
* @return 是否成功
*/
public boolean editBrand(Brand brand) {
BrandDao brandDao = new BrandDao();
return brandDao.updateBrand(brand);
}
/**
* 删除品牌信息
* @param id 品牌id
* @return 是否成功
*/
public boolean deleteBrand(int id) {
BrandDao brandDao = new BrandDao();
return brandDao.deleteBrand(id);
}
}
9.servlet类(位于com.cg.servlet包下)
创建(1)BrandListServlet
(2)AddServlet //增加
(3)EditPageServlet //查找
(4)EditServlet //修改
(5)DeleteServlet //删除
(1)BrandListServlet
package com.cg.servlet;
import java.io.IOException;
import java.util.List;
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 com.cg.entity.Brand;
import com.cg.service.BrandService;
@WebServlet("/brandList")
public class BrandListServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BrandService brandService = new BrandService();
List<Brand> brands = brandService.getList();//获取商品列表
//请求转发跳转页面
request.setAttribute("brands", brands);//把数据放入表中
request.getRequestDispatcher("/list.jsp").forward(request, response);
}
}
(2)AddServlet
package com.cg.servlet;
import java.io.IOException;
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 com.cg.entity.Brand;
import com.cg.service.BrandService;
@WebServlet("/add")
public class AddServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收用户提交的参数
request.setCharacterEncoding("UTF-8");//解决中文乱码
//获取参数(通过request获取用户提交的表单请求)
String brandName = request.getParameter("brand_name");
String companyName = request.getParameter("company_name");
String ordered = request.getParameter("ordered");
String description = request.getParameter("description");
String status = request.getParameter("status");
//把数据封装到brand实体中
Brand brand = new Brand();
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.parseInt(ordered) );
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
//id不需要赋,id是自增的
//新增一个品牌数据
BrandService brandService = new BrandService();//调用service
boolean flag = brandService.addBrand(brand);
if(flag){
response.sendRedirect("/BrandSys/brandList");
}
}
}
(3)EditPageServlet
package com.cg.servlet;
import java.io.IOException;
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 com.cg.entity.Brand;
import com.cg.service.BrandService;
@WebServlet("/editPage")
public class EditPageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//根据id查询品牌信息
String id = request.getParameter("id");
BrandService brandService = new BrandService();
Brand brand = brandService.getBrandById(Integer.parseInt(id));
//跳转到编辑页面
request.setAttribute("brand", brand);
request.getRequestDispatcher("/edit.jsp").forward(request, response);
//需要向页面传参的时候 用请求转发request
//不需要传参的时候 用重定向response
}
}
(4)EditServlet
package com.cg.servlet;
import java.io.IOException;
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 com.cg.entity.Brand;
import com.cg.service.BrandService;
@WebServlet("/edit")
public class EditServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取参数值
//接收用户提交的参数
request.setCharacterEncoding("UTF-8");//解决中文乱码
//获取参数(通过request获取用户提交的表单请求)
String brandName = request.getParameter("brand_name");
String companyName = request.getParameter("company_name");
String ordered = request.getParameter("ordered");
String description = request.getParameter("description");
String status = request.getParameter("status");
String id = request.getParameter("id");
//把数据封装到brand实体中
Brand brand = new Brand();
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.parseInt(ordered) );
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
brand.setId(Integer.parseInt(id));
//修改品牌信息
BrandService brandService = new BrandService();
boolean flag = brandService.editBrand(brand);
if(flag){
response.sendRedirect("/BrandSys/brandList");
}
}
}
(5)DeleteServlet
package com.cg.servlet;
import java.io.IOException;
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 com.cg.service.BrandService;
@WebServlet("/delete")
public class DeleteServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取id
String id = request.getParameter("id");
//根据id删除
BrandService brandService = new BrandService();
boolean flag = brandService.deleteBrand(Integer.parseInt(id));
if(flag){
response.sendRedirect("/BrandSys/brandList");
}
}
}
10.jsp页面(位于Webcontent目录下)显示于浏览器页面
(1)list页面
(2)add页面
(3)edit页面
(1)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=UTF-8">
<title>品牌列表页面title>
head>
<body>
<fieldset>
<legend>品牌列表legend>
<div style="margin-bottom: 5px">
<a href="/BrandSys/add.jsp">新增品牌a>
div>
<table border="1">
<tr>
<th>品牌名称th>
<th>企业名称th>
<th>描述信息th>
<th>状态th>
<th colspan="2">操作th>
tr>
<c:forEach items="${brands}" var="item">
<tr>
<td>${item.brandName}td>
<td>${item.companyName}td>
<td>${item.ordered}td>
<td>${item.description}td>
<td>${item.status==0?'禁用':'启用'}td>
<td><a href="/BrandSys/editPage?id=${item.id}">修改a>td>
<td><a href="/BrandSys/delete?id=${item.id}">删除a>td>
tr>
c:forEach>
table>
fieldset>
body>
html>
(2)add.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=UTF-8">
<title>新增品牌页面title>
head>
<body>
<fieldset>
<legend>新增品牌legend>
<form action="/BrandSys/add" method="post">
品牌名称:<input type="text" name="brand_name"><br>
企业名称:<input type="text" name="company_name"><br>
排序字段:<input type="text" name="ordered"><br>
描述信息:<input type="text" name="description"><br>
状态:<input type="radio" name="status" value="0">禁用
<input type="radio" checked="checked" name="status" value="1">启用<br><br>
<input type="submit" value="新增">
form>
fieldset>
body>
html>
(3)edit.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>修改品牌页面title>
head>
<body>
<fieldset>
<legend>修改品牌legend>
<form action="/BrandSys/edit" method="post">
品牌名称:<input type="text" value="${brand.brandName}" name="brand_name"><br>
企业名称:<input type="text" value="${brand.companyName }" name="company_name"><br>
排序字段:<input type="text" value="${brand.ordered}" name="ordered"><br>
描述信息:<input type="text" value="${brand.description}" name="description"><br>
<c:if test="${brand.status==0}">
状态:<input type="radio" name="status" checked="checked" value="0">禁用
<input type="radio" name="status" value="1">启用<br><br>
c:if>
<c:if test="${brand.status==1}">
状态:<input type="radio" name="status" value="0">禁用
<input type="radio" name="status" checked="checked" value="1">启用<br><br>
c:if>
<input type="hidden" name="id" value="${brand.id}">
<input type="submit" value="修改">
form>
fieldset>
body>
html>
1.项目的创建:
(1)顺序:
[1][2]
[3][4]
(2)第四步的时候一定要点击画√
2.包的创建
(1)顺序:上下
(2)包名自己取(com.cg.name属于个人习惯)
3.类的创建(实体类、Dao、Service、工具类均是这样创建)
(1)顺序为上下
(2)类名自取(注意:类名首字母大写)
(3)其他不用动只用填写类名即完成
4.Servlet的创建
(1)顺序:
[1][2]
[3][4]
5.name.jsp的创建
(1)顺序:上下
(2)名字自己取
6.配置数据库及连接池参数(放于src下)创建druid
(1)名字自行取(我用的是阿里的Druidl连接池,所以我去的名字是druid.properties)