IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> 利用框架实现开发 -> 正文阅读

[大数据]利用框架实现开发

思维导图

?代码

BaseDao.java

package com.lhw.dao;

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

import com.zking.utli.DBAccess;
import com.zking.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.java

package com.lhw.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.lhw.entity.Book;
import com.zking.utli.DBAccess;
import com.zking.utli.PageBean;
import com.zking.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);
	}
}

?mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<action path="/book" type="com.lhw.web.BookAction">
		<forward name="list" path="/bookList.jsp" redirect="false" />
		<forward name="toList" path="/book.action?name=list" redirect="true" />
		<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
	</action>
</config>

BookAction

package com.lhw.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.lhw.dao.BookDao;
import com.lhw.entity.Book;
import com.lhw.framework.ActionSupport;
import com.lhw.framework.ModelDriver;
import com.zking.utli.PageBean;

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

}

PageTag.java

package com.zking.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.zking.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()+")'>&lt;</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()+")'>&gt;</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.java

package com.zking.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("数据库连接(关闭)成功");
	}
}

EncodingFiter.java

package com.zking.utli;

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.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 中文乱码处理
 * 
 */
public class EncodingFiter implements Filter {

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

	public EncodingFiter() {
		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();
		}
	}

}

PageBean.java

package com.zking.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.setParamMap(req.getParameterMap());
		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.java

package com.zking.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.java

package com.zking.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);
	}

}

?运行结果

  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2021-09-03 11:59:18  更:2021-09-03 12:00:01 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 16:56:56-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码