将字符串插入Ag-Grid

时间:2017-12-21 03:39:16

标签: javascript java hibernate ag-grid

我有一个hibernate查询,我想导出到Ag-Grid数据javascript文件。

我认为我的变量“人”已经采用Ag-Grid能够采用的形式并将数据插入表中。我目前在桌子上什么也没得到。

如果有帮助,我可以发布hibernate和Ag-Grid Table构造函数文件的配置文件。

感谢您的帮助。

搜索hibernate代码

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();        
    }
}

数据java脚本文件

var ROW_DATA = [{
    persons
}];

function createRowData() {
    return ROW_DATA;
}

索引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>

1 个答案:

答案 0 :(得分:0)

我知道这个答案打破了传统的jsp编程方式,因为它混合了jsp文件中的java脚本,但是它有效。

的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>

答案的关键是

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

persons2使jsp中的javascript可以使用该变量。 person3和persons4使得信息能够被Ag-Grid使用

我还对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();        
    }
}

由于所有java脚本工作都在index.jsp中完成,因此不再使用data.js文件。这可以打破建议的做法,但有效。