How to get ID value in scriptlet before submit?.
My actual scenario is --- I created one JSP page, in which employee ID is the input. Now on blur, I want to get this ID and pass it to a SQL query for validation. Is it possible to send the ID value to SQL before submitting the form? If so, please guide me accordingly with example. If I use, request.getParameter
the ID value is coming as null
.
-
1Please provide some of your code. There are many ways of doing these if my view point in your question is same with your's. If possible avoid using scriptlet. See here http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files/3180202#3180202 – ace Mar 26 '11 at 10:01
2 Answers
Send an ajax request. jQuery is extremely helpful in this. Kickoff example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("#id").blur(function() {
$.getJSON("validateId", $(this).serialize(), function(data) {
$("#id_message").text(data.valid ? '' : 'invalid!');
});
});
});
</script>
<style>
.error { color: red; }
</style>
</head>
<body>
<form action="someservlet" method="post">
<label for="id">id</label>
<input id="id" name="id" />
<span id="id_message" class="error"></span>
<br/>
<input type="submit">
</form>
</body>
</html>
With a servlet which is mapped on an URL pattern of /validateId
and does the following in doGet()
method:
boolean valid = validateId(request.getParameter("id"));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("{valid:" + valid "}");
That's it. The validateId()
method example should of course do the DB job and return true
or false
depending on the outcome.
Note that you still need to perform the same validation in the server side in the servlet behind URL someservlet
. JavaScript is namely disableable/spoofable/hackable. When the server side validation fails, just put the message in a map in the request scope, let the servlet redisplay the JSP and let the JSP display the message using EL.
<span id="id_message" class="error">${messages.id}</span>
... yes, through use of javascript, your ajax call will have to talk to the server, no sample here but you should be able to find lots of examples with a little 'googling'

- 7,334
- 8
- 52
- 80