一? 思维导图
?
二 代码
PageTag
package com.ysw.tag;
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.ysw.utli.PageBean;
public class PageTag extends BodyTagSupport{
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) {
e.printStackTrace();
}
return super.doStartTag();
}
private String toHTML() {
StringBuffer sb = new StringBuffer();
// 隐藏的form表单---这个就是上一次请求下次重新发的奥义所在
// 上一次请求的URL
sb.append("<form action='"+pageBean.getUrl()+"' id='pageBeanForm' method='post'>");
sb.append(" <input type='hidden' name='page'>");
// 上一次请求的参数
Map<String, String[]> paramMap = pageBean.getParamMap();
if(paramMap != null && paramMap.size() > 0) {
Set<Entry<String, String[]>> entrySet = paramMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
// 参数名
String key = entry.getKey();
// 参数值
for (String value : entry.getValue()) {
// 上一次请求的参数,再一次组装成了新的Form表单
// 注意:page参数每次都会提交,我们需要避免
if(!"page".equals(key)) {
sb.append(" <input type='hidden' name='"+key+"' value='"+value+"' >");
}
}
}
}
sb.append("</form>");
// 分页条
sb.append("<ul class='pagination justify-content-center'>");
sb.append(" <li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'");
sb.append(" href='javascript:gotoPage(1)'>首页</a></li>");
sb.append(" <li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'");
sb.append(" href='javascript:gotoPage("+pageBean.previousPage()+")'><</a></li>");// less than 小于号
// sb.append(" <li class='page-item'><a class='page-link' href='#'>1</a></li>");
// sb.append(" <li class='page-item'><a class='page-link' href='#'>2</a></li>");
sb.append(" <li class='page-item active'><a class='page-link' href='#'>"+pageBean.getPage()+"</a></li>");
sb.append(" <li class='page-item "+(pageBean.getPage() == pageBean.maxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>></a></li>");
sb.append(" <li class='page-item "+(pageBean.getPage() == pageBean.maxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.maxPage()+")'>尾页</a></li>");
sb.append(" <li class='page-item go-input'><b>到第</b><input class='page-link'");
sb.append(" type='text' id='skipPage' name='' /><b>页</b></li>");
sb.append(" <li class='page-item go'><a class='page-link'");
sb.append(" href='javascript:skipPage()'>确定</a></li>");
sb.append(" <li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>");
sb.append("</ul>");
// 分页执行的JS代码
sb.append("<script type='text/javascript'>");
sb.append(" function gotoPage(page) {");
sb.append(" document.getElementById('pageBeanForm').page.value = page;");
sb.append(" document.getElementById('pageBeanForm').submit();");
sb.append(" }");
sb.append(" function skipPage() {");
sb.append(" var page = document.getElementById('skipPage').value;");
sb.append(" if (!page || isNaN(page) || parseInt(page) < 1 || parseInt(page) > "+pageBean.maxPage()+") {");
sb.append(" alert('请输入1~"+pageBean.maxPage()+"的数字');");
sb.append(" return;");
sb.append(" }");
sb.append(" gotoPage(page);");
sb.append(" }");
sb.append("</script>");
return sb.toString();
}
}
DBAccess
package com.ysw.utli;
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("数据库连接(关闭)成功");
}
}
PageBean
package com.ysw.utli;
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 String url;
private Map<String,String[]> paramMap = new HashMap<>();
public void setRequest(HttpServletRequest req) {
this.setUrl(req.getRequestURL().toString());
this.setPagination(req.getParameter("pagination"));
this.setRows(req.getParameter("rows"));
this.setPage(req.getParameter("page"));
}
public void setPage(String page) {
if(StringUtils.isNotBlank(page))
this.setPage(Integer.valueOf(page));
}
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows))
this.setRows(Integer.valueOf(rows));
}
public void setPagination(String pagination) {
if(StringUtils.isNotBlank(pagination))
this.setPagination(!"false".equals(pagination));
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParamMap() {
return paramMap;
}
public void setParamMap(Map<String, String[]> paramMap) {
this.paramMap = paramMap;
}
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;
}
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
public int maxPage() {
// total % rows == 0 ? total / rows : total / rows +1
return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
}
public int nextPage() {
return this.page < this.maxPage() ? this.page + 1 : this.page;
}
public int previousPage() {
return this.page > 1 ? this.page - 1 : this.page;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
PinYinUtil
package com.ysw.utli;
import java.util.regex.Pattern;
import net.sourceforge.pinyin4j.PinyinHelper;
/**
* 拼音工具类,能将汉字转换成拼音的首字母
*/
public class PinYinUtil {
/* 用于中文判断的正则表达式 */
private static final String regexStr = "[\u4e00-\u9fa5]";
/**
* 将一个字符串中的汉字转换成拼音首字母、非汉字则不变
*
* @param cn
* String
* @return String
*/
public static String toPinyin(String cn) {
String pinyin = null;
if (null == cn || 0 == cn.trim().length()) {
return pinyin;
}
/* 去掉字符串前后的空格 */
cn = cn.trim();
char[] chineseCharacterArr = cn.toCharArray(); // 转换成汉字字符数组
char[] letteCharacterArr = new char[chineseCharacterArr.length]; // 字母字符数组
for (int i = 0; i < chineseCharacterArr.length; i++) {
// 得到汉字拼音的首字母
letteCharacterArr[i] = getFirstLetterFromPinyin(chineseCharacterArr[i]);
}
if (0 != letteCharacterArr.length) {
pinyin = new String(letteCharacterArr);
pinyin = pinyin.toUpperCase();
}
return pinyin;
}
/* 得到一个汉字的拼音的首字母 */
private static char getFirstLetterFromPinyin(char cn) {
// 判断cn是否为一个合法的汉字,不是则直接返回cn
if (!isChineseCharacters(cn)) {
return cn;
}
String[] pyArr = PinyinHelper.toHanyuPinyinStringArray(cn);
char py = pyArr[0].charAt(0);
return py;
}
/**
* 判断字符是否为一个汉字
*
* @param cn
* char
* @return boolean
*/
public static boolean isChineseCharacters(char cn) {
boolean b = false;
if (Pattern.matches(regexStr, String.valueOf(cn))) {
b = true;
}
return b;
}
public static void main(String[] args) {
String s = "保存并加入A题库";
System.out.println(PinYinUtil.toPinyin(s).toLowerCase());
}
}
StringUtils
package com.ysw.utli;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
BaseDao
package com.zking.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import com.ysw.utli.DBAccess;
import com.ysw.utli.PageBean;
public class BaseDao<T> {
public interface CallBack<T>{
public List<T> forEach(ResultSet rs) throws Exception;
}
/**
* 1.通用分页两个基本要素
* 1.1 需要知道满足条件的条目数
* 1.2 查询满足条件指定页码的结果
* @throws Exception
*/
public List<T> executeQuery(PageBean pb, String sql,CallBack<T> cb) throws Exception {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBAccess.getConnection();
// 如果用户需要分页 就将用户传递过来sql语句进行转换
if (null != pb && pb.isPagination()) {
String countSql = this.countSql(sql);
ps = con.prepareStatement(countSql);
rs = ps.executeQuery();
if (rs.next()) {
pb.setTotal(rs.getInt(1));
}
// 开始查询结果
String pageSql = this.pageSql(sql, pb);
ps = con.prepareStatement(pageSql);
} else {
// 用户不需要分页
ps = con.prepareStatement(sql);
}
rs = ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return cb.forEach(rs);
}
/**
* 共用的方法用于执行sql语句实现增删改
*
* @param sql
* @return
*/
public int executeUpdate(String sql) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
int n = 0;
try {
con = DBAccess.getConnection();
ps = con.prepareStatement(sql);
n = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return n;
}
/**
* 将用户sql语句修改为查询满足条件的总条目数sql语句
*
* @param sql
* @return
*/
private String countSql(String sql) {
String countSql = "select count(*) from (" + sql + ") a";
return countSql;
}
private String pageSql(String sql, PageBean pb) {
String pageSql = "select * from (" + sql + ") a limit " + pb.getStartIndex() + "," + pb.getRows();
return pageSql;
}
}
BookDao
package com.zking.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;
import com.zking.entity.Book;
import com.ysw.utli.DBAccess;
import com.ysw.utli.PageBean;
import com.ysw.utli.StringUtils;
public class BookDao extends BaseDao<Book>{
public int add(Book book) throws SQLException {
String sql = "insert into t_book values("+book.getBid()+",'"+book.getBname()+"',"+book.getPrice()+")";
return this.executeUpdate(sql);
}
public int delete(Book book) throws SQLException {
String sql = "delete from t_book where bid="+book.getBid();
return this.executeUpdate(sql);
}
public int edit(Book book) throws SQLException {
String sql = "update t_book set bname='"+book.getBname()+"',price="+book.getPrice()+" where bid="+book.getBid();
return this.executeUpdate(sql);
}
public List<Book> list(Book book,PageBean pb) throws Exception {
String sql = "select * from t_book where 1=1";
if (StringUtils.isNotBlank(book.getBname())) {
sql+=" and bname like '%"+book.getBname()+"%'";
}
if (book.getBid() != 0) {
sql += " and bid="+book.getBid();
}
return this.executeQuery(pb, sql,new CallBack<Book>() {
@Override
public List<Book> forEach(ResultSet rs) throws Exception {
List<Book> ls =new ArrayList<Book>();
Book book=null;
while(rs.next()) {
book=new Book();
book.setBid(rs.getInt("bid"));
book.setBname(rs.getString("bname"));
book.setPrice(rs.getDouble("price"));
ls.add(book);
}
return ls;
}
});
}
public static void main(String[] args) throws SQLException {
Book b =new Book();
b.setBid(52);
b.setBname("99999");
b.setPrice(999);
new BookDao().edit(b);
}
}
Book
package com.zking.entity;
public class Book {
private int bid;
private String bname;
private double 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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
}
BookAction
package com.zking.web;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.ysw.utli.PageBean;
import com.zking.dao.BookDao;
import com.zking.entity.Book;
public class BookAction extends ActionSupport implements ModelDriver<Book>{
private Book book = new Book();
private BookDao db =new BookDao();
@Override
public Book getModel() {
return book;
}
public String add(HttpServletRequest req, HttpServletResponse resp) {
try {
db.add(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String delete(HttpServletRequest req, HttpServletResponse resp) {
try {
db.delete(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String edit(HttpServletRequest req, HttpServletResponse resp) {
try {
db.edit(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String list(HttpServletRequest req, HttpServletResponse resp) {
PageBean pb =new PageBean();
pb.setRequest(req);
try {
List<Book> ls = db.list(book, pb);
req.setAttribute("books", ls);
req.setAttribute("pageBean", pb);
} catch (Exception e) {
e.printStackTrace();
}
return "list";
}
public String toEdit(HttpServletRequest req, HttpServletResponse resp) {
//如果跳转的新增界面无需查询,如果是跳转的是修改界面,需要查询当前bid对应的数据,回显到界面
if (book.getBid() != 0) {
try {
List<Book> ls = db.list(book , null);
req.setAttribute("b", ls.get(0));
} catch (Exception e) {
e.printStackTrace();
}
}
return "toEdit";
}
}
|