0

I wrote a login web and it can't work well. It may be some problem of MySQL connecting.

Here is the code. It's simple. There are ServletLogin.java and a index.jsp.

ServletLogin.java

package Login;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.sql.*;

public class ServletLogin extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String name;
    private String pass;

    public ServletLogin() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String printout = "";
        this.name = request.getParameter("username");
        this.pass = request.getParameter("password");       
        if (name == "" || name == null || name.length() > 20) {
            try {
                printout = "20字以内ユーザネームを再入力ください";
                request.setAttribute("message", printout);
                response.sendRedirect("index.jsp");
                return;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        if (pass == "" || pass == null || pass.length() > 20) {
            try {
                printout = "20字以内のパスワードを再入力ください";
                request.setAttribute("message", printout);
                response.sendRedirect("index.jsp");
                return;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        // database driver 
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("Class not Found Exception");
        }
        // create url   
        String url = "jdbc:mysql://localhost:3306/databasedemo";

        try {
            Connection conn = DriverManager.getConnection(url,"root","");
            Statement stmt = conn.createStatement();
            String sql = "select * from userinfo where username='"+name+"' and password= '"+pass+"'";
            ResultSet rs = stmt.executeQuery(sql);

            if (rs.next()) {
                if (this.name.equals(rs.getString(1))||this.pass.equals(rs.getString(2))) {
                    response.sendRedirect("success.jsp");
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }   
    }
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ログイン</title>
<script type="text/javascript">

function changeImg() 
{
    document.getElementById("validateCodeImg").src="${pageContext.request.contextPath}/CheckCodeImage?" + Math.random();
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/ServletLogin">
    <table border="0" align="center">
        <tr height="30"></tr>
        <tr align="center">
            <td colspan="2"><font size="20">JAVA WEB</font></td>
        </tr>
        <tr height="30"></tr>
        <tr height="50">
            <td>ユーザネーム</td>
            <td><input type="text" name="username" placeholder="ユーザネームを入力してください"></td>
        </tr>
        <tr height="50">
            <td>パスワード</td>
            <td><input type="password" name="password" placeholder="パスワードを入力してください"></td>
        </tr>

        <tr height="50">
            <td><img alt="認めない" src="${pageContext.request.contextPath}/CheckCodeImage" 
            id="validateCodeImg" onclick="changeImg()">
            </td>
            <td><input type="text" name="checkcode" placeholder="右側の文字を入力してください"></td>
        </tr>
        <tr height="50">
            <td colspan="2" align="center">
                <input type="submit" name="login" value="ログイン">
            </td>
        </tr>
    </table>
</form>

</body>
</html>

And here is my database called databasedemo.

+--------+----------+----------+
| userid | username | password |
+--------+----------+----------+
| 1 | Jack | 123456 |
| 2 | Mary | 654321 |
+--------+----------+----------+

I think I am stucked with command in ServletLogin.java. I was supposed to submit the form and it would turn to ServletLogin.java and do the command.

If the username and the password are null, recording to the code in Servlet.java, it will go back to index.jsp. And it went very well.

But if the username and the password are the same as it in my database, it should have to go to the page success.jsp. But when I run it, it shows nothing. Seems it has not been submitted and do the command in Servletlogin.java. and the Url shows http://localhost:8080/LoginDemo/ServletLogin?username=Jack&password=123456&checkcode=Axww&login=%E3%83%AD%E3%82%B0%E3%82%A4%E3%83%B3

I'm so confused of it. I think I have problem about connecting to MySQL. But I don't know how to fix it. Please help me about it...


UPDATE

I have solved my problem!

When I run the code, the Exception shows Class not Found Exception java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/databasedemo. This is a exception of jdbc Driver.
When this exception shows, there's four reason:

  1. Wrong URL. Please check the right code: Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/XX","root","XXXX"
  2. Wrong Driver declaration, the right one is :com.mysql.jdbc.Driver
  3. mysql-connector-java-5.1.40.jar must be the same version as your MySQL.
  4. mysql-connector-java-5.1.40.jar has been put to the wrong position. The right position is to copy it in WEB-INF file.

As for me, I put .jar in the wrong position. And When I copy it in the file WEB-INF, my code run well. I hope this will help someone. And my code above is a simple webpage of login. I will continue to complete this java project.

And Thanks for everyone answered my question. @Ravi Kumar pointed out one of my mistakes, and I corrected it. It's a big mistake of me using MySQL.

Xinyi Zhang
  • 11
  • 1
  • 4
  • Did you check console any stacktrace for exception? – Ravi Kumar Nov 10 '16 at 10:49
  • @RaviKumar Yes, and it shows `Class not Found Exception java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/databasedemo`, so i think there must be wrong with the connection between servlet and MySQL, but i don't know how to fix it... – Xinyi Zhang Nov 10 '16 at 10:52
  • 1
    Do you have mysql-connector jar in your classpath – Ravi Kumar Nov 10 '16 at 10:55
  • @RaviKumar yes I use mysql connector java 5.1.40. I just found regular .java class can connect to mysql, but if I use Servlet class, it shows exception. I think I may have problem in the connection between Servlet and Mysql... Right now I am working on it – Xinyi Zhang Nov 10 '16 at 11:02
  • There is no reason servlet can not connect to mysql for sure, as it is also a java file only. Following are the reason it gives exception either the database is not up or the database doesn't exist. – Ravi Kumar Nov 10 '16 at 11:06

2 Answers2

0

There can be two possibilities as below:
1) You are seeing nothing in UI because there is nothing(no text content) in your success.jsp file.

You need to add some text as below in success.jsp page.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error page</title>
</head>
<body>
   <p>Success!!!</p>
</body>

I guess you are not getting any exception in both UI and Server console.

2) You need to traverse through the resultSetObject in order to fetch correct username and password values.

So, replace your below code:

if (rs.next()) {
            if (this.name.equals(rs.getString(1))||this.pass.equals(rs.getString(2))) {
                response.sendRedirect("success.jsp");
            }
        }

With ,

while(rs.next()){
   if(this.name.equals(rs.getString(1))||this.pass.equals(rs.getString(2))) {
                response.sendRedirect("success.jsp");
            }
   }
Rohit Gaikwad
  • 3,677
  • 3
  • 17
  • 40
  • This doesn't make any difference. If he know the query is going to yield only one row why do he need to run a loop. If(rs.next()) is perfectly fine with the query semantic. – Ravi Kumar Nov 10 '16 at 11:00
  • Yes, the query is going to yield only one row that is first row. May be he is using details of second row, so as there is an mismatch with data the response is not redirected. – Rohit Gaikwad Nov 10 '16 at 15:00
  • Thank you guys, I think I use if() is right. I have updated my post, and I think I have solved the problem. – Xinyi Zhang Nov 11 '16 at 13:11
0

My best guess is your query

select * from userinfo where username='"+name+"' and password= '"+pass+"'"

This basically select 1 | Jack | 123456

Now rs.getString(1)=1 ie id and rs.getString(2) is Jack ie. username

Instead use

rs.getString("username");
rs.getString("password");

You may also like to change your query to

select username,password from userinfo where username='"+name+"' and password= '"+pass+"'"

in order to make it work with existing code

Ravi Kumar
  • 993
  • 1
  • 12
  • 37
  • Thank you very much. This is a big mistake of me using database. And I have recorrected it. I figured out how my code didn't run well. I have updated my post. I put mysql-connector-java-5.1.40.jar in the wrong file. It's so stupid of me....Thank you again~ – Xinyi Zhang Nov 11 '16 at 13:13