You have to do this through ajax
/ servlet
/ xhr
requests. Here's an example of xhr
request.
For following code to work properly as it as(unedited), You must have your CSV file in C:
drive. Your CSV filename must be mydata.csv
. And, also, you should place index.jsp
and getEmail.jsp
in the same folder.
index.jsp
<%@page import="java.io.File"%>
<%@page import="java.io.FileReader"%>
<%@page import="com.opencsv.CSVReader"%>
<%@page import="java.util.ArrayList"%>
<html>
<head>
<script>
function selected(value){
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "getEmail.jsp?lvpl=" + value, false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
document.getElementById('textbox').value = serverResponse;
}
</script>
</head>
<body>
<%
// Varaibles
String lvpl, email;
int counter = 0;
CSVReader reader = new CSVReader(new FileReader(new File("C://mydata.csv")));
String[] data;
%>
<select onchange="selected(this.value)">
<%
// READING TO CSV TO CREATE DATA IN SELECT BOX
while ((data = reader.readNext()) != null) {
// Skips CSV File Headings: LVPL and EMAIL_ID
if(counter == 0){
counter++; // Increase it so that it can't come in this block again
continue;
}
// CSV FILE DATA AS READ BY CSVREADER
lvpl = data[0]; // LVPL
email = data[1]; // EMAIL
%>
<option><%=lvpl%></option>
<%
}
%>
</select>
<input id="textbox" type="text" placeholder="email will show in here">
</body>
</html>
getEmail.jsp
<%@page import="java.io.FileReader"%>
<%@page import="java.io.File"%>
<%@page import="com.opencsv.CSVReader"%>
<%@page import="java.util.ArrayList"%>
<%
// get lvpl from received request
String lvplReceived = request.getParameter("lvpl");
// Reading CSV
String lvpl = "", email = "";
int counter = 0;
boolean lvplFound = false; // becomes true when lvpl matches selected lvpl
CSVReader reader = new CSVReader(new FileReader(new File("C://mydata.csv")));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
/* Skips CSV File Headers: LVPL and EMAIL_ID */
if(counter == 0){
counter++;
continue;
}
// CSV FILE DATA
lvpl = nextLine[0]; // LVPL
email = nextLine[1]; // EMAIL
if(lvpl.equals(lvplReceived)){ // if this lvpl matches with selected lvpl
lvplFound = true;
break;
}
}
if(lvplFound){ // print email of matched lvpl
out.print(email);
} else {
out.print("not found");
}
%>
tested with mydata.csv
LVPL EMAIL
aaaaa1 [email protected]
aaaaa2 [email protected]
aaaaa3 [email protected]
aaaaa4 [email protected]
aaaaa5 [email protected]
If this didn't work the way you wanted or if you don't understand this code, please feel free to contact me through comments
Useful Links:
Note: If you're learning JSP now, I suggest you to move to JSTL. JSP is no longer used and it was deprecated 10 years ago because it couln't match Microsoft's ASP. If you continue to learn JSP, it will not benefit you in future especially in India, I can't believe people there are still teaching a 10 year old technology. Here's a JSTL book to get you started.