1:首先把所需的包导入项目内
2:连接数据库的帮助类DBAccess
package com.Liuyujian.Dao;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 提供了一组获得或关闭数据库对象的方法
*
*/
public class DBAccess {
private static String driver;
private static String url;
private static String user;
private static String password;
static {// 静态块执行一次,加载 驱动一次
try {
InputStream is = DBAccess.class
.getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("pwd");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 获得数据连接对象
*
* @return
*/
public static Connection getConnection() {
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void close(ResultSet rs) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Statement stmt) {
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
close(conn);
}
public static boolean isOracle() {
return "oracle.jdbc.driver.OracleDriver".equals(driver);
}
public static boolean isSQLServer() {
return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
}
public static boolean isMysql() {
return "com.mysql.jdbc.Driver".equals(driver);
}
public static void main(String[] args) {
Connection conn = DBAccess.getConnection();
DBAccess.close(conn);
System.out.println("isOracle:" + isOracle());
System.out.println("isSQLServer:" + isSQLServer());
System.out.println("isMysql:" + isMysql());
System.out.println("数据库连接(关闭)成功");
}
}
/与数据库的沟通桥梁
#mysql5
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
user=root
pwd=123
3:通用分页帮助类
3.1:PageBean
package com.Liuyujian.Dao;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
private Map paMap = new HashMap();
private String url;
public void setRequset(HttpServletRequest req) {
// 保存上一次请求所携带的参数
this.setPaMap(req.getParameterMap());
this.setUrl(req.getRequestURL() .toString());
// 在jsp界面控制是否分页
this.setPagination(req.getParameter("pagination"));
// 当jsp界面控制一页显示多少行数据
this.setRows(req.getParameter("rows"));
this.setPage(req.getParameter("page"));
}
// 重载方法是为了通用
private void setPagination(String pagination) {
// TODO Auto-generated method stub
this.pagination = StringUtils.isNotBlank(pagination) ? !"false".equals(pagination) : this.pagination;
}
private void setRows(String rows) {
// TODO Auto-generated method stub
this.rows = StringUtils.isNotBlank(rows) ? Integer.valueOf(rows) : this.rows;
}
private void setPage(String page) {
// TODO Auto-generated method stub
this.page = StringUtils.isNotBlank(page) ? Integer.valueOf(page) : this.page;
}
public Map getPaMap() {
return paMap;
}
public void setPaMap(Map paMap) {
this.paMap = paMap;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
// 获取到最大页码数
public int getMaxPage() {
return this.total % this.rows == 0 ? this.total/this.rows : this.total/this.rows+1;
}
// 下一页
public int getNextPage() {
return this.page < this.getMaxPage() ? this.page+1 : this.page;
}
// 上一页
public int getPreviousPage() {
return this.page > 1 ? this.page-1 : this.page;
}
}
3.2分页自定义标签Pagtag
package com.Liuyujian.web;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.Liuyujian.Dao.PageBean;
import sun.nio.cs.ext.DoubleByte.Encoder_DBCSONLY;
public class Pagtag extends BodyTagSupport {
private static final long serialVersionUID = -553969530960334073L;
private PageBean pageBean;
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.print(toHTML());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doStartTag();
}
private String toHTML() {
StringBuilder sb=new StringBuilder();
// 拼接下一次发送请求所要提交的隐藏的from表单
sb.append("");
// 拼接分页条
sb.append("");
// 拼接分页所需要的js代码
sb.append("");
return sb.toString();
}
}
4:Dao层
4.1:通用dao: BaseDao
package com.Liuyujian.Dao;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BaseDao {
//sql:不同的sql语句所以需要传递;
//clz:生产出不同的实体类对应的实列,然后装进list容器中
public List executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
Connection con= DBAccess.getConnection();
PreparedStatement ps = null;
ResultSet rs=null;
if(pageBean!=null && pageBean.isPagination()) {
System.out.println("1111111111111111");
//需要分页的sql代码
String consql=getconsql(sql);
ps = con.prepareStatement(consql);
rs=ps.executeQuery();
if(rs.next()) {
//算总记录数
pageBean.setTotal(rs.getLong(1)+"");
}
//需要分页的代码
String setsql=getsetsql(sql,pageBean);
ps = con.prepareStatement(setsql);
rs=ps.executeQuery();
}else {
ps = con.prepareStatement(sql);
rs=ps.executeQuery();
}
List list=new ArrayList<>();
T t;
while(rs.next()) {
//list.add(new Book(rs.getInt("bid"),rs.getString("bname") , rs.getFloat("price")));
//1:实列化一个对象(该对象是空的)2:去book的所有属性,然后给其赋值3:然后装进list
//给属性赋值
t= (T)clz.newInstance();
Field[] fileds = clz.getDeclaredFields();
for (Field field : fileds) {
field.setAccessible(true);
field.set(t, rs.getObject(field.getName()));
}
list.add(t);
}
DBAccess.close(con, ps, rs);
return list;
}
private String getsetsql(String sql, PageBean pageBean) {
// TODO Auto-generated method stub
return sql+" limit "+ pageBean.getStartIndex()+","+pageBean.getRows();
}
private String getconsql(String sql) {
// TODO Auto-generated method stub
//适合分页的代码;
return "select count(1) from ("+sql+")t";
}
public int executeQuery(String sql,T t,String[] attrs)throws Exception {
Connection con=DBAccess.getConnection();
PreparedStatement ps=con.prepareStatement(sql);
for(int i=1;i<=attrs.length;i++) {
Field field = t.getClass().getDeclaredField(attrs[i-1]);
field.setAccessible(true);
ps.setObject(i, field.get(t));
}
int num=ps.executeUpdate();
DBAccess.close(con, ps, null);
return num;
}
}
4.2所需要的实体类
package com.Liuyujian.Dao;
public class Book {
private int bid;
private String bname;
private float price;
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
}
4.3继承通用Basedao,的bookdao类
package com.Liuyujian.Dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BookDao extends BaseDao {
//分页查询
public List list(Book book,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
String sql="select * from t_mvc_book where true ";
String bname=book.getBname();
int bid=book.getBid();
if(StringUtils.isNotBlank(bname)) {
sql+=" and bname like '%"+bname+"%' ";
}
if(bid!=0) {
sql+=" and bid="+bid;
}
return super.executeQuery(sql, Book.class, pageBean);
}
/**
*
* @param book
* @return
* @throws Exception
*/
//修改
public int update(Book book) throws Exception{
String sql="update t_mvc_book set bname=?,price=? where bid=? ";
return super.executeQuery(sql, book, new String[] {"bname","price","bid"});
}
//增加
public int add(Book book) throws Exception{
String sql="insert into t_mvc_book(bid,bname,price) values(?,?,?)";
return super.executeQuery(sql, book, new String[] {"bid","bname","price"});
}
//删除
public int dele(Book book) throws Exception{
String sql=" delete from t_mvc_book where bid=? ";
return super.executeQuery(sql, book, new String[] {"bid"});
}
}
调用了上篇mvc框架 Actionsuppor: BookActuon
package com.Liuyujian.web;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Liuyujian.Dao.Book;
import com.Liuyujian.Dao.BookDao;
import com.Liuyujian.Dao.PageBean;
import com.Liuyujian.framework.Actionsuppor;
import com.Liuyujian.framework.ModelDrivern;
public class BookActuon extends Actionsuppor implements ModelDrivern {
private Book book=new Book();
private BookDao dao=new BookDao();
//分页查询
public String list(HttpServletRequest req,HttpServletResponse resp) {
PageBean pag=new PageBean();
pag.setRequset(req);
pag.setRows(5);
try {
List list=this.dao.list(book, pag);
req.setAttribute("booklist",list);
req.setAttribute("pageBean", pag);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "list";
}
public String presav(HttpServletRequest req,HttpServletResponse resp) {
//bid的类型是int类型,而int类型的默认值是0;如果jsp未传递bid,那么bid==0;
if(book.getBid()==0) {
System.out.println("做增加");
}else {
//修改逻辑
try {
Book b = this.dao.list(book, null).get(0);
req.setAttribute("book", b);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "bianji";
}
/**
* 新增
* @param req
* @param resp
* @return
*/
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
this.dao.add(book);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "tolist";
}
/**
* 修改
* @param req
* @param resp
* @return
*/
public String update(HttpServletRequest req,HttpServletResponse resp) {
try {
this.dao.update(book);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "tolist";
}
/**
* 删除
* @param req
* @param resp
* @return
*/
public String dele(HttpServletRequest req,HttpServletResponse resp) {
try {
this.dao.dele(book);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "tolist";
}
@Override
public Book getModel() {
// TODO Auto-generated method stub
return book;
}
}
根据所需:建立jsp页面booklist:用于遍历数据
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="/liuyujian" prefix="L" %>
Insert title here
小说目录
增加
编号
名称
价格
${b.bid }
${b.bname }
${b.price }
修改 删除
增加修改页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here