我在程序中使用了DBUtil组件
- Java code
import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;import java.text.SimpleDateFormat;import java.util.Date;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.sql.DataSource;import org.apache.commons.dbutils.*;public class AddMessage extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String sql = "insert into guestbook (id,name,email,phone,title,content,time) values (gb_seq.nextval,?,?,?,?,?,?)"; int result = 0; response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>Add Message</TITLE></HEAD>"); out.println(" <BODY>"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aaa"); String name = request.getParameter("name"); String title = request.getParameter("title"); if(StringUtil.validateNull(name)){ out.println("名字不能为空!请重新输入!"); out.println("<a href=\""+request.getContextPath()+"/AddMessage.htm>添加留言</a>"); } if(StringUtil.validateNull(title)){ out.println("主题不能为空!请重新输入!"); out.println("<a href=\""+request.getContextPath()+"/AddMessage.htm>添加留言</a>"); } String[] params = {StringUtil.filterHtml(name), StringUtil.filterHtml(request.getParameter("email")), StringUtil.filterHtml(request.getParameter("phone")), StringUtil.filterHtml(title), request.getParameter("content"), sdf.format(new Date())}; try { Context initCon = new InitialContext(); DataSource ds = (DataSource) initCon.lookup("java:comp/env/jdbc/oracledb"); QueryRunner qr = new QueryRunner(ds); //-------------------第86行--------------------------------- result = qr.update(sql, params); //------------------------ } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(result==0) { out.println("对不起,添加留言不成功,请您重新输入!<br>"); out.println("<a href=\""+request.getContextPath()+"/AddMessage.htm\">添加新的留言</a><br>"); } else { out.println("添加留言成功!<br>"); out.println("<a href=\""+request.getContextPath()+"/servlet/GetMessage\">查看留言</a><br>"); } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }}