如何在editurl中设置路径url并在jqgrid中启用添加功能,以便我可以影响数据库?

时间:2014-06-30 07:59:06

标签: jsp servlets jqgrid

我正在使用 postgres db。

我使用以下凭据连接到db。

username = "postgres";
password = "asbestos";
url = "jdbc:postgresql://localhost:5432/griddemo";

我已将jquery代码放在jsp中。通过servlet,我已经在jsp页面的jqgrid中获取并显示了记录。现在我想启用添加,编辑和删除功能。我在triands中找到了文档,我很困惑,因为它使用php来描述。

 <script type="text/javascript">
        <% String json = (String)request.getAttribute("val");   %> 
        var  jso = <%=json%>; <!-- retrieve from servlet -->
        $(document).ready(

                function () 
                {
                'use strict';
                var mydata= jso,
                $grid = $("#list"),

                initDateEdit = function (elem) 
                {
                    setTimeout(function () {
                        $(elem).datepicker({
                            dateFormat: 'dd-M-yy',
                            autoSize: true,
                            changeYear: true,
                            changeMonth: true,
                            showButtonPanel: true,
                            showWeek: true
                        });
                    }, 100);
                },

                initDateSearch = function (elem) 
                {
                    setTimeout(function () {
                        $(elem).datepicker({
                            dateFormat: 'dd-M-yy',
                            autoSize: true,
                            changeYear: true,
                            changeMonth: true,
                            showWeek: true,
                            showButtonPanel: true
                        });
                    }, 100);
                },
                numberTemplate = {
                        formatter: 'number', 
                        align: 'right', 
                        sorttype: 'number', 
                        editable: true,
                        searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'] }
                                  }

            $grid.jqGrid({
                /* url:'grid.php',
                datatype: 'json', */
                mtype: 'POST',
                datatype: 'local',
                data: mydata,
                colNames: [/*'Inv No', */'Client', 'Date', 'Amount', 'Tax', 'Total', 'Closed', 'Shipped via', 'Notes'],

             colModel: [
                    //{ name: 'id', index: 'id', width: 70, align: 'center', sorttype: 'int', searchoptions: { sopt: ['eq', 'ne']} },
                    { name: 'name', index: 'name', editable: true, width: 70, editrules: { required: true},
                    editoptions: { dataInit: function (elem) { $(elem).addClass('ui-state-highlight'); }}},

                    { name: 'invdate', index: 'invdate', width: 80, align: 'center', sorttype: 'date',
                    formatter: 'date', formatoptions: { newformat: 'd-M-Y' }, editable: true, datefmt: 'd-M-Y',
                    editoptions: { dataInit: initDateEdit },
                    searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'], dataInit: initDateSearch } },

                    { name: 'amount', index: 'amount', width: 80, template: numberTemplate },

                    { name: 'tax', index: 'tax', width: 55, template: numberTemplate,
                        editoptions: { dataInit: function (elem) { $(elem).addClass('ui-state-error'); }} },

                    { name: 'total', index: 'total', width: 65, template: numberTemplate},

                    {name: 'closed', index: 'closed', width: 75, align: 'center', editable: true, formatter: 'checkbox',
                        edittype: 'checkbox', editoptions: {value: 'Yes:No', defaultValue: 'Yes'},
                        stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':Any;true:Yes;false:No'} },

                    {name: 'ship_via', index: 'ship_via', width: 105, align: 'center', editable: true, formatter: 'select',
                        edittype: 'select', editoptions: { value: 'FE:FedEx;TN:TNT;IN:Intim', defaultValue: 'IN'},
                        stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':Any;FE:FedEx;TN:TNT;IN:IN'} },

                    { name: 'note', index: 'note', width: 60, sortable: false, editable: true, edittype: 'textarea'}
                ] ,
                rowNum: 10,
                rowList: [5, 10, 50],
                pager: '#pager',
                gridview: true,
                rownumbers: true,
                autoencode: true,
                ignoreCase: true,
                sortname: 'invdate',
                viewrecords: true,
                sortorder: 'desc',
                height: '100%',
                caption: 'Customer Table'
                 /* editurl:"index.jsp" */
            });

            $grid.jqGrid('navGrid', '#pager', {refreshstate: 'current', add: true, edit: true, del: true});

            $.extend(true, $.ui.multiselect, {
                locale: {
                    addAll: 'Make all visible',
                    removeAll: 'Hidde All',
                    itemsCount: 'Avlialble Columns'
                }
            });
         /*   $.extend(true, $.jgrid.col, {
                width: 500,
               msel_opts: {dividerLocation: 0.5}
            });  */
         /*    $grid.jqGrid('searchGrid', '#pager',{multipleSearch:true} ); */
             $grid .jqGrid('editGridRow', rowid, properties );

            $grid.jqGrid('navButtonAdd', '#pager', {
                caption: "",
                buttonicon: "ui-icon-calculator",
                title: "Choose columns",
                onClickButton: function () {
                    $(this).jqGrid('columnChooser',
                        {width: 550, msel_opts: {dividerLocation: 0.5}});
                    //$(this).jqGrid('columnChooser');
                    $("#colchooser_" + $.jgrid.jqID(this.id) + ' div.available>div.actions')
                        .prepend('<label style="float:left;position:relative;margin-left:0.6em;top:0.6em">Search:</label>');
                }
            });      
        });

    </script>

html的正文部分

<body>
    <form action="Loginservlet1" method="get">
        <input type="submit" id=fixedbutton value="get values">
    </form>                 <!-- ========== Call to servlet ============ -->
        <div class="container">
        <div class="table-responsive">
            <div id="content" style="float: center">
                <table id="list">
                    <tr>
                        <td />
                    </tr>
                </table>
                <div id="pager"></div>
            </div>
        </div>
    </div>      <!-- Main component for a primary message or call to action -->
    <!-- /container -->

这是我的servlet类

public class Loginservlet1 extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Connection connection= null;

    public Loginservlet1() {
        super();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("Into servlet>>>>>");
        String val = null;
        ConnectionUtil connUtil = new ConnectionUtil();

            try {
                System.out.println("in servlet");
                val = connUtil.getConnection();

            } catch (Exception e) {

                e.printStackTrace();
            }

            request.setAttribute("val",val.toString());
            request.getRequestDispatcher("/index.jsp").forward(request, response);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    }
}

这是在连接成功后servlet调用的Dao.java类。 公共课程LoginDao {

public String doFetch(Connection conn)throws Exception{
    //  boolean insertFlag = false;
        //PreparedStatement ps =null;
        ResultSet rs = null;
        Statement stmt=null;
        // connection = null;
        //int i = 0;
        try{


                String sql="select id,c.name,invdate,amount,tax,total,closed,ship_via,note from invheader i,clients c where  c.client_id=i.client_id order by i.id limit 100";
                stmt =conn.createStatement(); //connection to statement
                rs = stmt.executeQuery(sql); 
                System.out.println("in dao");
                 //get 


                   List<Map<String, Object>>  contents = getEntitiesFromResultSet(rs); 
                   ObjectMapper mapper = new ObjectMapper();     // Jack json librarys
                   String json = mapper.writeValueAsString(contents);
                 //  System.out.println(json);
                   return  json;
            }catch(Exception e){
            e.printStackTrace();
            throw e;
        }

        /*return null;*/


    }


     protected static List<Map<String, Object>> getEntitiesFromResultSet(ResultSet resultSet) throws SQLException 
        { System.out.println("in dao2222");
            ArrayList<Map<String, Object>> entities = new ArrayList<Map<String, Object>>();
            while (resultSet.next()) {
                entities.add(getEntityFromResultSet(resultSet)); //add map into List
            }
          //  System.out.println(entities);
            return entities; 

            //final output
            /* output:[{age=25, name=Dinesh},
             *  {age=29, name=Aarya}, 
             *  {age=26, name=arjun}, 
             *  {age=30, name=Drona}]
            */
        }

        private static Map<String, Object> getEntityFromResultSet(ResultSet rs1) throws SQLException 
        {
             ResultSetMetaData metaData = rs1.getMetaData(); //get meta data from resultset
                int columnCount = metaData.getColumnCount(); // get no. of columns by getColumnCount() function in metadata 
                Map<String,Object> resultsMap = new HashMap<String,Object>(); // init hashmap
                for (int i = 1; i <= columnCount; ++i) { 
                    String columnName = metaData.getColumnName(i).toLowerCase(); //get column data
                    Object object = rs1.getObject(i);
                    resultsMap.put(columnName, object);
                } //runs until column count
               // System.out.println(columnCount);
                return resultsMap;  
                /* output:
                *  {age=25, name=Dinesh}
                *{age=29, name=Aarya}
                *   {age=26, name=arjun}
                *   {age=30, name=Drona} 
                **/
        }
    }

更新 我知道他们在 php 中使用switch语句来插入/更新/删除记录。喜欢这个

switch ($_POST["oper"]) {
    case "add":
        // do mysql insert statement here
    break;
    case "edit":
        // do mysql update statement here
    break;
    case "del":
        // do mysql delete statement here
    break;
}

我如何在java servlet中实现相同的功能。

如何在jqgrid中启用添加,编辑和删除功能。请帮帮我

1 个答案:

答案 0 :(得分:0)

这里我删除功能。将所需参数传递给servlet,并从servlet执行删除查询。这是jsp页面的代码:

 jQuery().ready(function (){
    jQuery("#list").jqGrid({
        url:'<%=url%>',
        datatype: "xml",
        height: 250,
        colNames:[],
      //  colNames:['S.No','fromMailId','subject','isPriority','creationDate','caa'],
        colModel:[  ],

            <% if(type.equals("")){ %>
            multiselect: false,
          <%  }else{ %>
              multiselect: true,
              <% } %>
            //multiboxonly: true,
            autowidth: true,
          //  multiselect: false,
            navigator:true,
            paging: true,
            rowNum:10,
            rowList:[10,20,30],
            pager: $("#page"),
            caption: "<%=caption%>",
            gridComplete: function(){
                $("#list tr:nth-child(even)").css("background-color", "#fff");
            }
        ).navGrid('#page',{edit:false,add:false,del:true,deltext:"Move to Trash"},{},{},
            /*delete start */{
                 url: '<%=request.getContextPath() + "/MessageBoxServlet?inbox=Remove&msgBoxType="+type+"&userId="+userId%>',
                 closeOnEscape: true,
                 multipleSearch: true,
                 caption: "Confirmation",
                 msg: "Are you sure to move all selected message to trash?",
                 bSubmit: "Yes",
                 bCancel: "No",
                 width:350,
                 resize: false,
                 delicon:[false,,],
                 cancelicon:[false,,],
                 reloadAfterSubmit: true,
                 afterShowForm: function(form) {
                        form.closest('div.ui-jqdialog').center();
                    },
                // afterShowForm: function ($form) {
               //         $("#dData", $form.parent()).click();
               //  },

                 delData: {
                   MsgId: function () {
                        var sel_id = $('#list').jqGrid('getGridParam', 'selarrrow');
                        var value ="";
                        for(var a=0;a < sel_id.length;a++)
                            {
                               value = value + $('#list').jqGrid('getCell', sel_id[a], 'msgBoxId')+",";
                               if(value=="false,")
                                     value = "";
                            }
                        value = value.substring(0,value.length-1);
                       return value;
                   }
               },
               afterSubmit : function(response)
                 {
                   // return alert("success");
                 //  var xml = response.responseText;
                   var xml = $.parseXML(response.responseText),
                      $xml = $( xml ),
                      $msg = $xml.find("cell");
                   document.getElementById("message").innerHTML = $msg.text();
                  // document.getElementById("message").text = $title;
                   return document.getElementById("message").style.display = "block";
                 }
             }
          );

        <%}%>
    });