任何人都知道如何解決以下錯誤投擲例外的doGet()的Java Servlet錯誤調用存儲過程
unreported exception javax.naming.NamingException; must be caught or declared to be thrown Context context = new InitialContext();
Auth.java:46: unreported exception java.sql.SQLException; must be caught or declared to be thrown conn = ds.getConnection();
,我從這個Java Servlet的得到什麼?
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.sql.SQLException;
import oracle.jdbc.OracleTypes;
public class ABC extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Connection conn;
CallableStatement cs;
String xy = req.getParameter("xy");
String zz = req.getParameter("zz");
// call stored procedure
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("jdbc/mypool");
conn = ds.getConnection();
cs = conn.prepareCall("{call mysproc (?,?)}");
cs.setString(1, xy);
cs.setString(2, zz);
cs.execute();
if (conn != null) {
try { conn.close(); } catch (Exception ex) {}
conn = null;
}
// Set the content type (MIME Type) of the response.
res.setContentType("text/html");
// Write the HTML to the response
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>my title</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>my header</h2>");
out.println("my body text<br/>");
out.println("</body>);
out.println("</html>");
out.flush();
out.close();
}
public void destroy() {
}
}
如果我試圖取代
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
與
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws Exception {
或
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException, SQLException, NamingException {
它們都產生錯誤,說我不能覆蓋的doGet,作爲覆蓋的方法不拋出異常,或者SQLException或NamingException。
感謝mprabhat在答案中如此完整。這非常有幫助! – ggkmath
你是最受歡迎的 – mprabhat