在JSP和Servlet中使用JQuery的多按钮操作

时间:2012-08-13 07:50:18

标签: jquery

我想在JSP中添加添加,更新,删除,搜索功能的界面。我们可以为所有函数放置一个servlet。我已经allredy添加了添加功能,并且根据我的要求,我已经按钮进行了验证。我在下面添加了所有代码。如果我们不能为所有动作都有一个servlet,我怎么能在jquery中放置单独的动作。

<form id="form-sign-up" class="styled" action="DepartmentServlet" method="post">
            <fieldset>
                <h3>Department </h3>
                <ol>
                    <li class="form-row"><label>Department Id:</label>
                        <input type="text" name="departmentId" id="departmentId" class="text-input required"/><span id="errmsg"></span>
                    </li>
                    <li class="form-row"><label>Department Name:</label>
                        <input type="text" name="departmentName" id="departmentName" class="text-input required"/>
                    </li>
                    <li class="form-row"><label>Department Head:</label>
                        <select name="departmentHead" class="text-input required" id="myDropdown"style="width: 158px"> <option value="">Select Department Head</option>
                            <%

                                String val = "";
                                Department dp = new Department();
                                ResultSet rs = dp.getHeadOfDepartment();
                                while (rs.next()) {
                                    val = rs.getString(2);
                            %>

                            <option value="<%= val%>"><%= val%></option>
                            <%
                                }

                            %>


                        </select>
                    </li>
                    <li class="form-row"><label>Appointed Date:</label>
                        <input id="demo1" name="appointedDate"type="text" maxlength="25" size="25" class="text-input required"><a href="javascript:NewCal('demo1','ddmmmyyyy',true,24)"><img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a>
                            <span class="descriptions">pick a date..</span>
                    </li>

                    <li class="button-row">
                        <input type="submit" value="ADD" class="btn-submit img-swap"/>
                        <input type="submit" value="Delete" class="btn-delete img-swap"/>
                        <input type="submit" value="Update" class="btn-update img-swap"/>
                        <input type="submit" value="Search" class="btn-search img-swap"/>
                    </li>
                </ol>
            </fieldset>

$(document).ready(function() { 
    $("#departmentId").keypress(function (e)  
    { 
        //if the letter is not digit then display error and don't type anything
        if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
        {
            //display error message
            $("#errmsg").html("Digits Only").show().fadeOut("slow"); 
            return false;
        }   
    });


    $('.btn-delete').click(function(e){

        // Declare the function variables:
        // Parent form, form URL, email regex and the error HTML
        var $formId = $(this).parents('form');
        var formAction = $formId.attr('action');
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        var $error = $('<span class="error"></span>');

        // Prepare the form for validation - remove previous errors
        $('li',$formId).removeClass('error');

        $('span.error').remove();

        // Validate all inputs with the class "required"
        $('.required',$formId).each(function(){
            var inputVal = $("#departmentId").val();
            var $parentTag = $("#departmentId").parent();
            if(inputVal == ''){
                $parentTag.addClass('error').append($error.clone().text('Required Field'));
            }






            // Run the email validation using the regex for those input items also having class "email"


            // Check passwords match for inputs with class "password"


        });

        // All validation complete - Check if any errors exist
        // If has errors



        if ($('span.error').length > 0) {

            $('span.error').each(function(){

                // Set the distance for the error animation
                var distance = 5;

                // Get the error dimensions
                var width = $(this).outerWidth();

                // Calculate starting position
                var start = width + distance;

                // Set the initial CSS
                $(this).show().css({
                    display: 'block',
                    opacity: 0,
                    right: -start+'px'
                })
                // Animate the error message
                .animate({
                    right: -width+'px',
                    opacity: 1
                }, 'slow');

            });
        } else {
            $formId.submit();
        }
        // Prevent form submission
        e.preventDefault();


    });

    // Fade out error message when input field gains focus
    $('.required').focus(function(){
        var $parent = $(this).parent();
        $parent.removeClass('error');
        $('span.error',$parent).fadeOut();
    });

    $('.btn-submit').click(function(e){

        // Declare the function variables:
        // Parent form, form URL, email regex and the error HTML
        var $formId = $(this).parents('form');
        var formAction = $formId.attr('action');
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        var $error = $('<span class="error"></span>');

        // Prepare the form for validation - remove previous errors
        $('li',$formId).removeClass('error');

        $('span.error').remove();

        // Validate all inputs with the class "required"
        $('.required',$formId).each(function(){
            var inputVal = $(this).val();
            var $parentTag = $(this).parent();
            if(inputVal == ''){
                $parentTag.addClass('error').append($error.clone().text('Required Field'));
            }






            // Run the email validation using the regex for those input items also having class "email"
            if($(this).hasClass('email') == true){
                if(!emailReg.test(inputVal)){
                    $parentTag.addClass('error').append($error.clone().text('Enter valid email'));
                }
            }

            // Check passwords match for inputs with class "password"
            if($(this).hasClass('password') == true){
                var password1 = $('#password-1').val();
                var password2 = $('#password-2').val();
                if(password1 != password2){
                    $parentTag.addClass('error').append($error.clone().text('Passwords must match'));
                }
            }

        });

        // All validation complete - Check if any errors exist
        // If has errors



        if ($('span.error').length > 0) {

            $('span.error').each(function(){

                // Set the distance for the error animation
                var distance = 5;

                // Get the error dimensions
                var width = $(this).outerWidth();

                // Calculate starting position
                var start = width + distance;

                // Set the initial CSS
                $(this).show().css({
                    display: 'block',
                    opacity: 0,
                    right: -start+'px'
                })
                // Animate the error message
                .animate({
                    right: -width+'px',
                    opacity: 1
                }, 'slow');

            });
        } else {
            $formId.submit();
        }
        // Prevent form submission
        e.preventDefault();


    });

    // Fade out error message when input field gains focus
    $('.required').focus(function(){
        var $parent = $(this).parent();
        $parent.removeClass('error');
        $('span.error',$parent).fadeOut();
    });

});

public class DepartmentServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Getting the Value from the viewer
        String sdepartmentId=request.getParameter("departmentId");
        String departmentName=request.getParameter("departmentName");
        String departmentHead=request.getParameter("departmentHead");
        String dateTime=request.getParameter("appointedDate");




        //Converting to the String department id to integer
        Integer departmentId=Integer.parseInt(sdepartmentId);

        Department dp=new Department();
        dp.setAppDate(dateTime);
        dp.setDepartHead(departmentHead);
        dp.setDepartId(departmentId);
        dp.setDepartName(departmentName);
        try {
            new Department().insertDepartment(dp);
        } catch (SQLException ex) {
            Logger.getLogger(DepartmentServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }



}

1 个答案:

答案 0 :(得分:0)

一个好的做法就是让一个servlet充当控制器。 要使“DepartmentServlet”作为单点servlet足以完成所有操作,下面的代码将在上面的代码中进行一些更改

  1. 在表单标记内的jsp / html页面中添加一个名为action的隐藏变量,其中包含按下相应按钮时要执行的操作。

    <input type="hidden" name="action" id="action" value=""/>

    编写一个jquery函数,该函数将动作的值设置为单击的按钮,例如,当单击添加按钮时,在代码段下面调用

    $("#action").val('add')

  2. 在DepartmentServlet中,检索操作请求参数值

  3.    String action = request.getParameter("action");    
    
       if(action.equals("add")){
    
       }else if(action.equals("update")){
    
       }
       ....
       ....