每日记载内容总结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
时间: 2024-08-08 09:41:11

每日记载内容总结41的相关文章

每日记载内容总结34

1.数据库以及服务器方面 (1)查看电脑中 sql server 版本  1> select @@version2> go (2)1.数据库日期格式化 select id,nickName,addTime,date_format(addTime, '%H:%i:%s'),date_format(addTime, '%Y-%m-%d') from faqhelphead where status=1 and state=0 and nickName like '%飞回%' order by da

每日记载内容总结33

完整的客服服务功能需要注意的事项: 1.用户接入客服的提示 A.接入客服前,提示接入客服的时间段等条件,满足的话,则接入客服.不满足,跳转页面,让用户自主填写. B.接入客服中,提示正在接入客服 C.接入客服中,客服繁忙提示 D.接入客服不成功,提示,或者跳转页面 E.接入客服成功,客服对象的介绍或者提示 2.分配客服任务 A.先判断客服是否在线,然后分配任务 B.按照客服服务内容和用户问题内容对应分配 C.记录客服的正在服务任务和服务完成任务数,以及正在服务内容 3.客服服务 A.客服服务页面

每日记载内容总结32

1.java创建数组的3个方法: int vec[] = new int[]{1, 5, 3}; // 第一种方法 int vec[] = { 37 , 47 , 23 } ; // 第二种方法 int vec[] = new int [3]; 2.double保留2位小数(四舍五入) double avgTimeAll=23.5620d; BigDecimal bg = new BigDecimal(avgTimeAll); Double avgTime = bg.setScale(2, Bi

每日记载内容总结42

1. log日志,相关知识 log4j中输出信息的级别分为五个级别:DEBUG.INFO.WARN.ERROR和FATAL.这五个级别是有顺序的,DEBUG < INFO < WARN < ERROR < FATAL,明白这一点很重要.这里Log4j有一个规则:假设设置了级别为P,如果发生了一个级别Q比P高,则可以启动,否则屏蔽掉. catalina.out与log文件的区别:catalina.out里面存放的是tomcat启动关闭的输出和在控制台的输出.log文件保存的log日志

每日记载内容总结37

html页面内容: 1.获取下拉框的内容 根据input类别获取下拉框 var k = $("input[type='checkbox']:checked").length; 根据input name 获取下拉框 var k = $("input[name='checkboxname']:checked").length; 数据库内容: 1.批量替换数据库某个字段的值 --将aaaa替换为cccc update 表名 set 字段名=replace(字段名,'aaa

每日记载内容总结35

1.js实现关闭浏览器当前窗口 function closeWindow(){ var userAgent = navigator.userAgent; if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Presto") != -1) { window.location.replace("about:blank"); } else { window.opener = null

每日记载内容总结40

1.ajax传值map时,在页面解析 Map<Integer, List<Object[]>> objs = new HashMap<Integer, List<Object[]>>(); objs.put(1, page.getRows()); objs.put(2, pageOrders); return renderMyPageData(success, msg, objs, page); if(result.status == "true&

每日记载内容总结38

从一个项目中学到的做项目知识: 1.不管需求多么简单,多么熟练,都要和项目负责人对需求.对完了就知道有什么了,不对完,猜测有什么,说不定会多出什么. 2.项目需要文件没有齐全的话,需要考虑下次相同文件到来时,已最快的方法进行操作. 3.加需求,要考虑原需求是否可以按时完成,完不成,就不加,或者对负责人进行提醒. 4.要从整个项目出发,设计实体类和数据库内容,是做功能,还是做管理模块,等等,考虑全了再设计,总比推到再来强多了. 5.测试,要深入全面测试,不要只测同样功能的一部分,要测全部. 从一个

每日记载内容总结39

Apache POI Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能. HSSF - 提供读写Microsoft Excel XLS格式档案的功能. XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能. HWPF - 提供读写Microsoft Word DOC格式档案的功能. HSLF - 提供读写Microsoft Power