现在是用ajax 做从数据库读取数据的例子

1个jsp
Reg。jsp
Java代码   收藏代码
  1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  2. <%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
  7. <title>无标题文档</title>  
  8. </head>  
  9. <script>  
  10.     var xmlHttp;//不能用数字,标识符的定义  
  11.       
  12.         function creatXML(){//建立异步请求的对象,为了jsp和servlet的交互,固定写法,名字固定  
  13.   
  14.         if(window.ActiveXObject){  
  15.             xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");  
  16.         }else if(window.XMLHttpRequest){  
  17.             xmlHttp=new XMLHttpRequest();  
  18.         }  
  19.     }  
  20.     //调用的主要的方法  
  21.     function a(){  
  22.         creatXML();  
  23.         xmlHttp.open("GET","http://127.0.0.1:9999/test730/servlet/zf");  
  24.         xmlHttp.onreadystatechange=call;  
  25.         xmlHttp.send(null);  
  26.     }  
  27.     //  
  28.     function call(){  
  29.         if(xmlHttp.readyState==4){//固定写法 4 代表完成   
  30.             if(xmlHttp.status==200){//固定写法  200 代表 网页正常  
  31.                 var b=xmlHttp.responseXML.getElementsByTagName("rr");//按照标签的名字对应的是servlet里面的out.println("<rr>"+b.getCity()+"</rr>");  
  32.                 var c=document.getElementById("city");// <select name="city" id="city">里面的id="city"  
  33.                 for(var i=0;i<b.length;i++){//把b里面的数组做循环  
  34.                   
  35.                     var d=document.createElement("option");//option是固定的html标签  
  36.                     d.innerText=b[i].firstChild.nodeValue;//把城市输出的结果显示出来  
  37.                     d.setAttribute("value",b[i].firstChild.nodeValue);//输入value值  
  38.                     c.appendChild(d);//把option里面的东西放入到select标签里面  
  39.                       
  40.                 }  
  41.             }  
  42.         }  
  43.     }  
  44.     //测试用的方法  
  45.     function c(){  
  46.         alert("gag");  
  47.     }  
  48. </script>  
  49. <body οnlοad="a()">  
  50. <form id="form1" name="form1" method="post" action="reg.do">  
  51.   用户名:  
  52.   <label>  
  53.   <input name="username" type="text" id="username" />  
  54.   </label>  
  55.   <p>电话:  
  56.     <label>  
  57.     <input name="tel" type="text" id="tel" />  
  58.     </label>  
  59.   </p>  
  60.   <p>城市:  
  61.     <label>  
  62.     <select name="city" id="city">  
  63.                 
  64.     </select>  
  65.     </label>  
  66.   </p>  
  67.   <p>  
  68.     <label>  
  69.     <input type="submit" name="Submit" value="提交" />  
  70.     </label>  
  71.   </p>  
  72. </form>  
  73. <input type="button" value="gaoying" οnclick="a()"/>  
  74.   
  75. </body>  
  76. </html>  
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<script>
	var xmlHttp;//不能用数字,标识符的定义
	
		function creatXML(){//建立异步请求的对象,为了jsp和servlet的交互,固定写法,名字固定

		if(window.ActiveXObject){
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}else if(window.XMLHttpRequest){
			xmlHttp=new XMLHttpRequest();
		}
	}
	//调用的主要的方法
	function a(){
		creatXML();
		xmlHttp.open("GET","http://127.0.0.1:9999/test730/servlet/zf");
		xmlHttp.onreadystatechange=call;
		xmlHttp.send(null);
	}
	//
	function call(){
		if(xmlHttp.readyState==4){//固定写法 4 代表完成 
			if(xmlHttp.status==200){//固定写法  200 代表 网页正常
				var b=xmlHttp.responseXML.getElementsByTagName("rr");//按照标签的名字对应的是servlet里面的out.println("<rr>"+b.getCity()+"</rr>");
				var c=document.getElementById("city");// <select name="city" id="city">里面的id="city"
				for(var i=0;i<b.length;i++){//把b里面的数组做循环
				
					var d=document.createElement("option");//option是固定的html标签
					d.innerText=b[i].firstChild.nodeValue;//把城市输出的结果显示出来
					d.setAttribute("value",b[i].firstChild.nodeValue);//输入value值
					c.appendChild(d);//把option里面的东西放入到select标签里面
					
				}
			}
		}
	}
	//测试用的方法
	function c(){
		alert("gag");
	}
</script>
<body οnlοad="a()">
<form id="form1" name="form1" method="post" action="reg.do">
  用户名:
  <label>
  <input name="username" type="text" id="username" />
  </label>
  <p>电话:
    <label>
    <input name="tel" type="text" id="tel" />
    </label>
  </p>
  <p>城市:
    <label>
    <select name="city" id="city">
			  
    </select>
    </label>
  </p>
  <p>
    <label>
    <input type="submit" name="Submit" value="提交" />
    </label>
  </p>
</form>
<input type="button" value="gaoying" οnclick="a()"/>

</body>
</html>


1个servlet
Java代码   收藏代码
  1. package sl;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.ArrayList;  
  6.   
  7. import javabean.yonghu;  
  8.   
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import db.DB;  
  15.   
  16. public class zf extends HttpServlet {  
  17.   
  18.     /** 
  19.      * The doGet method of the servlet. <br> 
  20.      * 
  21.      * This method is called when a form has its tag value method equals to get. 
  22.      *  
  23.      * @param request the request send by the client to the server 
  24.      * @param response the response send by the server to the client 
  25.      * @throws ServletException if an error occurred 
  26.      * @throws IOException if an error occurred 
  27.      */  
  28.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  29.             throws ServletException, IOException {  
  30.   
  31.         response.setContentType("text/xml");//设置返回的信息的类型  
  32.         PrintWriter out = response.getWriter();//为了显示输出。  
  33.           
  34.         ArrayList a =new DB().yonghu();  
  35.           
  36.         /** 
  37.          * 做循环输出 
  38.          */  
  39.           
  40.         out.println("<citys>");  
  41.         for(int i=0;i<a.size();i++){  
  42.             yonghu b=(yonghu)a.get(i);  
  43.             out.println("<rr>"+b.getCity()+"</rr>");  
  44.         }  
  45.         out.println("</citys>");  
  46.         out.flush();//把流中的东西刷出去  
  47.         out.close();//关闭  
  48.     }  
  49.   
  50.     /** 
  51.      * The doPost method of the servlet. <br> 
  52.      * 
  53.      * This method is called when a form has its tag value method equals to post. 
  54.      *  
  55.      * @param request the request send by the client to the server 
  56.      * @param response the response send by the server to the client 
  57.      * @throws ServletException if an error occurred 
  58.      * @throws IOException if an error occurred 
  59.      */  
  60.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  61.             throws ServletException, IOException {  
  62.   
  63.           
  64.     }  
  65.   
  66. }  
package sl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javabean.yonghu;

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

import db.DB;

public class zf extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml");//设置返回的信息的类型
		PrintWriter out = response.getWriter();//为了显示输出。
		
		ArrayList a =new DB().yonghu();
		
		/**
		 * 做循环输出
		 */
		
		out.println("<citys>");
		for(int i=0;i<a.size();i++){
			yonghu b=(yonghu)a.get(i);
			out.println("<rr>"+b.getCity()+"</rr>");
		}
		out.println("</citys>");
		out.flush();//把流中的东西刷出去
		out.close();//关闭
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		
	}

}

DB包
Java代码   收藏代码
  1. package db;  
  2.   
  3. import java.sql.*;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.*;  
  6.   
  7. import javabean.yonghu;  
  8.   
  9.   
  10. public class DB {  
  11.     private Connection conn;//用来连接数据库的“数据库连接对象”  
  12.   
  13.     private PreparedStatement stmt;//数据库操作对象  
  14.   
  15.     private ResultSet rs;  
  16.   
  17.     public DB() {  
  18.         try {  
  19.             Class.forName("com.mysql.jdbc.Driver");  
  20.             conn = DriverManager.getConnection(  
  21.                     "jdbc:mysql://localhost:3306/test728""root""1234");  
  22.                     } catch (Exception e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.     }  
  26.   
  27.     public boolean adduser(String username,String tel,String city) {  
  28.         try {  
  29.   
  30.             stmt = conn  
  31.                     .prepareStatement("insert into test728.user(username,tel,city) values(?,?,?)");  
  32.             //stmt.setInt(1, name);  
  33.             stmt.setString(1, username);  
  34.             stmt.setString(2, tel);  
  35.             stmt.setString(3, city);  
  36.   
  37.             stmt.execute();  
  38.   
  39.         } catch (SQLException e) {  
  40.             // TODO Auto-generated catch block  
  41.             e.printStackTrace();  
  42.         }  
  43.         return false;  
  44.   
  45.     }  
  46.   
  47.          public ArrayList yonghu(){  
  48.             ArrayList a=new ArrayList();  
  49.             try {  
  50.                   
  51.                 stmt=conn.prepareStatement("select distinct city from test728.user");  
  52.       
  53.                   
  54.                 rs=stmt.executeQuery();  
  55.                 while(rs.next()){  
  56.   
  57.                     yonghu c=new yonghu();  
  58.                     //c.setId(Integer.parseInt(rs.getString("id")));  
  59.                     //c.setUsername(rs.getString("username"));  
  60.                     //c.setTel("tel");  
  61.                     c.setCity(rs.getString("city"));  
  62.                     a.add(c);  
  63.                       
  64.                 }  
  65.               
  66.             } catch (SQLException e) {  
  67.                 // TODO Auto-generated catch block  
  68.                 e.printStackTrace();  
  69.             }  
  70.               
  71.             return a;  
  72.         }  
  73. }  
package db;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;

import javabean.yonghu;


public class DB {
	private Connection conn;//用来连接数据库的“数据库连接对象”

	private PreparedStatement stmt;//数据库操作对象

	private ResultSet rs;

	public DB() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/test728", "root", "1234");
					} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean adduser(String username,String tel,String city) {
		try {

			stmt = conn
					.prepareStatement("insert into test728.user(username,tel,city) values(?,?,?)");
			//stmt.setInt(1, name);
			stmt.setString(1, username);
			stmt.setString(2, tel);
			stmt.setString(3, city);

			stmt.execute();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;

	}

		 public ArrayList yonghu(){
			ArrayList a=new ArrayList();
			try {
				
				stmt=conn.prepareStatement("select distinct city from test728.user");
	
				
				rs=stmt.executeQuery();
				while(rs.next()){

					yonghu c=new yonghu();
					//c.setId(Integer.parseInt(rs.getString("id")));
					//c.setUsername(rs.getString("username"));
					//c.setTel("tel");
					c.setCity(rs.getString("city"));
					a.add(c);
					
				}
			
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return a;
		}
}

1 个javabean
Java代码   收藏代码
  1. package javabean;  
  2.   
  3. public class yonghu {  
  4.     private int id;  
  5.     private String username;  
  6.     private String tel;  
  7.     private String city;  
  8.     public String getUsername() {  
  9.         return username;  
  10.     }  
  11.     public void setUsername(String username) {  
  12.         this.username = username;  
  13.     }  
  14.     public String getTel() {  
  15.         return tel;  
  16.     }  
  17.     public void setTel(String tel) {  
  18.         this.tel = tel;  
  19.     }  
  20.     public String getCity() {  
  21.         return city;  
  22.     }  
  23.     public void setCity(String city) {  
  24.         this.city = city;  
  25.     }  
  26.     public int getId() {  
  27.         return id;  
  28.     }  
  29.     public void setId(int id) {  
  30.         this.id = id;  
  31.     }  
  32.   
  33. }  
package javabean;

public class yonghu {
	private int id;
	private String username;
	private String tel;
	private String city;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}

}

Web.xml
Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  3.   <servlet>  
  4.     <servlet-name>action</servlet-name>  
  5.     <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>  
  6.     <init-param>  
  7.       <param-name>config</param-name>  
  8.       <param-value>/WEB-INF/struts-config.xml</param-value>  
  9.     </init-param>  
  10.     <init-param>  
  11.       <param-name>debug</param-name>  
  12.       <param-value>3</param-value>  
  13.     </init-param>  
  14.     <init-param>  
  15.       <param-name>detail</param-name>  
  16.       <param-value>3</param-value>  
  17.     </init-param>  
  18.     <load-on-startup>0</load-on-startup>  
  19.   </servlet>  
  20.   <servlet>  
  21.     <description>This is the description of my J2EE component</description>  
  22.     <display-name>This is the display name of my J2EE component</display-name>  
  23.     <servlet-name>zf</servlet-name>  
  24.     <servlet-class>sl.zf</servlet-class>  
  25.   </servlet>  
  26.   
  27.   <servlet-mapping>  
  28.     <servlet-name>action</servlet-name>  
  29.     <url-pattern>*.do</url-pattern>  
  30.   </servlet-mapping>  
  31.   <servlet-mapping>  
  32.     <servlet-name>zf</servlet-name>  
  33.     <url-pattern>/servlet/zf</url-pattern>  
  34.   </servlet-mapping>  
  35. </web-app>  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
读取 MongoDB 中的数据并在 HTML 中显示,您可以使用以下步骤: 1. 使用 MongoDB 的驱动程序连接到您的数据库。 2. 编写查询以检索所需的数据。 3. 将查询结果转换为 JSON 格式。 4. 在 HTML 页面中使用 JavaScript 代码来获取 JSON 数据并将其呈现为 HTML 元素。 以下是一个简单的示例: 在 Node.js 中使用 MongoDB 驱动程序连接到数据库: ``` const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017/mydb'; MongoClient.connect(url, function(err, db) { if (err) throw err; console.log('Database connected!'); // 查询数据并将其呈现为 JSON 格式 db.collection('mycollection').find({}).toArray(function(err, result) { if (err) throw err; console.log(result); // 将 JSON 数据发送到 HTML 页面 app.get('/', function(req, res) { res.send(result); }); db.close(); }); }); ``` 在 HTML 页面中使用 JavaScript 获取 JSON 数据并将其呈现为 HTML 元素: ``` <html> <head> <title>MongoDB Data</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function() { // 获取 JSON 数据 $.getJSON('/', function(data) { // 将数据呈现为 HTML 元素 var items = []; $.each(data, function(key, val) { items.push('<li>' + val.name + '</li>'); }); $('ul').html(items.join('')); }); }); </script> </head> <body> <h1>MongoDB Data</h1> <ul></ul> </body> </html> ``` 在这个例子中,我们使用 jQuery 库来轻松地获取 JSON 数据并将它们呈现为 HTML 元素。您也可以使用原生 JavaScript 来实现相同的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值