简体   繁体   English

从servlet连接到mysql数据库

[英]Connect to mysql database from servlet

I am trying to connect to my database in order to check a username and password. 我正在尝试连接到数据库以检查用户名和密码。 I am following a tutorial but my connection is not working. 我正在学习教程,但我的连接无法正常工作。 My question are in these lines: 我的问题在以下几行:

String url = "jdbc:mysql://localhost:3306/"; 
String dbName = "LoginExample";
String driver = "com.mysql.jdbc.Driver";  
String userName = "root";  
String password = "password"; 

What is the meaning of all those values? 所有这些值的含义是什么? Are those standard? 这些标准吗? If not how can I find which ones correspond to my database. 如果没有,我该如何找到与我的数据库相对应的数据库。 Also I wasn't asked for a username and password when I created my database. 同样,在创建数据库时,也没有要求我输入用户名和密码。

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    public static boolean validate(String name, String pass) {
        boolean status = false;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/"; 
        String dbName = "LoginExample";
        String driver = "com.mysql.jdbc.Driver";  
        String userName = "root";  
        String password = ""; 

        try {  
            Class.forName(driver).newInstance();  
            conn = DriverManager  
                    .getConnection(url + dbName, userName, password);  

            pst = conn  
                    .prepareStatement("select * from Users where username=? and password=?");  
            pst.setString(1, name);  
            pst.setString(2, pass);  

            rs = pst.executeQuery();  
            status = rs.next();  

        } catch (Exception e) {  
            System.out.println(e);  
        } finally {  
            if (conn != null) {  
                try {  
                    conn.close();  
                } catch (SQLException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (pst != null) {  
                try {  
                    pst.close();  
                } catch (SQLException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (rs != null) {  
                try {  
                    rs.close();  
                } catch (SQLException e) {  
                    e.printStackTrace();  
                }  
            }  
        }
        return status;
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String un = request.getParameter("username");
        String pw = request.getParameter("password");

        response.setContentType("text/html");    
        PrintWriter out = response.getWriter();  

        HttpSession session = request.getSession(false);
        if (session != null) {
            session.setAttribute("name", un);
        }

        if (validate(un,pw)) {
            RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");    
            rd.forward(request,response); 
        } else {
            out.print("<p style=\"color:red\">Sorry username or password error</p>"); 
        }
    }

}

Error log: 错误日志:

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: 

** BEGIN NESTED EXCEPTION ** 

java.net.ConnectException
MESSAGE: Connection refused: connect

STACKTRACE:

java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:271)
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
    at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at servlets.Login.validate(Login.java:55)
    at servlets.Login.doPost(Login.java:112)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)


** END NESTED EXCEPTION **

Url tells the program where and how to find the database. 网址告诉程序在哪里以及如何查找数据库。 In this case, you use JDBC to access a MySQL database running on your own computer ( localhost ). 在这种情况下,您将使用JDBC访问在您自己的计算机( localhost )上运行的MySQL数据库。

dbname is the name of the database. dbname是数据库的名称。 The MySQL server may host multiple databases, so you need to specify which one you want. MySQL服务器可能托管多个数据库,因此您需要指定所需的数据库。

Driver is the Java class that you will use to access the database. 驱动程序是将用于访问数据库的Java类。

Username and Password explain themselves. 用户名和密码说明自己。

Assuming the port in the url and the database name are correct, your problem is most likely the username/password combination. 假设url中的端口和数据库名称正确,则您的问题很可能是用户名/密码组合。 By default, the username is "root" and the password is empty. 默认情况下,用户名是“ root”,密码是空的。

Yes these all are standard you have to use it to connect to your database through java. 是的,所有这些都是标准的,您必须使用它通过java连接到数据库。

    //since you have to connect to database you have to connect through to database server with url(where localhost signifies your current system and 3306 is a port)
    String url = "jdbc:mysql://localhost:3306/"; 

    //In order to connect to specific database specify its name
    String dbName = "LoginExample";

    //Initialize a driver so you can open a communications channel with the database.
    String driver = "com.mysql.jdbc.Driver"; 

    //credentials required to connect 
    String userName = "root";  
    String password = "password"

Since you dint enter any username and password during installation then the default name and password were set.The default username is root and password is no password .You can also reset password . 由于您在安装过程中输入了任何用户名和密码,因此设置了默认名称和密码。默认用户名是root ,密码是no password。您还可以重设密码

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: com.mysql.jdbc.CommunicationsException:由于基础异常导致通信链接失败:

First You do not need to instantiate the driver, just call it's static initialization (eg, by calling Class.forName) so it gets registered in the DriverManager 首先,您不需要实例化驱动程序,只需调用它的静态初始化(例如,通过调用Class.forName),即可在DriverManager中注册它。

So remove .newInstance() from Class.forName(driver).newInstance() ; 因此,从Class.forName(driver).newInstance()删除.newInstance() Class.forName(driver).newInstance()

Also check if port 3306 is acquired by other process check this by 还要检查端口3306是否被其他进程获取

RUN resmon.exe and go to network tab to check if 3306 port is acquired by other process or not. 运行 resmon.exe并转到“网络”选项卡,以检查3306端口是否被其他进程获取。

资源监控器

You should not manually try to establish database connection from your servlet. 您不应该手动尝试从servlet建立数据库连接。 Instead you should define a DataSource and look it up from your servlet; 相反,您应该定义一个DataSource并从servlet中查找它。

Step by step guide for tomcat: Tomcat逐步指南:

  1. Put your mysql driver in tomcat's /lib folder 将您的mysql驱动程序放入tomcat的/lib文件夹中
  2. Define a datasource in Tomcat's context.xml 在Tomcat的context.xml定义数据源

     < Resource name="jdbc/DefaultDB" type="javax.sql.DataSource" auth="Container" description="Default datasource" maxActive="100" maxIdle="30" maxWait="10000" username="" password="" driverClassName="com.mysql.jdbc.Driver" url="com.mysql.jdbc.Driver"/> 
  3. Reference this data source in your web.xml 在您的web.xml引用此数据源

     < resource-ref> < res-ref-name>jdbc/DefaultDB</res-ref-name> < res-type>javax.sql.DataSource</res-type> < res-auth>Container</res-auth> < /resource-ref > 
  4. Look up the data source: 查找数据源:

    InitialContext ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/DefaultDB");

    As an alternative you can inject the data source: 或者,您可以注入数据源:

    @Resource(name="jdbc/DefaultDB") private javax.sql.DataSource ds;

  5. Get connection: 获取连接:

Connection connection = ds.getConnection();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM