栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

J2EE

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

J2EE

目录

 

一、前言

二、实现效果

三、代码示例

        ①MySQL部分:

        ②Jar包的导入介绍:

        ③MVC框架搭建:     

​编辑   

        ③配置web.xml和自定义xml文件(WEB-INF文件夹下)

        ④编写JSP显示界面文件


一、前言

        ①背景:

           面对编程而言,对于前台和后台或者网页显示数据的时候,可能会经常性的用到分页的功能,而我们在处理这种情况的时候,我们通常会写很多重复的代码,本文章讲的就是如何通过去解决重复分页代码问题。

        ②工具:1.Eclipse——安装        2.MySQL——安装​​​​​​​        3.Tomcat——安装

        ④jar包:1.jstl-1.2.jar、2.mysql-connector-java-5.1.44-bin.jar、3.pinyin4j-2.5.0.jar、4.standard-1.1.2.jar        jar包可以在浏览器查找

        本章中有一些是没有用上的通用代码,由于本章内容有限,仅供大家提供思路

二、实现效果

书籍分页效果

        本章重点是介绍技术的实现,因此界面相对而言比较简陋。

三、代码示例

        ①MySQL部分:

        首先我们得安装好mySQL数据库

        安装完成之后,我们进行表格的代码创建,我们需要先创建数据库本次使用的是ajf数据库,然后再创建表tb_book,以书籍表为例:

#使用你所创建的数据库
use ajf;
#创建表格
create table tb_book(
bid int not null primary key auto_increment comment '书籍编号',
bname varchar(30) not null comment '书本名称',
bpinyin varchar(30) comment '书本拼音',
bprice float default 0 comment '书本价格',
btype varchar(10) not null comment '书本类型'
) comment '书本信息表';
#自增序列:auto_increment
#mysql分页:limit 参数1,参数2
#参数1:从第几条数据开始(不包含起始位置)
#参数2:每次返回多少条数据
#第一页:从0开始,返3条
#第二页:从3开始,返3条	
#……
#以此类推		规律:页码:(page-1)*row		条数:row
#示例:
select * from tb_book limit 0,3;
#删除表格
drop table tb_book;
#查询表格
select * from tb_book;
#清空数据(不留痕迹)
truncate table tb_book;
#清空数据(可以恢复)
delete table tb_book;
#清空数据的范围大小:drop > truncate > delete

        ②Jar包的导入介绍:

         接下来就是准备导入一些jar包(工具包)了,注意:导入的jar包是在WEB-INF文件夹中的lib文件夹中

                jstl-1.2.jar、  standard-1.1.2.jar        属于:jstl中的jar包
                mysql-connector-java-5.1.44-bin.jar        属于:mySQLjar包
                pinyin4j-2.5.0.jar        属于:文字转拼音jar包
        当我们已经准备好jar包之后,那我们就可以按照MVC模式去搭建环境了。

        ③MVC框架搭建:     

  

        我们需要建立以下几个包:  1.utils    2.entity   3.dao    4.servlet   5.tag

        1.utils部分:        

        CommonUtils.java        ——遍历rs结果通用工具类

package com.web.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommonUtils {

	// 反射封装ResultSet结果集
	public static  List toList(ResultSet rs, Class cla) {
		// 定义返回结果
		List lst = new ArrayList();
		try {
			// 获取ResultSet中的列信息
			ResultSetMetaData metaData = rs.getMetaData();
			// 获取对象中的所有属性数组
			Field[] fields = cla.getDeclaredFields();
			// 循环遍历结果集ResultSet
			while (rs.next()) {
				// 通过反射机制实例化对象
				T obj = (T) cla.newInstance();
				// 循环遍历metaData
				for (int i = 0; i < metaData.getColumnCount(); i++) {
					// 获取SQL语句中的列名
					String colName = metaData.getColumnLabel(i + 1);
					// 循环遍历Fields数组
					for (Field field : fields) {
						// 获取属性名
						String fName = field.getName();
						// 判断数据表中的列名与实体中的属性名是否一致
						if (fName.toUpperCase().equals(colName.toUpperCase())) {
							// 拼接set方法 set+属性名首字母大写
							String methodName = "set" + fName.substring(0, 1).toUpperCase() + fName.substring(1);
							// 反射调用方法
							Method method = cla.getDeclaredMethod(methodName, field.getType());
							// 设置访问权限
							method.setAccessible(true);
							// 执行方法
							method.invoke(obj, rs.getObject(colName));
							break;
						}
					}
				}
				lst.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lst;
	}

	public static List> toList(ResultSet rs) {
		// 定义返回结果
		List> lst = new ArrayList>();
		try {
			// 获取ResultSet中的列信息
			ResultSetMetaData metaData = rs.getMetaData();
			// 循环遍历结果集ResultSet
			while (rs.next()) {
				Map obj=new HashMap();
				// 循环遍历metaData
				for (int i = 0; i < metaData.getColumnCount(); i++) {
					// 获取SQL语句中的列名
					String colName = metaData.getColumnLabel(i + 1);
					obj.put(colName,rs.getObject(colName));
				}
				lst.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lst;
	}
}

        DBHelper.java        ——数据库帮助实现类

package com.web.utils;

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 DBHelper {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;

	static {// 静态块执行一次,加载 驱动一次
		try {
			InputStream is = DBHelper.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);
		}
	}

	
	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 = DBHelper.getConnection();
		DBHelper.close(conn);
		System.out.println("isOracle:" + isOracle());
		System.out.println("isSQLServer:" + isSQLServer());
		System.out.println("isMysql:" + isMysql());
		System.out.println("数据库连接(关闭)成功");
	}
}

        EncodingFilter.java        ——处理中文乱码情况过滤器

package com.web.utils;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class EncodingFilter implements Filter {

	private String encoding = "UTF-8";// 默认字符集

	public EncodingFilter() {
		super();
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 中文处理必须放到 chain.doFilter(request, response)方法前面
		res.setContentType("text/html;charset=" + this.encoding);
		if (req.getMethod().equalsIgnoreCase("post")) {
			req.setCharacterEncoding(this.encoding);
		} else {
			Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
			Set set = map.keySet();// 取出所有参数名
			Iterator it = set.iterator();
			while (it.hasNext()) {
				String name = (String) it.next();
				String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"),
							this.encoding);
				}
			}
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}

}

        MD5.java        ——对字符串加密工具类

package com.web.utils;


public class MD5 {
	
	private static final int S11 = 7;

	private static final int S12 = 12;

	private static final int S13 = 17;

	private static final int S14 = 22;

	private static final int S21 = 5;

	private static final int S22 = 9;

	private static final int S23 = 14;

	private static final int S24 = 20;

	private static final int S31 = 4;

	private static final int S32 = 11;

	private static final int S33 = 16;

	private static final int S34 = 23;

	private static final int S41 = 6;

	private static final int S42 = 10;

	private static final int S43 = 15;

	private static final int S44 = 21;

	private static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0 };

	
	private long[] state = new long[4]; // state (ABCD)

	private long[] count = new long[2];// number of bits, modulo 2^64(lsbfirst)

	private byte[] buffer = new byte[64]; // input buffer

	
	private byte[] digest = new byte[16];

	public MD5() {
		md5Init();
	}

	
	public String getMD5ofStr(String inbuf) {
		md5Init();
		md5Update(inbuf.getBytes(), inbuf.length());
		md5Final();
		String digestHexStr = "";
		for (int i = 0; i < 16; i++) {
			digestHexStr += byteHEx(digest[i]);
		}
		return digestHexStr;

	}

	
	private void md5Init() {
		count[0] = 0L;
		count[1] = 0L;
		// 

	private long F(long x, long y, long z) {
		return (x & y) | ((~x) & z);

	}

	private long G(long x, long y, long z) {
		return (x & z) | (y & (~z));

	}

	private long H(long x, long y, long z) {
		return x ^ y ^ z;
	}

	private long I(long x, long y, long z) {
		return y ^ (x | (~z));
	}

	

	private long FF(long a, long b, long c, long d, long x, long s, long ac) {
		a += F(b, c, d) + x + ac;
		a = ((int) a << s) | ((int) a >>> (32 - s));
		a += b;
		return a;
	}

	private long GG(long a, long b, long c, long d, long x, long s, long ac) {
		a += G(b, c, d) + x + ac;
		a = ((int) a << s) | ((int) a >>> (32 - s));
		a += b;
		return a;
	}

	private long HH(long a, long b, long c, long d, long x, long s, long ac) {
		a += H(b, c, d) + x + ac;
		a = ((int) a << s) | ((int) a >>> (32 - s));
		a += b;
		return a;
	}

	private long II(long a, long b, long c, long d, long x, long s, long ac) {
		a += I(b, c, d) + x + ac;
		a = ((int) a << s) | ((int) a >>> (32 - s));
		a += b;
		return a;
	}

	
	private void md5Update(byte[] inbuf, int inputLen) {

		int i, index, partLen;
		byte[] block = new byte[64];
		index = (int) (count[0] >>> 3) & 0x3F;
		// 
		if ((count[0] += (inputLen << 3)) < (inputLen << 3))
			count[1]++;
		count[1] += (inputLen >>> 29);

		partLen = 64 - index;

		// Transform as many times as possible.
		if (inputLen >= partLen) {
			md5Memcpy(buffer, inbuf, index, 0, partLen);
			md5Transform(buffer);

			for (i = partLen; i + 63 < inputLen; i += 64) {

				md5Memcpy(block, inbuf, 0, i, 64);
				md5Transform(block);
			}
			index = 0;

		} else

			i = 0;

		// 
		md5Memcpy(buffer, inbuf, index, i, inputLen - i);

	}

	
	private void md5Final() {
		byte[] bits = new byte[8];
		int index, padLen;

		// 
		Encode(bits, count, 8);

		// 
		md5Update(bits, 8);

		// 
		Encode(digest, state, 16);

	}

	

	private void md5Memcpy(byte[] output, byte[] input, int outpos, int inpos,
			int len) {
		int i;

		for (i = 0; i < len; i++)
			output[outpos + i] = input[inpos + i];
	}

	
	private void md5Transform(byte block[]) {
		long a = state[0], b = state[1], c = state[2], d = state[3];
		long[] x = new long[16];

		Decode(x, block, 64);

		
		a = FF(a, b, c, d, x[0], S11, 0xd76aa478L); 
		d = FF(d, a, b, c, x[1], S12, 0xe8c7b756L); 
		c = FF(c, d, a, b, x[2], S13, 0x242070dbL); 
		b = FF(b, c, d, a, x[3], S14, 0xc1bdceeeL); 
		a = FF(a, b, c, d, x[4], S11, 0xf57c0fafL); 
		d = FF(d, a, b, c, x[5], S12, 0x4787c62aL); 
		c = FF(c, d, a, b, x[6], S13, 0xa8304613L); 
		b = FF(b, c, d, a, x[7], S14, 0xfd469501L); 
		a = FF(a, b, c, d, x[8], S11, 0x698098d8L); 
		d = FF(d, a, b, c, x[9], S12, 0x8b44f7afL); 
		c = FF(c, d, a, b, x[10], S13, 0xffff5bb1L); 
		b = FF(b, c, d, a, x[11], S14, 0x895cd7beL); 
		a = FF(a, b, c, d, x[12], S11, 0x6b901122L); 
		d = FF(d, a, b, c, x[13], S12, 0xfd987193L); 
		c = FF(c, d, a, b, x[14], S13, 0xa679438eL); 
		b = FF(b, c, d, a, x[15], S14, 0x49b40821L); 

		
		a = GG(a, b, c, d, x[1], S21, 0xf61e2562L); 
		d = GG(d, a, b, c, x[6], S22, 0xc040b340L); 
		c = GG(c, d, a, b, x[11], S23, 0x265e5a51L); 
		b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aaL); 
		a = GG(a, b, c, d, x[5], S21, 0xd62f105dL); 
		d = GG(d, a, b, c, x[10], S22, 0x2441453L); 
		c = GG(c, d, a, b, x[15], S23, 0xd8a1e681L); 
		b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8L); 
		a = GG(a, b, c, d, x[9], S21, 0x21e1cde6L); 
		d = GG(d, a, b, c, x[14], S22, 0xc33707d6L); 
		c = GG(c, d, a, b, x[3], S23, 0xf4d50d87L); 
		b = GG(b, c, d, a, x[8], S24, 0x455a14edL); 
		a = GG(a, b, c, d, x[13], S21, 0xa9e3e905L); 
		d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8L); 
		c = GG(c, d, a, b, x[7], S23, 0x676f02d9L); 
		b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8aL); 

		
		a = HH(a, b, c, d, x[5], S31, 0xfffa3942L); 
		d = HH(d, a, b, c, x[8], S32, 0x8771f681L); 
		c = HH(c, d, a, b, x[11], S33, 0x6d9d6122L); 
		b = HH(b, c, d, a, x[14], S34, 0xfde5380cL); 
		a = HH(a, b, c, d, x[1], S31, 0xa4beea44L); 
		d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9L); 
		c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60L); 
		b = HH(b, c, d, a, x[10], S34, 0xbebfbc70L); 
		a = HH(a, b, c, d, x[13], S31, 0x289b7ec6L); 
		d = HH(d, a, b, c, x[0], S32, 0xeaa127faL); 
		c = HH(c, d, a, b, x[3], S33, 0xd4ef3085L); 
		b = HH(b, c, d, a, x[6], S34, 0x4881d05L); 
		a = HH(a, b, c, d, x[9], S31, 0xd9d4d039L); 
		d = HH(d, a, b, c, x[12], S32, 0xe6db99e5L); 
		c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8L); 
		b = HH(b, c, d, a, x[2], S34, 0xc4ac5665L); 

		
		a = II(a, b, c, d, x[0], S41, 0xf4292244L); 
		d = II(d, a, b, c, x[7], S42, 0x432aff97L); 
		c = II(c, d, a, b, x[14], S43, 0xab9423a7L); 
		b = II(b, c, d, a, x[5], S44, 0xfc93a039L); 
		a = II(a, b, c, d, x[12], S41, 0x655b59c3L); 
		d = II(d, a, b, c, x[3], S42, 0x8f0ccc92L); 
		c = II(c, d, a, b, x[10], S43, 0xffeff47dL); 
		b = II(b, c, d, a, x[1], S44, 0x85845dd1L); 
		a = II(a, b, c, d, x[8], S41, 0x6fa87e4fL); 
		d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0L); 
		c = II(c, d, a, b, x[6], S43, 0xa3014314L); 
		b = II(b, c, d, a, x[13], S44, 0x4e0811a1L); 
		a = II(a, b, c, d, x[4], S41, 0xf7537e82L); 
		d = II(d, a, b, c, x[11], S42, 0xbd3af235L); 
		c = II(c, d, a, b, x[2], S43, 0x2ad7d2bbL); 
		b = II(b, c, d, a, x[9], S44, 0xeb86d391L); 

		state[0] += a;
		state[1] += b;
		state[2] += c;
		state[3] += d;

	}

	
	private void Encode(byte[] output, long[] input, int len) {
		int i, j;

		for (i = 0, j = 0; j < len; i++, j += 4) {
			output[j] = (byte) (input[i] & 0xffL);
			output[j + 1] = (byte) ((input[i] >>> 8) & 0xffL);
			output[j + 2] = (byte) ((input[i] >>> 16) & 0xffL);
			output[j + 3] = (byte) ((input[i] >>> 24) & 0xffL);
		}
	}

	
	private void Decode(long[] output, byte[] input, int len) {
		int i, j;

		for (i = 0, j = 0; j < len; i++, j += 4)
			output[i] = b2iu(input[j]) | (b2iu(input[j + 1]) << 8)
					| (b2iu(input[j + 2]) << 16) | (b2iu(input[j + 3]) << 24);

		return;
	}

	
	private static long b2iu(byte b) {
		return b < 0 ? b & 0x7F + 128 : b;
	}

	
	private static String byteHEx(byte ib) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char[] ob = new char[2];
		ob[0] = Digit[(ib >>> 4) & 0x0F];
		ob[1] = Digit[ib & 0x0F];
		String s = new String(ob);
		return s;
	}

	public static void main(String args[]) {
		String source = "888888";
		MD5 md5 = new MD5();
		String s1 = md5.getMD5ofStr(source);// length=32
		System.out.println(s1);
		//21218CCA77804D2BA1922C33E0151105
	}
}

        PinYinUtil.java        ——汉字转拼音工具类

package com.web.utils;

import java.util.regex.Pattern;

import net.sourceforge.pinyin4j.PinyinHelper;



public class PinYinUtil {
	
	private static final String regexStr = "[u4e00-u9fa5]";

	
	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;
	}

	
	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 = "任保存并加入题库";
		System.out.println(PinYinUtil.toPinyin(s).toLowerCase());
	}

}

                StringUtils.java        ——判断字符串是否为空方法类

package com.web.utils;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

        config.properties        ——连接数据库信息存放文件

#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#pwd=123


#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1433;DatabaseName=test1
#user=sa
#pwd=123


#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888


#mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/AJF?useUnicode=true&characterEncoding=UTF-8&useSSL=false
#url=jdbc:mysql://localhost:3306/bookshop?useUnicode=true&characterEncoding=UTF-8
user=root
pwd=1234

        2.entity:

        Book.java        ——书籍实体类

package com.web.entity;

import java.io.Serializable;


public class Book implements Serializable {

	
	private static final long serialVersionUID = 1L;

	private Integer bid;//书籍编号
	private String bname;//书籍名字
	private String bpinyin;//书籍拼音
	private Float bprice;//书籍价格
	private String btype;//书籍类型
	
	public Book() {
		
	}

	public Book(Integer bid, String bname, String bpinyin, Float bprice, String btype) {
		super();
		this.bid = bid;
		this.bname = bname;
		this.bpinyin = bpinyin;
		this.bprice = bprice;
		this.btype = btype;
	}

	public Book(String bname, String bpinyin, Float bprice, String btype) {
		super();
		this.bname = bname;
		this.bpinyin = bpinyin;
		this.bprice = bprice;
		this.btype = btype;
	}

	public Integer getBid() {
		return bid;
	}

	public void setBid(Integer bid) {
		this.bid = bid;
	}

	public String getBname() {
		return bname;
	}

	public void setBname(String bname) {
		this.bname = bname;
	}

	public String getBpinyin() {
		return bpinyin;
	}

	public void setBpinyin(String bpinyin) {
		this.bpinyin = bpinyin;
	}

	public Float getBprice() {
		return bprice;
	}

	public void setBprice(Float bprice) {
		this.bprice = bprice;
	}

	public String getbtype() {
		return btype;
	}

	public void setbtype(String btype) {
		this.btype = btype;
	}

	@Override
	public String toString() {
		return "Book [bid=" + bid + ", bname=" + bname + ", bpinyin=" + bpinyin + ", bprice=" + bprice + ", btype="
				+ btype + "]";
	}
}

        PageBean.java        ——书籍分页实体类

package com.web.entity;

import java.io.Serializable;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class PageBean implements Serializable {

	
	private static final long serialVersionUID = 1L;
	
	private Integer page = 1;//页码
	private Integer rows = 10;//行数
	private Integer total = 0;//总条数
	private boolean pageination = true;//是否分页
	
	//保存文件地址
	private String url;
	//保存参数
	private Map map;
	
	public PageBean() {
		
	}
	
	
	public void setRequest(HttpServletRequest req) {
		//获取前端传入的请求参数(分页三要素)
		String page = req.getParameter("page");
		String rows = req.getParameter("rows");
		String pagination = req.getParameter("pagination");
		
		//将结果保存到本类对象中
		this.setPage(page);
		this.setRows(rows);
		this.setPageination(pagination);
		
		//获取上一次请求的请求路径
		// http://localhost:8080/pagination/bookAction.action
		// req.getRequestURI()==/pagination/bookAction.action
		// req.getContextPath()==/pagination
		// req.getServletPath()==/bookAction.action
		this.url = req.getRequestURI();
		
		// name="bookname"  -> put("bookname",new String[]{"1"})
		// 
		//获取上一次请求的请求参数 Map
		this.map = req.getParameterMap();
	}
	
	//获取最大页码
	public int getMaxPager() {
		int max = this.total/this.getRows();
		if(this.total%this.rows!=0)
			max++;
		return max;
	}
	//上一页
	public int getProviousPager() {
		int pro = this.page-1;
		//判断页码
		if(pro<1)
			pro=1;
		return pro;
	}
	
	//下一页
	public int getNextPager() {
		int next = this.page+1;
		if(next>=this.getMaxPager())
			next=this.getMaxPager();
		return next;
	}
	public PageBean(Integer page, Integer rows, Integer total, boolean pageination) {
		super();
		this.page = page;
		this.rows = rows;
		this.total = total;
		this.pageination = pageination;
	}
	
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map getMap() {
		return map;
	}

	public void setMap(Map map) {
		this.map = map;
	}

	//计算开始的limit分页开始的位置
	public Integer getStartIndex() {
		return (page-1)*this.rows;
	}
	//页码
	public Integer getPage() {
		return page;
	}
	
	public void setPage(String page) {
		if(null!=page)
		this.page = Integer.parseInt(page);
	}
	//行数
	public Integer getRows() {
		return rows;
	}

	public void setRows(String rows) {
		if(null!=rows)
		this.rows = Integer.parseInt(rows);
	}
	//总条数
	public Integer getTotal() {
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public boolean isPageination() {
		return pageination;
	}

	public void setPageination(String pageination) {
		if(null!=pageination)
		this.pageination = Boolean.parseBoolean(pageination);
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pageination=" + pageination
				+ ", url=" + url + ", map=" + map + "]";
	}

}

        3.dao:

        BaseDao.java        ——简写增删改查通用方法类

package com.web.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.web.utils.DBHelper;


public class BaseDao {
	protected Connection conn = null;// 连接对象
	protected PreparedStatement stmt = null;// 执行对象
	protected ResultSet rs = null;// 结果集对象
	protected Integer n;

	
	public Integer executeUpdate(String sql, Object... obj) {
		// 获取连接对象
		conn = DBHelper.getConnection();
		try {
			// 获取执行对象
			stmt = conn.prepareStatement(sql);
			// 判断是否存在数据
			// 需要给占位符进行赋值
			if (null != obj) {
				for (int i = 0; i < obj.length; i++) {
					stmt.setObject(i + 1, obj[i]);
				}
			}
			// 进行执行
			n = stmt.executeUpdate();
			System.out.println(n);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(conn, stmt, null);
		}
		// 结果返出
		return n;
	}

	
	public ResultSet executeQuery(String sql, Object... obj) {
		// 获取连接对象
		conn = DBHelper.getConnection();
		try {
			// 获取执行对象
			stmt = conn.prepareStatement(sql);
			// 判断是否存在数据
			// 需要给占位符进行赋值
			if (null != obj) {
				for (int i = 0; i < obj.length; i++) {
					stmt.setObject(i + 1, obj[i]);
				}
			}
			// 进行执行
			rs = stmt.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 结果返出
		return rs;
	}
}

        BaseDaob.java        ——分页实现方法类

package com.web.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.web.entity.PageBean;
import com.web.utils.DBHelper;

public class BaseDaob {
	public static interface CallBack{
		//该方法只用于遍历rs结果集对象中的数据,并返回List结果
		//最后面谁要去遍历结果集,谁就得去实现这个接口的方法
		public List foreachRs(ResultSet rs) throws SQLException;
	}
	
	
	public List executeQuery(String sql, PageBean pb, CallBack callback){
		Connection conn = null;//连接对象
		PreparedStatement stmt = null;//
		ResultSet rs = null;
		List list = null;
		try {
			conn = DBHelper.getConnection();
			//获取连接对象
			stmt = conn.prepareStatement(sql);
			//判断是否分页
			if(null!=pb && pb.isPageination()) {
				//①确定是否分页
				//①根据条件获取总记录条数
				String countSQL = this.getCountSQL(sql);
				//创建执行对象
				stmt = conn.prepareStatement(countSQL);
				//执行SQL并返回总记录数
				rs = stmt.executeQuery();
				System.out.println(rs.toString());
				//由于只有单挑记录,因此使用if
				if(rs.next()) {
					pb.setTotal(rs.getInt(1));
				}
				//②根据满足条件获取查询SQL——limit
				sql = this.getPageSQL(sql, pb);
			}
			//②满足条件的分页查询SQL
			//①不分页(普通查询)
			//①根据满足条件查询数据
			//②根据满足条件获取查询SQL——limit
			//创建执行对象
			System.out.println(sql);
			stmt = conn.prepareStatement(sql);
			//执行
			rs = stmt.executeQuery();
			//将rs存入到foreachRs()方法中
			 list = callback.foreachRs(rs); 
			 return list;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBHelper.close(conn, stmt, rs);
		}
		return list;
	}
	
	private String getCountSQL(String sql) {
		return "select count(0) from ("+sql+") temp";
	}
	
	private String getPageSQL(String sql, PageBean pb) {
		return sql+" limit "+pb.getStartIndex()+","+pb.getRows();
	}
	
}

        BookDao.java        ——书籍方法类

package com.web.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.web.dao.BaseDaob.CallBack;
import com.web.entity.Book;
import com.web.entity.PageBean;
import com.web.utils.DBHelper;
import com.web.utils.StringUtils;

public class BookDao extends BaseDao {
	private List list = null;
	private Book book = null;

	// 增
	
	public void addBook(Book book) {
		// System.out.println(book);
		Integer n = this.executeUpdate("insert into tb_book(bname,bpinyin,bprice,btype) values(?,?,?,?)",
				new Object[] { book.getBname(), book.getBpinyin(), book.getBprice(), book.getbtype() });
		// 判断抛出异常
		if (n == 0) {
			throw new RuntimeException("影响行数为0,执行失败");
		}
	}

	// 删

	// 改

	// 查
	public List queryBookDim(Book book, PageBean pb) {
		// 实例化list集合
		list = new ArrayList();
		//定义sql
		String sql = "select bid,bname,bpinyin,bprice,btype from tb_book where 1=1";
		// 判断book中bname属性是否为空
		if (StringUtils.isNotBlank(book.getBname())) {
			sql += " and bname like '%" + book.getBname() + "%'";
			// 按照编号降序排序
			sql += " order by bid desc";
		}
		System.out.println(sql);
		return new BaseDaob().executeQuery(sql, pb, new CallBack() {
			
			public List foreachRs(ResultSet rs) throws SQLException {
				list = new ArrayList();
				try {
					// 遍历
					while (rs.next()) {
						Book book = new Book();
						// 将数据封装到Book实体对象中
						book = new Book(rs.getInt("bid"), rs.getString("bname"), rs.getString("bpinyin"), rs.getFloat("bprice"),
								rs.getString("btype"));
						// 添加到集合中
						list.add(book);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					DBHelper.close(conn, stmt, rs);
				}
				return list;
			}
			
		});
		
	
	}
}

        BookDaoTest.java        ——书籍方法测试类

package com.web.dao;

import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.web.entity.Book;
import com.web.entity.PageBean;
import com.web.utils.PinYinUtil;


public class BookDaoTest {

	
	Book book = null;//实体
	BookDao bookDao = new BookDao();
	@Before
	public void setUp() throws Exception {
		//System.out.println("setUp");
		book = new Book();
		
		
		
	}

	@After
	public void tearDown() throws Exception {
		//System.out.println("tearDown");
	}

	@Test
	public void testAddBook() {
		//System.out.println("testAddBook");
		//循环添加50条书籍信息
		for (int i = 1; i <= 50; i++) {
			book = new Book();
			book.setBname("史记第"+i+"章");
			book.setBpinyin(PinYinUtil.toPinyin("史记第"+i+"章").toLowerCase());
			book.setBprice(34.5f);
			book.setbtype("神话");
			//System.out.println(book);
			//调用添加数据的方法
			bookDao.addBook(book);
		}
	}

	@Test
	public void testQueryBookDim() {
		//System.out.println("testQueryBookDim");
		PageBean pb = new PageBean();
		pb.setPage("2");
		pb.setRows("5");
		List books = bookDao.queryBookDim(book, pb);
		System.out.println(books);
		System.out.println("总记录数:"+pb.getTotal());
		books.forEach(System.out::println);
	}

}

        4.servlet:

        BookServlet.java        ——实现数据(是否分页)显示servlet

package com.web.dao;

import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.web.entity.Book;
import com.web.entity.PageBean;
import com.web.utils.PinYinUtil;


public class BookDaoTest {

	
	Book book = null;//实体
	BookDao bookDao = new BookDao();
	@Before
	public void setUp() throws Exception {
		//System.out.println("setUp");
		book = new Book();
		
		
		
	}

	@After
	public void tearDown() throws Exception {
		//System.out.println("tearDown");
	}

	@Test
	public void testAddBook() {
		//System.out.println("testAddBook");
		//循环添加50条书籍信息
		for (int i = 1; i <= 50; i++) {
			book = new Book();
			book.setBname("史记第"+i+"章");
			book.setBpinyin(PinYinUtil.toPinyin("史记第"+i+"章").toLowerCase());
			book.setBprice(34.5f);
			book.setbtype("神话");
			//System.out.println(book);
			//调用添加数据的方法
			bookDao.addBook(book);
		}
	}

	@Test
	public void testQueryBookDim() {
		//System.out.println("testQueryBookDim");
		PageBean pb = new PageBean();
		pb.setPage("2");
		pb.setRows("5");
		List books = bookDao.queryBookDim(book, pb);
		System.out.println(books);
		System.out.println("总记录数:"+pb.getTotal());
		books.forEach(System.out::println);
	}

}

        5.tag:

        PaginationTag.java        ——自定义标签帮助类(通过该类实现分页)

package com.web.tag;

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.web.entity.PageBean;

public class PaginationTag extends BodyTagSupport {

	
	private static final long serialVersionUID = 1L;
	private PageBean pageBean;
	
	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}

	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.write(toHtml());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}
	
	private String toHtml() {
		//判断是否分页
		if(null==pageBean||!pageBean.isPageination())
			return "";
		else {
			StringBuilder sb=new StringBuilder();
			//TODO
			sb.append("");
			
			//拼接Form表单
			sb.append("
"); //设置page隐藏域 sb.append(""); //拼接请求参数集合 Map map = pageBean.getMap(); //获取请求参数集合键值对 Set> entrySet = map.entrySet(); //遍历请求参数键值对 for (Entry entry : entrySet) { //获取请求参数名,也就是来自于表单中的name属性名称 String name=entry.getKey(); //如果参数为page,则continue跳过 if(name.equals("page")) continue; //获取请求参数对应的值,String[] String[] values=entry.getValue(); //遍历value值 for (String value : values) { //拼接请求参数 sb.append(""); } } sb.append(""); //拼接共几页/第几页 sb.append("共"+pageBean.getMaxPager()+"页/第"+pageBean.getPage()+"页,"); //拼接首页、上一页、下一页、末页 if(pageBean.getPage()==1) sb.append("首页 上一页 "); else { sb.append("首页 "); sb.append("上一页 "); } if(pageBean.getPage()==pageBean.getMaxPager()) sb.append("下一页 末页 "); else { sb.append("下一页 "); sb.append("末页 "); } //拼接跳转页码 sb.append(""); sb.append(""); //拼接javascript跳转方法 sb.append(""); sb.append(""); return sb.toString(); } } public PageBean getPageBean() { return pageBean; } public void setPageBean(PageBean pageBean) { this.pageBean = pageBean; } }

        ③配置web.xml和自定义xml文件(WEB-INF文件夹下)

        web.xml        ——web项目中的标签配置文件(一般用于配置:servlet和filter和listener)



  Web_03
  
  
   
  encodingFilter
  com.web.utils.EncodingFilter
    
  
  
    encodingFilter
    /*
    
    
 
     
  
  bookSelect
  com.web.servlet.BookServlet
  
  
    bookSelect
    /bookServlet.do
    
    
       
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  

        z.tld        ——自定义xml




	
	1.0
	
	1.2
	
	z
	
	/zking

	
		
		pagination
		
		
		com.web.tag.PaginationTag
		
		empty
		
		
			
			pageBean
			
			true
			
			true
		
	

        ④编写JSP显示界面文件

        bookList.jsp        ——书籍展示界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@taglib prefix="z" uri="/zking"%>




书籍




	

书籍编号 书籍名称 书籍拼音 书籍价格 书籍类型
${book.bid } ${book.bname } ${book.bpinyin } ${book.bprice } ${book.btype }


<%-- ${pageBean } --%> <%--
第${pageBean.getPage() }页/页${pageBean.getMaxPager() }码 老版本: 首页 上一页 下一页 尾页 首页 上一页 下一页 末页 --%>

        以上就是本章的全部内容!感谢观看!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/978030.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号