如何在另一个方法中使用一个方法中声明的变量

时间:2016-01-28 05:58:29

标签: java scope local-variables

我写了一个名为“Get_connection”的方法来连接SQL服务器和我的Servlet,我不能使用“out.println();”尽管我将http servlet Responce作为参数传递给了这个方法。

有人可以解释如何纠正..

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
   response.setContentType("text/html;charset=UTF-8");
   try (PrintWriter out = response.getWriter()) {

   }
 }

 public Connection Get_connection() {
   try {
     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
     String url = "jdbc:sqlserver://localhost:1433; databaseName = Colombo_Health; integratedSecurity=true;";
     con = DriverManager.getConnection(url, "", "");
     out.println("Connection Established");
   } catch (ClassNotFoundException e) {

     out.println("Class not Found       " + e.toString());
     e.toString();

   } catch (Exception e) {
     out.println("Driver not Found    " + e.toString());
     e.toString();
   }

   return con;

 }

1 个答案:

答案 0 :(得分:1)

您的Get_connection方法应低于签名。

public Connection Get_connection(PrintWriter out) { }

将此方法从processRequest方法的try块调用为Get_connection(out);

同样在processRequest方法中,您的尝试应该遵循catch块或最后。欢呼声。