如何以HTML格式获取servlet变量

时间:2017-02-21 04:49:55

标签: javascript html ajax servlet-3.0

我试图通过脚本将一个变量从html表单传递给servlet,在servlet中它将连接到DB并获得两个结果变量。

我再次使用请求调度程序将响应转发回html表单,但我仍然坚持让变量以html格式填充。

<title>Insert title here</title>
<script>
function showCustomer() {

    var kkk = document.getElementById("num").value;
    alert("this is mango1 "+kkk);

    var xmlhttp;

    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            <!-- what should come here to get "set attributes value " -->

        }
    };

  xmlhttp.open("POST", "callserv1?num="+kkk, true); 
  xmlhttp.send();
}
</script>
</head>
<body>
<form action=""> 
Receipt no <input type="text" name="num" id="num"/>
<input type="button" onclick="showCustomer(num)" value ="call"/>
</form>
<p id="demo">Customer info will be listed here...</p>
</body>
</html>
import static java.lang.System.out;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class callserv1 extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
    {
        response.setContentType("text/html");   
        PrintWriter out = response.getWriter();
        out.println("This Example demonstrates, using Ajax request to Access Servlet ");
        String grnxx =  request.getParameter("num");
        String pono = null;
        String podt = null;

        out.println("i am in" +grnxx);  

        try
        {                 
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con=DriverManager.getConnection("connection db");
        Statement st=con.createStatement();
        System.out.println("Connection estabilished"+con);

        //Input query to get PO and Itemlist for given GRn
        ResultSet rs=st.executeQuery("query");

        while(rs.next()) {
            pono = rs.getString("doc");
            podt = rs.getString("dt"); 
            System.out.println("Pono:----   "+pono);
            System.out.println("Podt:----   "+podt);
        }

        con.close(); 
        System.out.println("DB Connection closed successfully");

        }   catch (Exception e) {
            System.out.println("Connection error: "+e);
        }

        request.setAttribute("pono", pono);
        request.setAttribute("podt", podt);
        request.getRequestDispatcher("index.html").forward(request,response);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用请求转发将数据从servlet传递到JSP(而不是HTML),并在请求中将数据设置为属性,然后在JSP上,您可以渲染这些数据以生成HTML

在Jsp方面,您可以使用以下选项获取属性值。

  • 小脚本
  • 表达语言