在jsp页面上验证登录表单

时间:2016-04-13 19:19:17

标签: java html mysql jsp sql-injection

登录表单(index2.html)

<html>
<head>
    <title>Login Form</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body bgcolor="96D2C2">

    <form name="ask_1" method="get" action="index24.jsp">
    Username: <input type="text" name="id11"/> <BR>
    Password: <input type="password" name="id22" /> <BR>
    <input type="submit" value="Login"  /> <BR>
    <BR>
    </form>
  <a href="index12.html"> Create an Account </a>
</body>

我的JSP代码,以验证登录信息并打印到用户成功与否......(index24.jsp)`

<%@page contentType="text/html" pageEncoding="UTF-8"%>
 <%@page import="java.sql.*" %> 
 <% int j=0; %>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
   <% 
   Class.forName("com.mysql.jdbc.Driver"); 
   String myDatabase = "jdbc:mysql://localhost:3306/mydb1?user=root&password=1234"; 
   Connection myConnection = DriverManager.getConnection(myDatabase);
   Statement myStatement = myConnection.createStatement();  
   String id11=request.getParameter("id11");
   String id22=request.getParameter("id22");
   String sqlString = "SELECT FROM users WHERE username='"+id11+"' AND password='"+id22+"' ";
   ResultSet rs = myStatement.executeQuery(sqlString);
   if(rs.next()) {
       System.out.println("Success"); }
   else {
       System.out.println("Failed");
   }

   %>


    </body>

</html>

上面给出的代码给出了错误,“请求的资源不可用。”。欢迎对我的代码或编辑提出任何建议和改进。

2 个答案:

答案 0 :(得分:0)

Connection myConnection = DriverManager.getConnection(myDatabase); 是错误的,因为getConnection()将不会处理给定的URL作为参数String尝试这样做:

Connection myConnection = DriverManager.getConnection("jdbc:mysql://localhost/mydb1" , "root" , "1234");

您可以查看该方法的文档,并且不要删除此行

String myDatabase = "jdbc:mysql://localhost:3306/mydb1?user=root&password=1234"; 

答案 1 :(得分:0)

尝试使用

关闭“try {”块
} catch (Exception e) {
    e.printStackTrace(new java.io.PrintWriter(out));
}

获取有关错误的更多详细信息。这是开发jsps的一个简单技巧,应该在官方版本的网站中删除。

此外,它可能不在主题,但您的代码易受SQL注入。在这里查看更多 http://www.w3schools.com/sql/sql_injection.asp