简体   繁体   English

使用MySQL登录/注册Servlet

[英]Login / Registration Servlet with MySQL

I am having issues getting my registration servlet to add rows to my mySQL table. 我在获取注册servlet向mySQL表添加行时遇到问题。 That being said, the servlet CAN see if a user is already in my table, and will redirect accordingly (so I know my connection is there). 话虽如此,该servlet可以查看用户是否已在我的表中,并将进行相应的重定向(所以我知道我的连接在那里)。 I have also tested my query string, and it appears to be right. 我还测试了我的查询字符串,它似乎是正确的。 I am not sure what I am doing wrong, or how I can see exactly what messages my mySQL server is seeing / how it responds to the registration request. 我不确定自己在做什么错,或者不确定我的mySQL服务器究竟能看到什么消息/它如何响应注册请求。

Well, here is my code: 好吧,这是我的代码:

index.jsp

                    <div id="loginDiv">

                <form action="LoginHandler" method="post" id="1">
                Login Here! -->
                    Username: <input type="text" name="username" required="required"> </input>
                    Password: <input type="password" name="password" required="required"> </input>
                <input type="submit" value="Login"> </input> 
                </form>
                </div>

                <div id="registerDiv">
                <form action="RegistrationHandler" method="post" id="2">
                Register Here! -->
                    Username: <input type="text" name="username" required="required"> </input>
                    Password: <input type="password" name="password" required="required"> </input>
                <input type="submit" value="Register"> </input>
                </form>
                </div>

loginHandler.java : loginHandler.java

public class RegistrationHandler extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    //get username & pass from jsp login
        String userName = request.getParameter("username");
        String passWord = request.getParameter("password");
    //pass username & pass to mysql query
    Connection conn = null;
    String url = "jdbc:mysql://localhost:8888/";
    String dataBase = "usersdb";
    String driver = "com.mysql.jdbc.Driver";
    String dBUserName = "admin";
    String dBPassword = "xxxx";
    RequestDispatcher rd = null;

    try{

        Class.forName(driver).newInstance();
        conn = (Connection) DriverManager.getConnection(url+dataBase,dBUserName,dBPassword);
        String strQuery = "select * from playerinfo where usrname='" + userName + "'" + ";" ;
        Statement st = (Statement) conn.createStatement();
        ResultSet rs = st.executeQuery(strQuery);

        if(rs.next())
        //username already exists
        {
        request.setAttribute("userName", userName);
        RequestDispatcher requestDispatcher = request
            .getRequestDispatcher("/registrationError.jsp");
        requestDispatcher.forward(request,response);
        }

        else
        //create new user in database
        {
        String createUserQuery = "insert into playerinfo values ('" + userName + "','" + passWord + "'," + 100 + "," + 100 + "," + 100 + "," + "NULL" + "," + "NULL" + ") ;" ;
        Statement create = (Statement) conn.createStatement();
        rs = st.executeQuery(createUserQuery);

        RequestDispatcher requestDispatcher = request
            .getRequestDispatcher("/userHome.jsp");
        requestDispatcher.forward(request,response);
        }
    //close connection
    rs.close();
    st.close();
    }
    catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e){
    }
}

}

The rs.next() conditional function will work correctly ie if there is a user with a username already in my db, it will redirect to the error page correctly. rs.next()条件函数将正常运行,即,如果我的数据库中已经有一个用户名已经存在的用户,它将正确地重定向到错误页面。

But, if they aren't in the table then it will not add them, or redirect to the proper page. 但是,如果它们不在表中,它将不会添加它们,也不会重定向到正确的页面。

So I think I am improperly telling mySQL to add a new user to my table. 因此,我认为我是在不正确地告诉mySQL将新用户添加到表中。 Is this correct? 这个对吗? If so, where did I go wrong? 如果是这样,我哪里出错了?

THANK YOU! 谢谢!

EDIT : 编辑

These are the changes I have made to my servlet, but still no luck in getting it to work :( 这些是我对servlet所做的更改,但是仍然无法使它正常工作:(

public class RegistrationHandler extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    //get username & pass from jsp login
        String userName = request.getParameter("username");
        String passWord = request.getParameter("password");
    //pass username & pass to mysql query
    Connection conn = null;
    Connection conn2 = null;
    String url = "jdbc:mysql://localhost:8888/";
    String dataBase = "usersdb";
    String driver = "com.mysql.jdbc.Driver";
    String dBUserName = "admin";
    String dBPassword = "xxxx";
    RequestDispatcher rd = null;

    try{

        Class.forName(driver).newInstance();
        conn = (Connection) DriverManager.getConnection(url+dataBase,dBUserName,dBPassword);
        String strQuery = "select * from playerinfo where usrname='" + userName + "'"  ;
        Statement st = (Statement) conn.createStatement();
        ResultSet rs = st.executeQuery(strQuery);

        if(rs.next())
        //username already exists
        {
        request.setAttribute("userName", userName);
        RequestDispatcher requestDispatcher = request
            .getRequestDispatcher("/registrationError.jsp");
        requestDispatcher.forward(request,response);
        }

        else
        //create new user in database
        {
        register(userName, passWord);

        RequestDispatcher requestDispatcher = request
            .getRequestDispatcher("/userHome.jsp");
        requestDispatcher.forward(request,response);
        }
    //close connection
    rs.close();
    st.close();
    }
    catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e){
    }



        }
private static void register(String username, String password){
    Connection conn = null;
    String url = "jdbc:mysql://localhost:8888/";
    String dataBase = "usersdb";
    String driver = "com.mysql.jdbc.Driver";
    String dBUserName = "admin";
    String dBPassword = "xxxx";

    try{

        Class.forName(driver).newInstance();
        conn = (Connection) DriverManager.getConnection(url+dataBase,dBUserName,dBPassword);
        String strQuery = "insert into playerinfo values ('" + username + "','" + password + "'," + 100 + "," + 100 + "," + 100 + "," + "NULL" + "," + "NULL" + ") " ;
        Statement st = (Statement) conn.createStatement();
        st.executeQuery(strQuery);

    }
    catch(ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e){

    }
  }
}

Any hints or clues as to why I cannot successfully query mysql to add this new user to the table? 关于为什么我无法成功查询mysql将此新用户添加到表的任何提示或线索?

In the else block, where you actually want to add the user to the database, you are still calling the first statement. 在else块中,您实际上要将用户添加到数据库中,您仍在调用第一条语句。 Not the one you newly created. 不是您新创建的。 This might be what's causing the problem. 这可能是导致问题的原因。

That being said, you might also want to look at the Hibernate framework. 话虽这么说,您可能还想看看Hibernate框架。 It will let you get rid of doing all this stuff yourself and instead you can just code Java instead of actual SQL. 它可以让您摆脱自己做所有这些事情的麻烦,而可以只编写Java而不是实际的SQL。 Makes life a lot easier I found. 我发现生活变得更加轻松。

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

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