使用json,连接sqlserver数据库,把数据传入到前台
先看下效果图
1.我使用的是mvc结构写的
2.写DBUtil的工具类,
package cn.hnpi.DButil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author Administrator
* @DBUtil工具类,链接SQLSERVER数据库
*/
public class DBUtil {
//Connection方法
public static Connection getConn(){
String url ="jdbc:sqlserver://localhost:1433;databaseName=MYdb";
String user = "sa";
String pwd = "1";
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, user, pwd);
System.out.println("dbutil");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
//close方法;
public static void closeConn(Connection conn,PreparedStatement ps,ResultSet rs){
try {
if(conn != null){
conn.close();}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(ps != null){
ps.close();}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(rs != null){
rs.close();}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
bean下面的代码,我用只用了三个变量
package cn.hnpi.bean;
public class Book {
//图书编号
private Integer id;
//图书名称
private String bookName;
//图书作者
private String bookAtuor;
public Book() {
super();
}
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 getBookAtuor() {
return bookAtuor;
}
public void setBookAtuor(String bookAtuor) {
this.bookAtuor = bookAtuor;
}
}
service层 和serviceImpl,以及servlet的代码
//service层
package cn.hnpi.service.impl;
import cn.hnpi.bean.Book;
import java.util.List;
public interface BookService {
List<Book> list();
}
//serviceImpl
package cn.hnpi.service.impl;
import cn.hnpi.DButil.DBUtil;
import cn.hnpi.bean.Book;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BookServiceImpl implements BookService {
public List<Book> list() {
// TODO Auto-generated method stub
Connection conn = DBUtil.getConn();
PreparedStatement ps = null;
ResultSet rs = null;
//构建查询语句
String sql = "select * from books";
List<Book> books =new ArrayList<Book>();
try {
ps= conn.prepareStatement(sql);
//从数据库返回一个结果集,使用ResultSet进行接收
rs = ps.executeQuery();
while(rs.next()){
Book book =new Book();
book.setId(rs.getInt(1));
book.setBookName(rs.getString(2));
book.setBookAtuor(rs.getString(3));
books.add(book);
}
} catch ( SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DBUtil.closeConn(conn,ps,rs);
}
System.out.println(books);
return books;
}
}
//servlet代码
package cn.hnpi.servlet;
import cn.hnpi.DButil.DBUtil;
import cn.hnpi.bean.Book;
import cn.hnpi.service.impl.BookService;
import cn.hnpi.service.impl.BookServiceImpl;
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
public class BookServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;chatset=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
BookService bookService = new BookServiceImpl();
List<Book> books = bookService.list();
String json = JSON.toJSONString(books);
System.out.print(json);
out.print(json);
out.flush();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
jsp js代码(省事,直接放一起)
<%--
Created by IntelliJ IDEA.
User: Xntyty
Date: 2019/10/26
Time: 13:53
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>查询数据</title>
</head>
<script src="Js/jquery.js"></script>
<script type="text/javascript">
$(function () {
$(":button").on("click", function () {
$.ajax({
url: "bookServlet",//提交地址
type: "post",//提交方式(get,post)
dataType: "json",//指定服务器返回的数据类型
success: function (data) {//请求成功后的回调函数
$("#tbody").empty(); //删除匹配的元素集合中所有的子节点(就是不重复执行)
var trStr = "";
//使用循环找到控制台的数据
for (var i = 0; i < data.length; i++) {
trStr += "" + data[i].id + " " + data[i].bookName + " " + data[i].bookAtuor + " "
}
$("#tbody").show().append(trStr);//向内部追加内容
},
error: function () {
alert('请求失败');
}
})
});
});
</script>
<body>
<table align="center">
<tr><td><input type="button" value="查看图书"/></td></tr>
<tr>
<td>id</td>
<td>图书名称</td>
<td>图书作者</td>
</tr>
<tbody id="tbody">
</tbody>
</table>
</body>
</html>