我有一个在我的网站上注册的表单。提交表单时,会调用一个Java Servlet。在Servlet中,我检查数据库是否已经使用了用户名或电子邮件。我希望Servlet在注册完成后作出响应,并且我希望我的客户端能够收到此响应并采取相应措施。一个简单的结果可能是注册表格上方显示“注册成功”或“电子邮件/用户名已在使用中”的文字。 如何让我的客户端收到来自Servlet的响应?注册表单提交和Java servlets
我的形式
<form id="registerForm" autocomplete="on">
<h1>Registrera</h1>
<p>
<label for="usernamesignup" class="uname" data-icon="u">Användarnamn</label>
<input id="usernamesignup" name="usernamesignup" required="required" type="text"
placeholder="användarnamn" />
</p>
<p>
<label for="emailsignup" class="youmail" data-icon="e">E-mail</label>
<input id="emailsignup" name="emailsignup" required="required" type="email"
placeholder="[email protected]" />
</p>
<p>
<label for="passwordsignup" class="youpasswd" data-icon="p">Lösenord</label>
<input id="passwordsignup" name="passwordsignup" required="required" type="password"
placeholder="lösenord" />
</p>
<p>
<label for="passwordsignup_confirm" class="youpasswd" data-icon="p">Upprepa lösenord</label>
<input id="passwordsignup_confirm" name="passwordsignup_confirm" required="required" type="password"
placeholder="lösenord" />
</p>
<p class="signin button">
<input type="submit" value="Registrera"/>
</p>
<p class="change_link">
Redan medlem? <a href="#tologin" class="to_register">Logga in</a>
</p>
</form>
我的servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("usernamesignup");
String email = request.getParameter("emailsignup");
String password = request.getParameter("passwordsignup");
try {
MysqlDataSource dataSource = new MysqlDataSource();
...
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE username = '" + username + "' OR email = '" + email + "'");
if (!rs.next()) {
stmt.executeUpdate("INSERT INTO Users VALUES('" + username + "', '" + password + "', '" + email + "')");
//Notify the client that the registration was successful!
} else {
//Notify the client that the registration failed!
}
...
}
}
我的解决方案
我去哪里,我从我的Servlet发送重定向和附加状态的解决方案参数。核心JSTL然后检索此参数并相应地显示一条消息。我在我的servlet以下几点:
ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE username = '" + username + "' OR email = '" + email + "'");
if (!rs.next()) {
stmt.executeUpdate("INSERT INTO Users VALUES('" + username + "', '" + password + "', '" + email + "')");
//Registration was successful!
response.sendRedirect ("pages/index.jsp?status=1");
} else {
//Registration failed
response.sendRedirect ("pages/index.jsp?status=2#toregister");
}
,并在我的JSP我做的:
<div id="registerMessage">
<c:set var="status" value="${param.status}" />
<c:if test="${status == '1'}">
<p class="success">Du är nu registrerad och kan logga in!</p>
</c:if>
<c:if test="${status == '2'}">
<p class="fail">Användarnamnet eller email adressen finns redan!</p>
</c:if>
</div>
在网上搜索我发现,像你这样写jsp是被认为是不好的做法。使用核心JSTL要好得多。不过,我会将你的答案标记为正确,因为它让我走上了正确的轨道。谢谢! –
感谢您的评论。 –