【发布时间】:2013-04-09 01:14:54
【问题描述】:
我不确定我是否尝试正确“打印”我的结果。我想要做的是使用 JSP 接收变量,然后将其传递给 servlet,它将在其中查询数据库,然后显示结果。我测试了在不同的 java 文件中查询我的数据库,我没有遇到任何问题。任何建议将不胜感激!
JSP 文件:
<form method="post" action="HelloServlet"/>
Enter your name:<input name = "exName"/><br>
<input type = "submit" />
</form>
JAVA 文件(servlet):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//response.setContentType("text/html; charset=ISO-8859-1");
PrintWriter out = response.getWriter();
java.sql.Connection con = null;
java.sql.PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/masters";
String user = "christine";
String password = "password";
try{
String exName = request.getParameter("exName");
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name ='"+exName+"';");
rs = pst.executeQuery();
while (rs.next()){
String name = rs.getString("description_txt");
out.print(exName);
out.print(name);
}
}catch(SQLException ex){
}finally {
try {
if (rs != null){
rs.close();
}
if (pst != null){
pst.close();
}
if (con != null){
con.close();
}
}catch(SQLException ex){
}
}
}
【问题讨论】:
-
你完全压制了
SQLException被抛出。 为什么? 将throw new ServletException(ex)添加到 catch 中,这样您就可以得到一个带有堆栈跟踪的漂亮错误页面,并且全部都在 em 上。异常包含问题的全部答案。 -
(我还是个初学者)我想我不知道我正在抑制 SQLException。你介意指出我在做什么吗?我不太明白。谢谢。
-
您正在捕捉
SQLException,但没有对它做任何事情并继续代码流,就好像没有发生什么特别的事情一样。您至少应该记录/打印它,或者在这种情况下最好将其重新抛出为ServletException,符合 Servlet API 规范建议。 -
POST 表单值是属性,使用 getAttribute 代替 getParameter
-
谢谢你们提供的信息!