Reputation: 2517
I have a signup form in which the user has to enter the email address and after some quick asynchronous processing at the backend I have to tell the user that whether the email address is already registered or not.
Below is a sample example of the JSP page that I have created,
<input type="email" id="inputEmail" placeholder="*Email" name="inputEmail" onchange="checkDuplicate();"/>
<div id="duplicateEmail"></div>
<script>
var request;
function createRequest(){
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
}
//Below 2 functions are to check whether the email entered by the user is already registered or not
function checkDuplicate(){
var email = document.getElementById("inputEmail").value;
if(email!=""){
createRequest();
var url = "../ajaxPages/check_email.jsp?email="+email;
try{
request.onreadystatechange=duplicateEmailMessage;
request.open("GET",url,true);
request.send();
}catch(e){
alert("Unable to connect to server");
}
}
}
function duplicateEmailMessage(){
if(request.readyState==4){
var x = document.getElementById("duplicateEmail");
var msg = request.responseText;
x.innerHTML = msg;
}
}
</script>
Now the at the backend the check_email.jsp page will be like this,
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<c:set var="email" value="${param['email']}"/>
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver" user="root" password="root" url="jdbc:mysql://localhost:3306/ercafe"/>
<sql:query dataSource="${db}" sql="SELECT * FROM user_details" var="result" />
<c:forEach var="row" items="${result.rows}">
<c:if test="${row.user_email_id eq email}">
<c:out value="This email is already registered"/>
</c:if>
</c:forEach>
I know that it is not advisable to include the database interaction in the JSP page but as this page would be handled in the backend without any direct interaction from the user I'm very tempted to use check_email.jsp as above. Can anyone tell me how to handle the check_email.jsp by the ideal way?
EDIT: Come on people suggest something.......
Upvotes: 0
Views: 185
Reputation: 13002
Separate your JSP and "backend" code, JSP should only be used for displaying data and your java servlet for doing the logic - separation of concerns is applicable here: https://en.wikipedia.org/wiki/Separation_of_concerns
Have a look at these oracle JDBC tutorials: http://docs.oracle.com/javase/tutorial/jdbc/index.html
In order to get the data from the servlet to display on your JSP page, in the servlet you will do
req.setAttribute(key, value);
And on the JSP side you will use:
${key}
to display that value again.
Upvotes: 2