package com.product.dbutil.register.action;控制层
package com.product.dbutil.register.service;服务层
package com.product.dbutil.register.dao;数据访问层。
控制层的定义代码:
package com.product.dbutil.register.action; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.product.dbutil.register.dao.RegisterDao; import com.product.dbutil.register.service.RegisterService; import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH; public class RegisterAction extends HttpServlet { private RegisterService service;//服务层接口 /** * Constructor of the object. */ public RegisterAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response);//复写doPost方法 } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getContextPath();//用来重定向 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String username = request.getParameter("username"); String pswd = request.getParameter("pswd"); String realname = request.getParameter("realname"); List<Object> params = new ArrayList<Object>(); params.add(username); params.add(pswd); params.add(realname); boolean flag = service.registerUser(params); if (flag) { response.sendRedirect(path + "/index.jsp");//重定向的实现 } out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException * if an error occurs */ public void init() throws ServletException { // Put your code here service = new RegisterDao(); } }
服务层,定义业务逻辑处理规范。代码如下:
package com.product.dbutil.register.service; import java.util.List; public interface RegisterService { //完成用户的注册功能 public boolean registerUser(List<Object> params); }
package com.product.dbutil.register.dao; import java.util.List; import com.product.dbutil.jdbc.JdbcUtils; import com.product.dbutil.register.service.RegisterService; public class RegisterDao implements RegisterService { private JdbcUtils utils = null; public RegisterDao() { //操作数据库 utils = new JdbcUtils(); } /* * 完成了对用户注册的dao的编写 * * @see * com.product.dbutil.register.service.RegisterService#registerUser(java * .util.List) */ public boolean registerUser(List<Object> params) { // TODO Auto-generated method stub boolean flag = false; String sql = "insert into userinfo(username,pswd,realname) values(?,?,?)"; try { // 先获得链接 utils.getConnection(); flag = utils.updateByPreparedStatement(sql, params); System.out.println("-flag-->>" + flag); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } finally { // 关闭数据库的链接 utils.releaseConn(); } return flag; } }
数据库工具类:
package com.product.dbutil.jdbc; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JdbcUtils { // 表示定义数据库的用户名 private final String USERNAME = "root"; // 定义数据库的密码 private final String PASSWORD = "admin"; // 定义数据库的驱动信息 private final String DRIVER = "com.mysql.jdbc.Driver"; // 定义访问数据库的地址 private final String URL = "jdbc:mysql://localhost:3306/mydb"; // 定义数据库的链接 private Connection connection; // 定义sql语句的执行对象 private PreparedStatement pstmt; // 定义查询返回的结果集合 private ResultSet resultSet; // 实现批处理操作的功能 private Statement stmt; public JdbcUtils() { try { Class.forName(DRIVER); System.out.println("注册驱动成功!!"); } catch (Exception e) { // TODO: handle exception } } // 定义获得数据库的链接 public Connection getConnection() { try { connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (Exception e) { // TODO: handle exception } return connection; } public boolean deleteByBatch(String[] sql) throws SQLException{ boolean flag = false; stmt = connection.createStatement(); if(sql!=null){ for(int i=0;i<sql.length;i++){ stmt.addBatch(sql[i]); } } int[] count = stmt.executeBatch(); if(count!=null){ flag = true; } return flag; } /** * 完成对数据库的表的添加删除和修改的操作 * * @param sql * @param params * @return * @throws SQLException */ public boolean updateByPreparedStatement(String sql, List<Object> params) throws SQLException { boolean flag = false; int result = -1;// 表示当用户执行添加删除和修改的时候所影响数据库的行数 pstmt = connection.prepareStatement(sql); int index = 1; if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } result = pstmt.executeUpdate(); flag = result > 0 ? true : false; return flag; } /** * 查询返回单条记录 * * @param sql * @param params * @return * @throws SQLException */ public Map<String, Object> findSimpleResult(String sql, List<Object> params) throws SQLException { Map<String, Object> map = new HashMap<String, Object>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery();// 返回查询结果 ResultSetMetaData metaData = resultSet.getMetaData(); int col_len = metaData.getColumnCount();// 获得列的名称 while (resultSet.next()) { for (int i = 0; i < col_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } map.put(cols_name, cols_value); } } return map; } /** * 查询返回多行记录 * * @param sql * @param params * @return * @throws SQLException */ public List<Map<String, Object>> findMoreResult(String sql, List<Object> params) throws SQLException { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } map.put(cols_name, cols_value); } list.add(map); } return list; } // jdbc的封装可以用反射机制来封装: public <T> T findSimpleRefResult(String sql, List<Object> params, Class<T> cls) throws Exception { T resultObject = null; int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { // 通过反射机制创建实例 resultObject = cls.newInstance(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } Field field = cls.getDeclaredField(cols_name); field.setAccessible(true);// 打开javabean的访问private权限 field.set(resultObject, cols_value); } } return resultObject; } /** * 通过反射机制访问数据库 * * @param <T> * @param sql * @param params * @param cls * @return * @throws Exception */ public <T> List<T> findMoreRefResult(String sql, List<Object> params, Class<T> cls) throws Exception { List<T> list = new ArrayList<T>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { T resultObject = cls.newInstance(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } Field field = cls.getDeclaredField(cols_name); field.setAccessible(true); field.set(resultObject, cols_value); } list.add(resultObject); } return list; } public void releaseConn() { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
原文地址:http://blog.csdn.net/u014600432/article/details/41414981