如何在不提交表单的情况下使用 JSP 检查数据库中是否存在用户名?

huangapple go评论62阅读模式
英文:

How to check if username exists in database or not without submitting the form using jsp?

问题

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Controller</title>
</head>
<body>
<div class="container">
    <%
    String Username = request.getParameter("Username");
    session.setAttribute("theName", Username);
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abc?autoReconnect=true&useSSL=false", "root", "");
    try{
        Statement st = con.createStatement();
        ResultSet rs;
        rs = st.executeQuery("select * from signupform where Username='" + Username + "'");
        if(rs.next()){
            String usermessage = "Username already exists";
            request.getSession().setAttribute("usermessage", usermessage);
            response.sendRedirect("Signupform.jsp");
        } else {
            PreparedStatement ps = con.prepareStatement("insert into signupform(Username) values(?)");
            ps.setString(1, Username);
            if(Username.isEmpty()) {
                String message = "Please fill all the fields";
                request.getSession().setAttribute("message", message);
                response.sendRedirect("Signupform.jsp");
            } else {
                ps.executeUpdate();
                response.sendRedirect("Welcome.jsp");
            }
        }
    } catch (Exception e) {
        out.println(e);
    }
    %>
</div>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register</title>
<link Rel=stylesheet type="text/css" href="main.css">
</head>
<body>
<div class ="container">      
    <div>
        <form action="controller1.jsp" method="POST">
            Username <input type="text" name="Username" value="">
            <br>
            <input type="submit" value="Submit"/>
            <input type="reset" value="Reset"/>
            <br>
            <p>${usermessage}</p>
            <c:remove var="usermessage" scope="session"/>
        </form>
    </div>
</div>
</body>
</html>
英文:

I am trying to check if username exists in database or not without submitting the form. But I am not getting success.
Below is my code.

controller1.jsp

&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
	pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;%@ page import=&quot;java.io.*,java.util.*,java.sql.*&quot;%&gt;
&lt;%@ page import=&quot;javax.servlet.http.*,javax.servlet.*&quot;%&gt;
&lt;%@ page import=&quot;java.util.regex.*&quot;%&gt;
&lt;%-- &lt;%@ page import=&quot;java.net.URLEncoder&quot; session=&quot;false&quot; %&gt; --%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
&lt;title&gt;Controller&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;div class=&quot;container&quot;&gt;
		&lt;%
    String Username = request.getParameter(&quot;Username&quot;);
		session.setAttribute( &quot;theName&quot;, Username );
    			Class.forName(&quot;com.mysql.jdbc.Driver&quot;);
    			Connection con = DriverManager.getConnection(&quot;jdbc:mysql://localhost:3306/abc?autoReconnect=true&amp;useSSL=false&quot;, &quot;root&quot;, &quot;&quot;);
    		    try{
    		    	Statement st = con.createStatement();
        		    ResultSet rs;
        		    rs = st.executeQuery(&quot;select * from signupform where Username=&#39;&quot; + Username + &quot;&#39;&quot;);
    		    if(rs.next()){
    		    	String usermessage = &quot;Username already exists&quot;;
    		    	request.getSession().setAttribute(&quot;usermessage&quot;, usermessage);
    		    	response.sendRedirect(&quot;Signupform.jsp&quot;);
    		    }
    		    else{
    			PreparedStatement ps = con. prepareStatement(&quot;insert into signupform(Username) values(?)&quot;);
    			ps.setString(1, Username);
    	if(Username.isEmpty())
		{
    		String message = &quot;Please fill all the fields&quot;;
			request.getSession().setAttribute(&quot;message&quot;, message);
			/* response.sendRedirect(&quot;Signupform.jsp?message=&quot;+ URLEncoder.encode(message, &quot;UTF-8&quot;)); */
			response.sendRedirect(&quot;Signupform.jsp&quot;);
		}
    	else{
    		ps.executeUpdate();
    		response.sendRedirect(&quot;Welcome.jsp&quot;);
    	}
    		    }
    		    }
    catch (Exception e) {
        out.println(e);
    }
%&gt;
	&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

The form used for providing input is shown in the code Signupform.jsp. It should immediately report in the same page whether the user exists or not when the user fill the respective field.

Signupform.jsp

&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
    pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;%@ taglib uri = &quot;http://java.sun.com/jsp/jstl/core&quot; prefix = &quot;c&quot; %&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
&lt;title&gt;Register&lt;/title&gt;
&lt;link Rel=stylesheet type=&quot;text/css&quot; href=&quot;main.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class =&quot;container&quot;&gt;      
&lt;div&gt;
&lt;form action=&quot;controller1.jsp&quot; method = &quot;POST&quot;&gt;
Username &lt;input type = &quot;text&quot; name = &quot;Username&quot; value=&quot;&quot;&gt;
&lt;br&gt;
&lt;input type=&quot;submit&quot; value=&quot;Submit&quot;/&gt;
&lt;input type=&quot;reset&quot; value=&quot;Reset&quot;/&gt;
&lt;br&gt;
&lt;p&gt;${usermessage}&lt;/p&gt;
&lt;c:remove var=&quot;usermessage&quot; scope=&quot;session&quot;/&gt;

&lt;/form&gt;
&lt;/div&gt;
   &lt;/div&gt;
   &lt;/body&gt;
&lt;/html&gt;

答案1

得分: 1

首先,这是一个巨大的安全漏洞。不能像这样进行数据库查询;请使用PreparedStatement。或者,填写用户名:

joe'; DROP TABLE signupform CASCADE; --

然后你的数据库将会消失。

你似乎知道如何使用preparedstatements(你在插入操作中使用了它)。你必须在所有地方都使用它,几乎所有的SQL都必须是一个单独的字符串常量。如果你曾经输入过类似 "SELECT ...." + ... 的内容,停止这样做。

你想要的事情不容易实现。这不是网页的工作方式。客户端是客户端,服务器是服务器,除非你明确地让它们联系在一起,它们不会互相交流。

客户端必须使用JavaScript(在客户端上运行的代码)在输入时向服务器发出请求,触发用户名字段的更改,这本身就很棘手(有很多种方法可以更改浏览器中的文本字段。例如,你可以右键点击并选择粘贴,因此注册键盘处理程序是无效的)。

相对较简单的解决方案:使用setInterval大约每200毫秒检查一次。如果自上次检查以来字段没有被修改,则不执行任何操作;如果正在进行ajax调用,则不进行检查。否则,向服务器发送一个ajax调用来询问,并操作DOM以反映这一点。

你将不得不学习JavaScript,这并不是你一小时内能够完成的事情。这实际上归结为:“我如何编写web应用程序”。这个问题有答案,但是Stack Overflow并不适合这种情况。这更适合于书籍和非常长的教程。

英文:

For starters, this is a gigantic security hole. You can't do DB queries like this; use PreparedStatement. Alternatively, fill in for username:

joe&#39;; DROP TABLE signupform CASCADE; --

and your database will disappear.

You seem to know how preparedstatements work (you're using it for the insert). You have to use it everywhere, all your SQL pretty much has to be a single string constant. If you ever type &quot;SELECT ....&quot; +... stop. Don't do that.

What you want can't easily be done. That's not how the web works. The client is the client, the server is the server, they aren't in contact with each other unless you explicitly make it so.

The client would have to use javascript (code that runs on the client) to ask the server as-you-type, triggering off of the username field changing, which is itself tricky (there are a heck of a lot of ways to change a text field in a browser. For example, you can right click and select paste, so registering a keyboard handler is no good).

Easy-ish solution: Use setInterval to check every ±200 milliseconds or so. Don't do anything if the field hasn't been modified since the last time you checked, and don't check if an ajax call is in progress. Otherwise, send an ajax call to the server to ask, and manipulate the DOM to reflect this.

You're going to have to learn javascript, which.. is not exactly a thing you'll get done in an hour. This really boils down to: "How do I write webapps". That question has answers, but SO is not a good place for that. That's more a matter for books and very long tutorials.

huangapple
  • 本文由 发表于 2020年8月21日 00:27:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63509369.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定