IT公司一道笔试题
下面代码有三处潜在的问题(错误),请找到并修正.public class TestServlet extends HttpServlet {
private final static String drv = "oracle.jdbc.driver.OracleDriver";
private final static String url = "jdbc:oracle:thin@210.220.251.96:1521:ORA8i";
private final static String user = "scott";
private final static String password = "tiger";
private ServletContext context;
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public void init(ServletConfig config) throws ServletException {
super.init(config);
context = config.getServletContext();
try {
Class.forName(drv);
} catch (ClassNotFoundException e) {
throw new ServletException("unable to load jdbc driver");
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ,SQLException{
String id = req.getParameter("id");
conn = DriverManager.getConnection(url,user,password);
stmt = conn.createStatement();
rs = stmt.executeQuery("select ... where id='"+ id +"'");
while(rs.next()){
// ...
}
rs.close();
stmt.close();
conn.close();
}
我只找到一处问题,就是SQLexception不能加在overide的时候,另外两处有高人帮忙找下吗 --------------------编程问答-------------------- 自己顶下 --------------------编程问答-------------------- 我找到一处 jdbc:oracle:thin:@210.220.251.96:1521:ORA8i
另外 LZ说 ServletException不能加在overide的时候,不是这样 是子类复写不能抛出比父类更大的异常
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ,SQLException{
这个抛出了IOException ,SQLException 是错的 --------------------编程问答-------------------- (1)doGet()方法不能抛出SQLException
(2)不要使用stmt.executeQuery("select ... where id='"+ id +"'"),存在SQL注入漏洞,要使用preparedstatement
(3)
Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
这三个成员变量存在线程安全问题 --------------------编程问答--------------------
doGet()方法可以跑出SQLException异常啊 --------------------编程问答--------------------
--------------------编程问答--------------------
public abstract class HttpServlet extends GenericServlet implements Serializable{
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
}
}
//你难道不知道,子类不能比父类抛出更多的异常吗?
郁闷了 郁闷了 我看错了 以为他是说ServletException 我在3楼都说了 --------------------编程问答-------------------- --------------------编程问答--------------------
如果3楼的是你,那我是谁啊?
--------------------编程问答--------------------
又错了。。哎 今天状态不好 2楼啊 不会看ID啊? --------------------编程问答-------------------- 第一个:
stmt.executeQuery("select ... where id='"+ id +"'");可能有sql注入的问题
第二个:
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null
有线程安全的问题
第三个:sql异常应该在doget()里面try。。chatch()
补充:Java , Java SE