zoukankan      html  css  js  c++  java
  • 每日记载内容总结41

    1.dbcp连接数据库(附带基本数据库操作方法)

    package com.nplus.dbcp;
    
    import java.io.InputStream;
    import java.sql.Connection;
    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;
    import java.util.Properties;
    
    import org.apache.commons.dbcp.BasicDataSource;
    import org.apache.commons.dbcp.BasicDataSourceFactory;
    import org.apache.log4j.Logger;
    
    import com.nplus.help.StringHelper;
    
    public class Dbcp {
    
        public static Logger logger = Logger.getLogger(Dbcp.class);
        private static final String config = "commons-dbcp.properties";
        private BasicDataSource ds;
        private static Dbcp db;
        private Connection conn = null;
        private Statement stmt = null;
    
        private Dbcp(String config) {
            this.ds = null;
            try {
                this.ds = createDataSource(config);
            } catch (Throwable thr) {
                throw new RuntimeException(thr);
            }
        }
    
        public synchronized static Dbcp getInstance() {
    
            if (db == null)
                try {
                    db = new Dbcp(config);
                } catch (Exception e) {
                    e.printStackTrace();
                    
                }
            return db;
        }
    
        public static BasicDataSource createDataSource(String propertiesFile)
                throws Exception {
            Properties properties = new Properties();
            // System.out.println("dbcp
            // path="+Dbcp.class.getResource(".").getPath());
            InputStream stream = Dbcp.class.getResourceAsStream(propertiesFile);
            properties.load(stream);
            stream.close();
            BasicDataSource ds = (BasicDataSource) BasicDataSourceFactory
                    .createDataSource(properties);
            return ds;
        }
    
        public Connection getConnection() throws SQLException {
            return this.ds.getConnection();
        }
    
        public static void close(Connection conn) {
            if (conn != null)
                try {
                    conn.close();
                } catch (Throwable localThrowable) {
                }
        }
    
        public static void close(Statement stmt) {
            if (stmt != null)
                try {
                    stmt.close();
                } catch (Throwable localThrowable) {
                }
        }
    
        public static void close(ResultSet rs) {
            if (rs != null)
                try {
                    rs.close();
                } catch (Throwable localThrowable) {
                }
        }
    
        public static void close(Connection conn, Statement stmt, ResultSet rs) {
            close(rs);
            close(stmt);
            close(conn);
        }
    
        public static void close(Connection conn, Statement stmt) {
            close(stmt);
            close(conn);
        }
    
        public static void close(Statement stmt, ResultSet rs) {
            close(rs);
            close(stmt);
        }
    
        public int getExecuteCount(String sql) {
            int queryNum = -1;
            ResultSet rs = null;
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = this.getConnection();
                stmt = conn.createStatement();
                rs = stmt.executeQuery(sql);
                if (rs != null) {
                    rs.next();
                    queryNum = rs.getInt(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(sql);
            } finally {
                closeAll(conn, rs, stmt);
    
            }
            return queryNum;
        }
        
        public int getExecuteCount(String sql,Object[] params) {
            int queryNum = -1;
            ResultSet rs = null;
            Connection conn = null;
            PreparedStatement ps = null;
            try {
                conn = this.getConnection();
                ps = conn.prepareStatement(sql);
                for(int i=0;i<params.length;i++) {
                    ps.setObject(i+1, params[i]);
                }
                rs = ps.executeQuery();
                if (rs != null) {
                    rs.next();
                    queryNum = rs.getInt(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(new StringHelper().getSql(sql, params));
            } finally {
                closeAll(conn, rs, stmt);
                
            }
            return queryNum;
        }
    
        public void closeAll(Connection conn, ResultSet rs, Statement stmt) {
            close(conn);
            close(rs);
            close(stmt);
        }
    
        public String getNextSequence(String seq_name) {
            String sql = "select " + seq_name + ".nextval seq_value from dual";
            Map map = db.getValue(sql);
            return (String) map.get("SEQ_VALUE");
        }
    
        public String getStringValue(String sql) {
            Map map = db.getValue(sql);
            return (String) map.get("STRING_VALUE");
        }
    
        public int execute(String sqlstr) {
            ResultSet rs = null;
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = getConnection();
                stmt = conn.createStatement();
                stmt.execute(sqlstr);
                return 1;
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(sqlstr);
            } finally {
                closeAll(conn, rs, stmt);
            }
            return 0;
        }
        
        public int execute(String sql,Object[] params) {
            ResultSet rs = null;
            Connection conn = null;
            PreparedStatement ps = null;
            try {
                conn = getConnection();
                ps = conn.prepareStatement(sql);
                for(int i=0;i<params.length;i++) {
                    ps.setObject(i+1, params[i]);
                }
                ps.execute();
                return 1;
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(new StringHelper().getSql(sql, params));
            } finally {
                closeAll(conn, rs, ps);
            }
            return 0;
        }
    
        public ArrayList getList(String sqlString) {
            ArrayList<Map> pkv = new ArrayList<Map>();
            ResultSet rs = null;
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = getConnection();
                stmt = conn.createStatement();
                rs = stmt.executeQuery(sqlString);
                ResultSetMetaData rsmd = rs.getMetaData();
                int num = rsmd.getColumnCount();
                while (rs.next()) {
                    Map map = new HashMap();
                    for (int i = 1; i <= num; i++) {
                        String key = rsmd.getColumnName(i);
                        String value = rs.getString(i);
                        if (value == null)
                            value = "";
                        map.put(key, value);
                    }
                    pkv.add(map);
                }
            } catch (SQLException e) {
                logger.error(sqlString);
                logger.error(e.toString());
            } finally {
                closeAll(conn, rs, stmt);
            }
            return pkv;
        }
    
        public Map getValue(String sql) {
            Map map = new HashMap();
            ResultSet rs = null;
            Connection conn = null;
            Statement stmt = null;
    
            try {
                conn = getConnection();
                stmt = conn.createStatement();
                rs = stmt.executeQuery(sql);
                ResultSetMetaData rsmd = rs.getMetaData();
                int num = rsmd.getColumnCount();
                if (rs.next()) {
                    for (int i = 1; i <= num; i++) {
                        String key = rsmd.getColumnName(i);
                        String value = rs.getString(i);
                        if (value == null)
                            value = "";
                        map.put(key, value);
                    }
                }
            } catch (Exception e) {
                logger.info(sql);
                logger.info(e.toString());
            } finally {
                closeAll(conn, rs, stmt);
            }
            return map;
        }
    
        public int excuteBatch(List<String> sqlList) {
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = getConnection();
                conn.setAutoCommit(false);
                stmt = conn.createStatement();
    
                for (String sql : sqlList) {
                    stmt.addBatch(sql);
                }
                stmt.executeBatch();
                conn.commit();
                conn.setAutoCommit(true);
                return 1;
    
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    if (stmt != null) {
                        stmt.close();
                        stmt = null;
                    }
                    if (conn != null) {
                        conn.close();
                        conn = null;
                    }
                } catch (SQLException ee) {
                    logger.info(ee.toString());
                }
            } finally {
                try {
                    if (stmt != null) {
                        stmt.close();
                        stmt = null;
                    }
                    if (conn != null) {
                        conn.close();
                        conn = null;
                    }
                } catch (SQLException ee) {
                    logger.info(ee.toString());
                }
            }
            return 0;
        }
    
        public void beginBatch() {
    
            try {
                conn = getConnection();
                conn.setAutoCommit(false);
                stmt = conn.createStatement();
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    if (stmt != null) {
                        stmt.close();
                        stmt = null;
                    }
                    if (conn != null) {
                        conn.close();
                        conn = null;
                    }
                } catch (SQLException ee) {
                    // TODO Auto-generated catch block
                    logger.info(e.toString());
                }
            }
        }
    
        public void addBatch(String sql) {
            try {
                stmt.addBatch(sql);
            } catch (SQLException e) {
                e.printStackTrace();
                try {
                    if (stmt != null) {
                        stmt.close();
                        stmt = null;
                    }
                    if (conn != null) {
                        conn.close();
                        conn = null;
                    }
                } catch (SQLException ee) {
                    ee.printStackTrace();
                }
            }
        }
    
        public int doBatch() {
            try {
                stmt.executeBatch();
                conn.commit();
                return 1;
            } catch (SQLException e) {
                e.printStackTrace();
                try {
                    conn.rollback();
                    if (stmt != null) {
                        stmt.close();
                        stmt = null;
                    }
                    if (conn != null) {
                        conn.close();
                        conn = null;
                    }
                } catch (SQLException ee) {
                    logger.info(ee.toString());
                }
            }
            return 0;
        }
    
        public void endBatch() {
            try {
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

     在servlet中 private Dbcp db = Dbcp.getInstance(); 之后 就可以使用db里面的方法。

    2.servlet中实现ajax交互

    前端页面

    <form id="adminForm">
                <div class="inputArea">
                    <label>旧密码:</label>
                    <div class="inputLine"><input value="" placeholder="旧密码" type="password" name="password" placeholder="请输入旧密码" id="password"></div>
                </div>
                <div class="inputArea">
                    <label>新密码:</label>
                    <div class="inputLine"><input value="" placeholder="新密码" type="password" name="newPwd" placeholder="请输入新密码" id="newPwd"></div>
                </div>
                <div class="inputArea">
                    <label>再次输入新密码:</label>
                    <div class="inputLine"><input value="" placeholder="再次输入新密码" type="password" name="newPwd2" placeholder="请再次输入新密码" id="newPwd2"></div>
                </div>
            </form>

    前端jQuery

    var state=0;
    var pwd = $("#password").val();
    if
    (pwd != null && $.trim(pwd) !=""){ $.ajax({ type:"POST", async:false, url:"${ctx }/admin/audit.json", data:{password:pwd}, success:function(result){ result = eval("("+result+")"); if(result.status == "true" || result.status == true){ state=1; }else{ state=0; if(result.flag == '请先登录再操作'){ alert("请先登录再操作"); window.location.href="${ctx}/admin/login.html"; }else{ alert(result.flag); } } } }); }else{ alert("请输入旧密码"); return false; }

    后台java代码

    public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String password = request.getParameter("password");
            
            response.setContentType("text/html;charset=UTF-8");  
            response.setHeader("Cache-Control","no-cache"); 
            JSONObject json = new JSONObject(); 
            json.put("status", false);
            String str = (String)request.getSession().getAttribute("SESSION_ADMIN");
            if(str != null){
                String sqlById = "select * from t_admin where id="+str;
                Map<String, String> map = db.getValue(sqlById);
                if(map != null && StringUtils.isNotBlank(map.get("username"))){
                    if(StringUtils.isNotBlank(map.get("password"))){
                        if(map.get("password").equals(new MD5Util().MD5(password))){
                            json.put("status", true);
                            json.put("flag", "旧密码验证成功");
                            response.getWriter().write(json.toString());
                            return;
                        }else{
                            json.put("flag", "旧密码验证失败");
                            response.getWriter().write(json.toString());
                            return;
                        }
                    }
                }else{
                    json.put("flag", "请先登录再操作");
                    response.getWriter().write(json.toString());
                    return;
                }
            }else{
                json.put("flag", "请先登录再操作");
                response.getWriter().write(json.toString());
                return;
            }
        }

    3.request.getRequestDispatcher response.sendRedirect区别,以及文件路径和跳转路径区别(原文链接:http://blog.csdn.net/honglei_zh/article/details/7204946

    response.sendRedirect(url) -- 重定向到指定URL
    request.getRequestDispatcher(url).forward(request,response) -- 请求转发到指定URL

    二者区别:

    response.sendRedirect(url)跳转到指定的URL地址,产生一个新的request,所以要传递参数只有在url后加参数,如:
    url?id=1.
    request.getRequestDispatcher(url).forward(request,response) 是直接将请求转发到指定URL,所以该请求能够直接获得上一个请求的数据,也就是说采用请求转发,request对象始终存在,不会重新创建。而 sendRedirect()会新建request对象,所以上一个request中的数据会丢失。

    更具体来说就是这样的:

    redirect 会首先发一个response给浏览器, 然后浏览器收到这个response后再发一个requeset给服务器, 然后服务器发新的response给浏览器. 这时页面收到的request是一个新从浏览器发来的.

    forward 发生在服务器内部, 在浏览器完全不知情的情况下发给了浏览器另外一个页面的response. 这时页面收到的request不是从浏览器直接发来了,可能己经用request.setAttribute在request里放了数据.在转到的页面可 直接用request.getAttribute获得数据。

    最基本的用法就如上了,其他的一些应注意的地方如下:

    跳转方式

    http://localhost:8080/Test 应用

    运用forward方法只能重定向到同一个Web应用程序中的一个资源。而sendRedirect方法可以让你重定向到任何URL。

    表单form的action="/uu";sendRedirect("/uu");表示相对于服务器根路径。如http://localhost:8080/Test 应用(则提交至http://localhost:8080/uu );

    Forward代码中的"/uu"则代表相对与WEB应用的路径。如http://localhost:8080/Test 应用(则提交至http://localhost:8080/Test/uu );

     

     

    (运用RequestDispatcher接口的Forward)方法

     

    forward()无法重定向至有frame的jsp文件,可以重定向至有frame的html文件,

     

    同时forward()无法在后面带参数传递,比如servlet?name=frank,这样不行,可以程序内通过response.setAttribute("name",name)来传至下一个页面.

     

     

    "/"代表相对与web应用路径

     

    RequestDispatcher rd = request.getRequestDispatcher("/ooo");

     

    rd.forward(request, response);提交至http://localhost:8080/Test/ooo

     

    RequestDispatcher rd = getServletContext().getRequestDispatcher("/ooo");

     

    rd.forward(request, response);提交至http://localhost:8080/Test/ooo

     

    RequestDispatcher rd =getServletContext().getNamedDispatcher("TestServlet");(TestServlet为一个<servlet-name>)

     

    rd.forward(request, response);提交至名为TestServlet的servlet

     

    如果在<jsp:forward>之前有很多输出,前面的输出已使缓冲区满,将自动输出到客户端,那么该语句将不起作用,这一点应该特别注意。

     

    另外要注意:它不能改变浏览器地址,刷新的话会导致重复提交

     

    http://localhost:8080/Test/gw/page.jsp 中转发

     

    <jsp:forward page="OtherPage.jsp"/>在JSP页面被解析后转换成pageContext.forward("OtherPage.jsp");

     

    "/OtherPage.jsp"提交到http://localhost:8080/Test/OtherPage.jsp

     

    "OtherPage.jsp"提交到http://localhost:8080/Test/gw/OtherPage.jsp

     

    (运用HttpServletResponse接口的sendRedirect)方法302

     

    是在用户的浏览器端工作,sendRedirect()可以带参数传递,比如servlet?name=frank传至下个页面,

     

    同时它可以重定向至不同的主机上,sendRedirect()可以重定向有frame.的jsp文件.

     

    假设转发代码包含于注册的servlet-url为/ggg/tt;jsp为/ggg/tt.jsp:

     

    绝对路径:response.sendRedirect("http://www.brainysoftware.com

     

    根路径:response.sendRedirect("/ooo")发送至http://localhost:8080/ooo

     

    相对路径:response.sendRedirect("ooo")发送至http://localhost:8080/Test/ggg/ooo ,

     

    sendRedirect等同于此方式

     

    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

     

    String newLocn = "/newpath/jsa.jsp";

     

    response.setHeader("Location",newLocn);

     

    路径资料来源(http://blog.csdn.net/m1872216/article/details/7913658

     

    服务器端的相对路径 、绝对路径

    相对*.do,绝对/*.do;

    DD(web.xml)文件中的url-pattern只能绝对路径,即/*.do,根地址为应用目录。

    • <form action=”" >中的路径一般写相对,即为DD文件中定义的servlet-mapping的url-pattern。例如DD中<url- pattern>/proName</url-pattern>,action=”proName”。若action要写绝对地址,则 必须从服务器根写起,因为container是从server开始分析的。例如action=”/webapp/proName”。

       

    • HttpServletResponse.sendRedirect(String)

      参数可以指定为相对路径response.sendRedirect(“/foo/stuff.do”)。容器相对于Web应用本身加参数建立完整的URL—http://localhost/foo/stuff.do。

      其它Web应用:相对路径或绝对路径。

      相对路径情况下生成的完整URL与sendRedirect方法相同。

      绝对路径与重定向不同,容器将相对于Web应用的根目录加参数生成完整的URL,即:request.getRequestDispatcher(“/foo/stuff.do”)生成的URL是http://localhost/myApp/foo/stuff.do。

       二:

    • /表示根路径,但是jsp的根路径和servlet的根路径不一样

    •  

      jsp的根路径:http:/ /localhost:8080 而servlet的根路径 http:localhost:8080/weapp

     

     

     

  • 相关阅读:
    LeetCode Algorithm
    实现QObject与JavaScript通讯(基于QWebEngine + QWebChannel)
    Linux工具参考篇(网摘)
    GO 语言简介(网摘)
    Qt窗体引用window自带阴影边框效果
    无插件VIM编程技巧(网摘)
    ASP.NET 5基础之中间件
    ASP.NET Core 1.0基础之应用启动
    理解ASP.NET 5 Web Apps
    DNX 概览
  • 原文地址:https://www.cnblogs.com/cuiyf/p/4185234.html
Copyright © 2011-2022 走看看