如何使用javascript从servlet检索数据到jsp

时间:2017-03-25 11:26:45

标签: javascript jsp servlets

我是servlets的新手我编写了一个servlet,它从数据库中获取数据并打印一个表,我有一个jsp页面,其中有一个按钮来搜索员工ID。 我的要求是表格应该显示在我搜索的同一页面中 jsp page.I我整天搜索但是找不到使用javascript的解决方案。我希望这只能使用javascript而不是jquery。提前完成。 这是我的jsp页面

search.jsp的

<html>
<head>

    <script>
        var request;
        var date;
        function data()
        {

            var v = document.getElementById("ele1").value;

            var url = "Retrieve?ele1=" + v;
            alert("v" + v);
            if (window.XMLHttpRequest)
            {
                request = new XMLHttpRequest();
            } else if (window.ActiveXObject)
            {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            try
            {
                request.onreadystatechange = getInfo;
                request.open("GET", url, true);
                request.send();

            } catch (e)
            {
                alert("unable to connect to server");
            }
        }
        function getInfo()
        {
            request = new XMLHttpRequest();

            if (request.readyState == 4)
            {

                alert(val);
                var response = request.responseXML;
                var val = request.responseText;
                document.getElementById("sun").innerHTML = val;
            }
        }

        }

    </script>
</head>
<body>
    <div>
        <form id="search" name="search" action="Retrieve" method="post"> 
            <label id="search">Search By Empid</label>
            <input type="text" name="ele1" id="ele1">
            <input type="button" value="Get Details" onclick="data();">

        </form>

    </div>
    <div id="sun">

    </div>
</body>

这是我的servlet页面

Retrieve.java

public class Retrieve扩展了HttpServlet {

Connection con = null;
Statement st = null;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //response.setContentType("text/html;charset=UTF-8");

    try (PrintWriter out = response.getWriter()) {

        Class.forName("org.postgresql.Driver");
        con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/name", "postgres", "admin");
        st = con.createStatement();

        String num = request.getParameter("ele1");
        int id = Integer.valueOf(num);
        PreparedStatement ps = con.prepareStatement("select * from empretrieve where Empid=?");
        ps.setInt(1, id);

        out.print("<table width=50% border=1>");
        out.print("<caption>Result:</caption>");

        ResultSet rs = ps.executeQuery();

        ResultSetMetaData rsmd = rs.getMetaData();
        int tot = rsmd.getColumnCount();
        out.print("<tr>");
        for (int i = 1; i <= tot; i++) {
            out.print("<th>" + rsmd.getColumnName(i) + "</th>");

        }
        out.print("</tr>");

        while (rs.next()) {
            out.print("<tr><td>" + rs.getInt(1) + "</td><td>" + rs.getString(2) + "</td><td>" + rs.getString(3) + "</td><td>" + rs.getString(4) + "</td><td>" + rs.getString(5) + "</td><td>" + rs.getString(6) + "</td><td>" + rs.getString(7) + "</td><td>" + rs.getString(8) + "</td><td>");
        }
        out.print("</table>");
        System.out.println("processRequest : : ");

    } catch (Exception e) {
        PrintWriter out = response.getWriter();
        out.println(" e : " + e);
    } finally {
        try {
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (Exception ex) {
        }
    }

}

1 个答案:

答案 0 :(得分:0)

这对我有用: Servlet的:

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

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

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

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

JSP:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>XTMLREQUEST</title>
</head>
<body>

<h1>XTMLREQUEST</h1>
Response:<div id="response"></div>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'XTMLRequestServlet', true);

// If specified, responseType must be empty string or "text"
xhr.responseType = 'text';

xhr.onload = function () {
    if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) {
           var el  = document.querySelector("#response");
           el.insertAdjacentHTML("beforeend", xhr.responseText);
            console.log(xhr.responseText);
        }
    }
};

xhr.send(null);
</script>
</body>
</html>