Ajax&Servlet获取表数据

最下面有惊喜哦
一、功能介绍
1、首先通过登录界面来进行登录(登录的账户密码,是从数据库中获取的)
2、登录成功,则跳转到图书信息查询结果界面
3、登录失败则无跳转,并显示登录失败
效果图:
在这里插入图片描述
二、代码实现
HTML项目目录
在这里插入图片描述
web项目目录:
在这里插入图片描述
在这里插入图片描述
数据库建两个表(用户账户表(users)和图书信息表(book)):
在这里插入图片描述
在这里插入图片描述
1、首先先写一个登陆界面,然后进行正则表达式的判断,如果判断都成功则给登录按钮设置点击事件,代码如下:
html(界面):

<head>
		<meta charset="UTF-8">
		<title>登录</title>
		<script src="js/jquery.js"></script>
		<link rel="stylesheet" type="text/css" href="css/login.css" />

	</head>

	<body>
		<div id="div">
			<table>
				<tr>
					<th>用户名:</th>
					<td><input type="text" id="name" data-index="0" /></td>
				</tr>
				<tr>
					<th>密码:</th>
					<td><input type="text" id="pwd" data-index="1" /></td>
				</tr>
				<tr>
					<td colspan="3" id="losing"></td>
				</tr>
				<tr>
					<td colspan="3" style="text-align: center;">
						<div id="login">登 录</div>
					</td>
				</tr>
			</table>
		</div>

外部css样式:

#div {
	width: 400px;
	height: 260px;
	margin: 0px auto;
	border-radius: 20px;
	background-repeat: no-repeat;
	background-size: 470px;
	margin-top: 100px;
	background-image: url(../img/1.jpg);
}

th {
	width: 80px;
	text-align: right;
}

table {
	width: 300px;
	height: 150px;
	margin-top: 60px;
	margin-left: 50px;
	position: absolute;
}

input {
	font-size: 18px;
	width: 190px;
	border-radius: 10px;
	margin-top: 10px;
}

#login {
	width: 100px;
	height: 40px;
	background-color: #CCCCCC;
	margin-left: 100px;
	border-radius: 20px;
	line-height: 40px;
}

#losing {
	height: 30px;
	font-size: 12px;
	padding: 0px;
	text-align: center;
	color: red;
}

接下来该中最重要的部分,就是js代码了(具体解释看注释):
(注:这里要注意的就是ajax里面的URL的地址)

<script type="text/javascript">
			//调用getText()方法,来判断正则表达式
			getText();

			//登陆跳转事件方法
			function skip() {
				$(function() {
					$.ajax({
						//地址必须是在浏览器上打开BookInfoServlet文件的地址
						url: "http://127.0.0.1:8080/Login2/LoginServlet",
						type: "post",
						data: {
							name: $("#name").val(),
							pwd: $("#pwd").val(),
						},
						dataType: "text",
						success: function(data) {
							//如果返回的值是true,则跳转到bookInfo.html,否则登录失败
							if(data == "true") {
								window.location.href = "bookInfo.html";
							} else {
								//否则显示登录失败,并给id是losing的标签内的文本设置一个定时器,让文本清空
								$("#losing").text("登录失败");
								setTimeout(function() {
									$("#losing").text("");
								}, 3000);
							}
						}
					});
				});
			}

			//登录按钮事件
			function loginBtn() {
				//如果两个span里面的内容是“√√”,就改变登录按钮的背景色,并加一个点击事件
				if($("span").text() == "√√") {
					$("#login").css("background-color", "chartreuse");
					$("#login").on("click", function() {
						skip();
					});
				} else {
					//否则登录按钮背景色不改变,并取消点击事件
					$("#login").css("background-color", "#CCCCCC");
					$("#login").off("click");
				}
			}
			//获取 输入框内容 与 正则表达式 做对比
			function getText() {
				var reg = [/^[a-z]{5,12}$/, /^[a-z\d]{5,12}$/];
				$(":text,:password").after("<span></span>").blur(function() {
					if(reg[$(this).attr("data-index")].test($(this).val())) {
						$(this).next("span").text("√").css("color", "green");
					} else {
						$(this).next("span").text("×").css("color", "red");
					}
					loginBtn();
				});
			}
		</script>
	</body>
</html>

2、登录界面有了,下面就该如何获取数据库中登录账户的信息了,首先建一个web项目
a、既然要与数据库做连接,就先来写一个连接数据库的类,代码如下:

package com.hnpi.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
	public static Connection getConn() {
		Connection conn = null;
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			conn = DriverManager.getConnection(
					"jdbc:sqlserver://localhost:1433;databaseName=Book", "sa",
					"1");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	//关闭数据库资源接口方法
	public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
		try {
			if (conn != null) {
				conn.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

b、然后写一个登陆的servlet(LoginServlet)
(注:这里面注意的就是,如果要进行跨域,就必须要有:response.setHeader(“Access-Control-Allow-Origin”, “*”);这段代码)

package com.hnpi.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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

import com.hnpi.util.DBUtil;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//允许跨域(这是必须要写的)
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		//获取输入框的内容
		String ajaxName = request.getParameter("name");
		String ajaxPwd = request.getParameter("pwd");

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			conn = DBUtil.getConn();
			String sql = "select * from users where name = ? and pwd = ?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, ajaxName);
			ps.setString(2, ajaxPwd);
			rs = ps.executeQuery();
			//如果输入框里的数据 在数据库中存在,则输出true,否则输出false
			if (rs.next()) {
				out.print("true");
			} else {
				out.print("false");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.flush();
		out.close();
	}
}

3、接下来,当登录成功后跳转到图书信息的界面,把图书信息通过表格形式来展示,首先要有HTML界面
a、HTML和css样式代码如下:

<head>
		<meta charset="UTF-8">
		<title>图书信息</title>
		<script src="js/jquery.js"></script>
		<style type="text/css">
			table,
			table td {
				border: 2px solid red;
				border-collapse: collapse;
				text-align: center;
			}
			table{
				margin-left: 40px;
			}
			div{
				width: 400px;
				height: auto;
				margin: 0px auto;
			}
		</style>
	</head>

	<body>
		<div>
			<table>
				<thead>
					<tr>
						<td>ID</td>
						<td>图书名字</td>
						<td>图书作者</td>
						<td>图书出版社</td>
					</tr>
				</thead>
				<tbody></tbody>
			</table>
		</div>

然后实现js代码:

<script type="text/javascript">
			$.ajax({
				//地址必须是在浏览器上打开BookInfoServlet文件的地址
				url: "http://127.0.0.1:8080/Login2/BookInfoServlet",
				type: "post",
				data: {},
				dataType: "json",
				success: function(data) {
					console.log(data);//使用console.log()方法来找到对象的内容
					$.each(data, function(i) {
						var trString = "<tr><td>" + data[i].id + "</td><td>" + data[i].bookName + "</td><td>" + data[i].bookAuthor + "</td><td>" + data[i].bookPress + "</td></tr>";
						$("tbody").append(trString);
					});
				}
			});
		</script>
	</body>
</html>

b、最后就是通过web项目来获取图书信息:
1、写一个图书类:

package com.hnpi.bean;

public class Book {
	private Integer id;
	private String bookName;
	private String bookAuthor;
	private String bookPress;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public String getBookAuthor() {
		return bookAuthor;
	}
	public void setBookAuthor(String bookAuthor) {
		this.bookAuthor = bookAuthor;
	}
	public String getBookPress() {
		return bookPress;
	}
	public void setBookPress(String bookPress) {
		this.bookPress = bookPress;
	}
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(Integer id, String bookName, String bookAuthor, String bookPress) {
		super();
		this.id = id;
		this.bookName = bookName;
		this.bookAuthor = bookAuthor;
		this.bookPress = bookPress;
	}
}

2、接口interface:

package com.hnpi.service;

import java.util.List;
import com.hnpi.bean.Book;

public interface BookService {
	List<Book> select();
}

3、实现接口:

package com.hnpi.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hnpi.bean.Book;
import com.hnpi.service.BookService;
import com.hnpi.util.DBUtil;

public class BookServiceImpl implements BookService {

	public List<Book> select() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		//new一个数组
		List<Book> list = new ArrayList<Book>();
		
		try {
			conn = DBUtil.getConn();
			String sql = "select * from book";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				Book book = new Book();
				//获取数据库表中每一列的数据
				book.setId(rs.getInt(1));
				book.setBookName(rs.getString(2));
				book.setBookAuthor(rs.getString(3));
				book.setBookPress(rs.getString(4));
				//把获取的数据放到list数组中
				list.add(book);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBUtil.close(conn, ps, rs);
		}
		return list;
	}
}

4、servlet界面,调用select()方法,获取数组中的数据,把数据放到JSON中,通过json把数据返回到HTML界面展示出来,代码如下:

package com.hnpi.servlet;

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

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

import com.alibaba.fastjson.JSON;
import com.hnpi.bean.Book;
import com.hnpi.service.BookService;
import com.hnpi.service.impl.BookServiceImpl;

public class BookInfoServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//允许跨域(这是必须要写的)
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		//实例化BookService接口
		BookService bookService = new BookServiceImpl();
		//获取接口里的select()方法
		List<Book> list = bookService.select();
		//把查询到的数据放到JSON中
		String bookStr = JSON.toJSONString(list);
		
		out.println(bookStr);
		out.flush();
		out.close();
	}
}

三、以上就是实现整个功能效果的代码了,如果觉得代码排布有点乱,可以通过文字描述来理解,最后,可以扫描下面二维码关注微信公众号,回复:js1027 领取源代码:
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值