NetBeans Servlet MySQL

时间:2013-10-04 03:16:31

标签: java mysql jsp servlets netbeans

这已经解决了

问题在于参数名称。

我正在尝试创建一个基本的登录servlet来检查员工的登录详细信息。

但是我的servlet似乎没有与数据库交互,总是将我返回到“tryagain.jsp”。 我究竟做错了什么? 我正在使用glassfish和netbeans。 我的库文件中也有j / connector驱动程序。

这已经解决了

问题在于参数名称。

这是代码。

package loginServlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

/**
 *
 * @author asus
 */
public class Login1 extends HttpServlet {


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

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

        Connection conn;
        PreparedStatement ps;
        ResultSet rs;
        String DRIVER = "com.mysql.jdbc.Driver";
        String DATABASE_URL = "jdbc:mysql://localhost:3306/northwind";
       String uname=request.getParameter("username");
String passwd=request.getParameter("userPass");
        try {
            // load the driver class
            Class.forName(DRIVER);

            // establish connection to database                              
            conn =
                    DriverManager.getConnection(DATABASE_URL, "jonh86", "ADMIN");
            System.out.println("Connected....");
            ps = conn.prepareStatement("select * from userdata where user_name = ? and password = ?");
            ps.setString(1, uname);
            ps.setString(2, passwd);
            rs = ps.executeQuery();
            if (rs.next()) {

            RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet");
            rd.forward(request, response);

//out.println(rs.getString(2));
            } else {
                RequestDispatcher rd = request.getRequestDispatcher("tryagain.jsp");
            rd.include(request, response);
            }
        } 


        catch (Exception e) {
            System.out.println(e);
        }

    }

}

1 个答案:

答案 0 :(得分:0)

您可以通过一些正确的错误检查找到原因。有很多原因导致它失败。

// establish connection to database                              
            conn = DriverManager.getConnection(DATABASE_URL, "jonh86", "ADMIN");
            if(conn == null) System.out.println("Could not Connect");
            System.out.println("Connected...."); //--this code is misleading
            ps = conn.prepareStatement("select * from userdata where user_name = ? and password = ?");
            ps.setString(1, uname);
            ps.setString(2, passwd);
            rs = ps.executeQuery();

此外,您应该捕获SQLExceptions并打印它们:

catch (SQLException e) {
    System.out.println("Exception = " + e);
}