尝试从myeclipse中的servlet连接到mysql时访问被拒绝

时间:2012-10-10 09:29:54

标签: java mysql servlets

我正在尝试在我的servlet/mysql webapp中使用tomcat服务器运行一个简单的eclipse。 当我尝试从database连接到servlet时,出现以下错误:

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create 
PoolableConnectionFactory (Access denied for user ''@'localhost' (using password: YES))
下面的

是我执行的脚本:

servlet:

import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

public class EmployeeServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  @Resource(name = "jdbc/testDB")
    DataSource ds;

  public EmployeeServlet() {
    super();
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try {
      Connection con = ds.getConnection();

      Statement stmt = con.createStatement();
      String query = "select * from Employee";
      ResultSet rs = stmt.executeQuery(query);

      PrintWriter out = response.getWriter();
      response.setContentType("text/html");
      out.print("<center><h1>Employee Details</h1></center>");
      out.print("<html><body>");
      out.print("<table border=\"1\" cellspacing=10 cellpadding=5>");
      out.print("<tr><th>Employee ID</th>");
      out.print("<th>Employee Name</th>");
      out.print("<th>Salary</th>");
      out.print("<th>Department</th></tr>");

      while (rs.next()) {
        out.print("<tr>");
        out.print("<td>" + rs.getInt("emp_id") + "</td>");
        out.print("<td>" + rs.getString("emp_name") + "</td>");
        out.print("<td>" + rs.getDouble("salary") + "</td>");
        out.print("<td>" + rs.getString("dept_name") + "</td>");
        out.print("</tr>");
      }
      out.print("</table></body></html>");
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  }
}

context.xml文件的内容:

<?xml version="1.0" encoding="UTF-8"?>
<Context crossContext="true">
  <WatchedResource>WEB-INF/web.xml</WatchedResource>
  <Resource name="jdbc/testDB" auth="Container"
    type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000" 
    username="root" password="root"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost/mysql">
</Context>

3 个答案:

答案 0 :(得分:1)

尝试从任何其他工具/从命令提示符连接到mysql,并将您在代码中使用的所有信息连接到同一个。尝试在连接URL中包含端口。默认端口是3306

答案 1 :(得分:1)

如果从远程客户端访问数据库,请使用mysql的GRANT查询授予您访问数据库的权限。

答案 2 :(得分:0)

似乎网址中缺少端口号:

jdbc:mysql://localhost:<port>/mysql