开发者

How to pass id value from JSP to select query as input before submit?

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, req开发者_开发问答uest.getParameter the ID value is coming as null.


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'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜