简体   繁体   English

将字符串插入Ag-Grid

[英]Insert String into Ag-Grid

I have a hibernate query that I want to export to an Ag-Grid data javascript file. 我有一个休眠查询,我想导出到Ag-Grid数据javascript文件。

I assumed that my variable "persons" was already in a form that Ag-Grid would be able to take and insert the data into the table. 我以为我的变量“ persons”已经处于一种形式,Ag-Grid将能够采用这种形式并将数据插入表中。 I currently am getting nothing in the table. 我目前在桌子上什么都没有。

I can post the config file for hibernate and Ag-Grid Table constructor file if that would be helpful. 如果有帮助,我可以发布休眠的配置文件和Ag-Grid Table构造函数文件。

Thank you for your help. 谢谢您的帮助。

Search hibernate Code 搜索休眠代码

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;



/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, 
HttpServletResponse response)
     */
    @SuppressWarnings({ "deprecation", "unchecked" })
        protected void doGet(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException {


        SessionFactory factory = new Configuration()
                .configure("hibernate.cfg.xml")
                .addAnnotatedClass(Tbphonebook.class)
                .buildSessionFactory();
        Session session = factory.getSessionFactory().openSession();
        session.beginTransaction();

        String firstName = request.getParameter("searchFirstName");
        // String lastName = request.getParameter("searchLastName");

        @SuppressWarnings("rawtypes")
        Query query = session.createQuery("from Tbphonebook where firstname = ?");

        query.setParameter(0, firstName);


        List<Tbphonebook> persons = (List<Tbphonebook>) query.getResultList();

        request.setAttribute("persons", persons);
        request.getRequestDispatcher("index.jsp").forward(request, response);
        response.sendRedirect("data.js");

        session.getTransaction().commit();
        session.close();        
    }
}

Data java script file 数据Java脚本文件

var ROW_DATA = [{
    persons
}];

function createRowData() {
    return ROW_DATA;
}

Index jsp file 索引jsp文件

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <h1>Search for Contact in Phone Book</h1> <body> <form name="searchInfo" method="get" action="SearchServlet"> Search First Name: <input type="text" name="searchFirstName"/> <br/> <br/> <input type="submit" name="action" value="search" /> </form> </body> <head> <style> html, body { margin: 0; padding: 0; height: 100%; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://unpkg.com/ag-grid-enterprise@15.0.0/dist/ag-grid-enterprise.js"></script> <link rel="stylesheet" href="styles.css"> </head> <body> <style> button:disabled { color: #a0a0a0; } </style> <div style="width: 900px;"> <div style="padding: 4px"> <div style="float: right;"> <input type="text" id="quickFilterInput" placeholder="Type text to filter..."/> </div> <div style="padding: 4px;"> <b>Phone Book Results</b> <span id="rowCount"></span> </div> <div style="clear: both;"></div> </div> <div style="width: 100%; height: 400px;" id="bestHtml5Grid" class="ag-theme-fresh ag-basic"> </div> </div> <script src="data.js"></script> <script src="example.js"></script> </body> </html> 

I know this answer breaks the conventional way of programming in jsp since it mixes java script in the jsp file, but it works. 我知道这个答案打破了在jsp中进行编程的传统方式,因为它在jsp文件中混合了Java脚本,但是它可以工作。

Index.jsp Index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Add contact to Phone Book</h1>
</head>
<body>
  <form name="submitInfo" method="get" action="AddEntryServlet">
        First Name: <input type="text" name="firstName"/> <br/>
        <br/>
        Last Name: <input type="text" name="lastName"/> <br/>
        <br/>
        Area Code: <input type="number" name="areaCode"/> <br/>
        <br/>
        Phone Number: <input type="number" name="phoneNumber"/> <br/>
        <br/>
        <input type="submit" value="Submit" />

    </form>
</body>



<h1>Search for Contact in Phone Book</h1>
<body>

<%Object persons = request.getAttribute("persons"); %>

<br>
  <form name="searchInfo" method="get" action="SearchServlet">
        Search First Name: <input type="text" name="searchFirstName"/> <br/>
        <br/>

        <input type="submit" name="action" value="search" />

        </form>
</body>


</body>

<html>
<head>
<style> html, body { margin: 0; padding: 0; height: 100%; } </style>
    <script src="https://unpkg.com/ag-grid@15.0.0/dist/ag-grid.js"></script>

</head>
<body>
 <input type="text" id="quickFilterInput" placeholder="Type text to filter..."/>
<div id="myGrid" style="width: 100%; height: 100%;" class="ag-theme-fresh"></div>

    <script>

            var columnDefs = [
                {headerName: 'First Name', field: 'firstname'},
                {headerName: 'Last Name', field: 'lastname'},
                {headerName: 'Area Code', field: 'areacode'},
                {headerName: 'Phone Number', field: 'phonenumber'}
            ]


var persons2 ='<%= persons%>';


var persons3 = JSON.stringify(eval("(" + persons2 + ")"));

var persons4 = JSON.parse(persons3);

var rowData = persons4;


var gridOptions = {
    columnDefs: columnDefs,
    rowData: rowData,
    rowSelection: 'multiple',
        enableColResize: true,
        enableSorting: true,
        enableFilter: true,
        enableRangeSelection: true,
        suppressRowClickSelection: true,
        animateRows: true,

        debug: true,
    onGridReady: function (params) {
        params.api.sizeColumnsToFit();
    }
};
 addQuickFilterListener();
 function addQuickFilterListener() {
        var eInput = document.querySelector('#quickFilterInput');
        eInput.addEventListener("input", function () {
            var text = eInput.value;
            gridOptions.api.setQuickFilter(text);
        });
    }

// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function() {

    // lookup the container we want the Grid to use
    var eGridDiv = document.querySelector('#myGrid');

    // create the grid passing in the div to use together with the columns & data we want to use
    new agGrid.Grid(eGridDiv, gridOptions);
});

    </script>
</body>


</html>

The key to the answer is the 答案的关键是

var persons2 ='<%= persons%>';   
var persons3 = JSON.stringify(eval("(" + persons2 + ")"));
var persons4 = JSON.parse(persons3);
var rowData = persons4;

persons2 makes the variable usable by javascript inside the jsp. person2使该变量在jsp中可由javascript使用。 persons3 and persons4 make it so the information is able to be used by Ag-Grid person3和person4做到了,因此Ag-Grid可以使用该信息

I also made a few changes to the searchServlet 我还对searchServlet进行了一些更改

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;




/**
 * Servlet implementation class SearchServlet
 */
@SuppressWarnings("deprecation")
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;



    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @SuppressWarnings({ "unchecked" })
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());

        SessionFactory factory = new Configuration()
                .configure("hibernate.cfg.xml")
                .addAnnotatedClass(Tbphonebook.class)
                .buildSessionFactory();
        Session session = factory.getSessionFactory().openSession();
        session.beginTransaction();

        String firstName = request.getParameter("searchFirstName");


        @SuppressWarnings("rawtypes")
        Query query = session.createQuery("from Tbphonebook where firstname = ?");

        query.setParameter(0, firstName);


        List<Tbphonebook> persons = (List<Tbphonebook>) query.getResultList();

        request.setAttribute("persons", persons);

        request.getRequestDispatcher("index.jsp").forward(request, response);

        response.sendRedirect("index.jsp");


        session.getTransaction().commit();
        session.close();        
    }
}

Since all of the java script work is done in index.jsp the data.js file is no longer being used. 由于所有Java脚本工作都是在index.jsp中完成的,因此不再使用data.js文件。 This is something that breaks suggested practice but works. 这是打破建议的做法但可行的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM