前后端分离开发MVC框架实现管理系统
利用了ajax json知识实现的
下面是效果展示:
下面是后端项目:
一个抽象了
Book.java
package cn.hnpi.bean;
public class Book {
private Integer id;// ID
private String name;// 图书名称
private String author;// 图书作者
private String isbn;// 图书编号
private String publish;// 图书出版社
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getPublish() {
return publish;
}
public void setPublish(String publish) {
this.publish = publish;
}
}
定义一个接口
BookService.java
package cn.hnpi.service;
import java.util.List;
import cn.hnpi.bean.Book;
public interface BookService {
/**
* 查询
* @return
*/
List<Book> list();
/**
* 删除
* @param id
* @return
*/
boolean delete(Integer id);
//在更新时就这样传值最方便,别傻傻的一个一个传!!!切记切记切记!!!!!
/**
* 修改
* @param book
* @return
*/
boolean update(Book book);
/**
* 添加
* @param book
* @return
*/
boolean add(Book book);
}
实现接口
BookServiceImpl.java
package cn.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 cn.hnpi.bean.Book;
import cn.hnpi.service.BookService;
import cn.hnpi.util.DButil;
public class BookServiceImpl implements BookService {
//查询
public List<Book> list() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
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.setName(rs.getString(2));
book.setAuthor(rs.getString(3));
book.setIsbn(rs.getString(4));
book.setPublish(rs.getString(5));
list.add(book);
}
} catch (Exception e) {
// TODO: handle exception
} finally {
DButil.close(rs, ps, conn);
}
return list;
}
//删除
public boolean delete(Integer id) {
Connection conn = null;
PreparedStatement ps = null;
int reset = 0;
try {
conn = DButil.getConn();
String sql = "delete from book where id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
reset = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DButil.close(null, ps, conn);
}
if (reset > 0){
return true;
}else{
return false;
}
}
//修改
public boolean update(Book book) {
PreparedStatement ps = null;
Connection conn = null;
int reaset;
try {
conn = DButil.getConn();
String sql = "update book set book_name= ?,book_author = ?,book_isbn = ?,book_publish = ? where id = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, book.getName());
ps.setString(2, book.getAuthor());
ps.setString(3, book.getIsbn());
ps.setString(4, book.getPublish());
ps.setInt(5, book.getId());
reaset = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} finally {
DButil.close(null, ps, conn);
}
if (reaset > 0) {
return true;
} else {
return false;
}
}
//添加
public boolean add(Book book) {
PreparedStatement ps = null;
Connection conn = null;
int reaset;
try {
conn = DButil.getConn();
String sql = "insert into book(id,book_name,book_author,book_isbn,book_publish)values(?,?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setInt(1, book.getId());
ps.setString(2, book.getName());
ps.setString(3, book.getAuthor());
ps.setString(4, book.getIsbn());
ps.setString(5, book.getPublish());
reaset = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} finally {
DButil.close(null, ps, conn);
}
if (reaset > 0) {
return true;
} else {
return false;
}
}
}
LoginServlet.java
package cn.hnpi.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html,charset = utf-8");
PrintWriter out = response.getWriter();
response.setHeader("Access-Control-Allow-Origin", "*");
// 定义两个变量账户name,密码pwd并赋值
String name = "Admin";
String pwd = "Admin123456";
// 获取输入框账户,密码的数据
String ajaxName = request.getParameter("name");
String ajaxPwd = request.getParameter("pwd");
// 进行账户,密码的正确判断
if (name.equals(ajaxName) && pwd.equals(ajaxPwd)) {
// 如果正确则为ok
out.print("ok");
} else{
// 反之则为error
out.print("error");
}
out.flush();
out.close();
}
}
BookAdd.java
package cn.hnpi.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hnpi.bean.Book;
import cn.hnpi.service.BookService;
import cn.hnpi.service.impl.BookServiceImpl;
public class BookAdd 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.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset = utf-8");
PrintWriter out = response.getWriter();
response.setHeader("Access-Control-Allow-Origin", "*");
String id = request.getParameter("id");
String name = request.getParameter("name");
String author = request.getParameter("author");
String isbn = request.getParameter("isbn");
String publish = request.getParameter("publish");
// 实例化接口
BookService service = new BookServiceImpl();
Book book = new Book();
book.setId(Integer.parseInt(id));
book.setName(name);
book.setAuthor(author);
book.setIsbn(isbn);
book.setPublish(publish);
if (service.add(book)) {
out.print("true");
} else {
out.print("true");
}
}
}
BookDelete.java
package cn.hnpi.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hnpi.service.BookService;
import cn.hnpi.service.impl.BookServiceImpl;
public class BookDelete 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 {
request.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
String id = request.getParameter("id");
BookService service = new BookServiceImpl();
if (service.delete(Integer.parseInt(id))) {
response.sendRedirect("http://localhost:63342/10-28-01/listbook.html");
} else {
response.sendRedirect("http://localhost:63342/10-28-01/listbook.html");
}
}
}
BookUpdate.java
package cn.hnpi.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hnpi.bean.Book;
import cn.hnpi.service.BookService;
import cn.hnpi.service.impl.BookServiceImpl;
public class BookUpdate 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.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset = utf-8");
PrintWriter out = response.getWriter();
response.setHeader("Access-Control-Allow-Origin", "*");
String id = request.getParameter("id");
String name = request.getParameter("name");
String author = request.getParameter("author");
String isbn = request.getParameter("isbn");
String publish = request.getParameter("publish");
// 实例化接口
BookService service = new BookServiceImpl();
Book book = new Book();
book.setId(Integer.parseInt(id));
book.setName(name);
book.setAuthor(author);
book.setIsbn(isbn);
book.setPublish(publish);
if (service.update(book)) {
out.print("true");
} else {
out.print("true");
}
out.flush();
out.close();
}
}
BookSelect.java
package cn.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 cn.hnpi.bean.Book;
import cn.hnpi.service.BookService;
import cn.hnpi.service.impl.BookServiceImpl;
import com.alibaba.fastjson.JSON;
public class BookSelect 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.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset = utf-8");
PrintWriter out = response.getWriter();
response.setHeader("Access-Control-Allow-Origin", "*");
BookService service = new BookServiceImpl();
List<Book> lists = service.list();
String json = JSON.toJSONString(lists);
out.print(json);
out.flush();
out.close();
}
}
连接数据库
DButil.java
package cn.hnpi.util;
import java.sql.Connection;
import java.sql.Driver;
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 {
Driver.class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=MyDB", "sa", "1");
}catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(ResultSet rs,PreparedStatement ps,Connection conn) {
try {
if(rs != null)
rs.close();
if(ps != null)
ps.close();
if(conn != null)
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
数据库
CREATE DATABASE MyDB
ON PRIMARY
(
NAME = 'MyDB_data',
FILENAME = 'D:\MyDB_data.mdf',
SIZE = 10MB,
MAXSIZE = 50MB,
FILEGROWTH = 10%
)
LOG ON
(
NAME = 'MyDB_log',
FILENAME = 'D:\MyDB_log.ldf',
SIZE = 10MB,
FILEGROWTH = 1MB
)
GO
USE MyDB
CREATE TABLE book
(
id int PRIMARY KEY NOT NULL,
book_name varchar(64) NOT NULL,--图书名称
book_author varchar(64) NOT NULL,--图书作者
book_isbn varchar(64) NOT NULL,--图书编号
book_publish varchar(64) NOT NULL,--图书出版社
)
INSERT INTO book VALUES(1,'西游记','吴承恩','001','教育局出版社')
INSERT INTO book VALUES(2,'水浒传','施耐庵','002','教育局出版社')
INSERT INTO book VALUES(3,'三国演义','罗贯中','003','教育局出版社')
INSERT INTO book VALUES(4,'红楼梦','曹雪芹','004','教育局出版社')
下面是前端项目
登录页面
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
<script src="js/jquery.js"></script>
<style type="text/css">
body {
background-color: #17181B;
}
form {
margin-top: 250px;
border: 2px solid white;
width: 250px;
height: 145px;
text-align: center;
line-height: 50px;
color: #FBBB46;
border: 2px solid white;
background-color: #17181B;
}
#name, #pwd {
width: 140px;
height: 22px;
}
</style>
</head>
<body>
<center>
<form action="#" method="post">
账户: <input type="text" name="name" id="name"/> <br/> 密码: <input
type="text" name="pwd" id="pwd"/> <br/> <input type="button"
value="登录"/>
</form>
</center>
<script type="text/javascript">
$(function () {
$(":button").on("click", function () {
//ajax请求
$.ajax({
url: "http://localhost:8080/10-28/LoginServlet",
type: "post",
//发送数据到服务器
data: {
name: $("#name").val(),
pwd: $("#pwd").val()
},
dataType: "text",
//success 当请求之后调用。传入返回后的数据,进行判断。
success: function (data) {
if (data == "ok") {
//如果服务器返回的是 ok 则进行跳转到listbook.html页面
window.location.href = "listbook.html";
} else {
//反之进行弹框提示 登录失败
alert("登录失败!!!");
//清空密码
$("#pwd").val("");
}
}
});
});
//失去焦点进行输入框校验
$("#name").blur(function () {
//用户名: 大写字母开头 6-20位字符(不允许有符号但是允许有_)
var limitierName = /^[A-Z]\w{4,19}$/;
reg("name", limitierName);
});
//失去焦点进行输入框校验
$("#pwd").blur(function () {
//密码:大写开头 数字字母符号混合 8-15位
var limitierPwd = /^[A-Z][\w\W]{7,14}$/;
reg("pwd", limitierPwd);
});
//验证的函数
function reg(eleId, rule) {
var inputValue = document.getElementById(eleId).value;
var result = rule.test(inputValue.trim());
if (result) {
//如果符合输入框格式则设边框为蓝色
document.getElementById(eleId).style.borderColor = "#FBBB46";
} else {
//如果不符合输入框格式则设边框为红色
document.getElementById(eleId).style.borderColor = "red";
}
}
});
</script>
</body>
</html>
查询所有数据页面
listbook.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>所有数据</title>
<script src="js/jquery.js"></script>
<style type="text/css">
body {
background-color: #17181B;
}
caption {
color: #FBBB46;
font-size: 18px;
}
table, td, caption {
border: 1px solid #FBBB46;
border-collapse: collapse;
}
table {
text-align: center;
}
td {
color: #FBBB46;
width: 150px;
height: 30px;
text-align: center;
}
a {
text-decoration: none;
color: #FBBB46;
}
p {
width: 500px;
height: 30px;
}
p{
width:1185px;
text-align: right;
}
</style>
</head>
<body>
<table align="center">
<caption><b>图书数据</b></caption>
<thead>
<tr>
<td>ID</td>
<td>图书名称</td>
<td>图书作者</td>
<td>图书编号</td>
<td>图书出版社</td>
<td>操作</td>
</tr>
</thead>
<tbody></tbody>
</table>
<p><a href="add.html">添加数据</a></p>
<script type="text/javascript">
$(function () {
$.ajax({
url: "http://localhost:8080/10-28/BookSelect",
type: "post",
dataType: "json",
success: function (data) {
$("tbody").empty();
$.each(data, function (i) {
var str = "";
str = " <tr><td>" + data[i].id + "</td><td>" + data[i].name + "</td><td>" + data[i].author + "</td><td>" + data[i].isbn + "</td>" +
"<td>" + data[i].publish + "</td><td><a href='http://localhost:8080/10-28/BookDelete?id=" + data[i].id + "'>删除</a>" +
" <a href='update.html?id=" + data[i].id + "'>修改</a></td></tr>";
$("tbody").append(str);
});
}
});
});
</script>
</body>
</html>
添加页面
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加数据</title>
<script src="js/jquery.js"></script>
<style type="text/css">
body {
background-color: #17181B;
}
table {
width: 150px;
}
th {
text-align: left;
color: #FBBB46;
}
td {
text-align: center;
color: #FBBB46;
}
caption {
color: #FBBB46;
}
</style>
</head>
<body>
<center>
<form action="#" method="post">
<table>
<caption>添加数据</caption>
<tr>
<th>ID:</th>
</tr>
<tr>
<td><input type="text" id="id"></td>
</tr>
<tr>
<th>图书名称:</th>
</tr>
<tr>
<td><input type="text" id="name"></td>
</tr>
<tr>
<th>图书作者:</th>
</tr>
<tr>
<td><input type="text" id="author"></td>
</tr>
<tr>
<th>图书编号:</th>
</tr>
<tr>
<td><input type="text" id="isbn"></td>
</tr>
<tr>
<th>图书出版社:</th>
</tr>
<tr>
<td><input type="text" id="publish"></td>
</tr>
<tr>
<td><input type="button" value="提交"></td>
</tr>
</table>
</form>
</center>
<script type="text/javascript">
$(function () {
$(":button").on("click", function () {
$.ajax({
url: "http://localhost:8080/10-28/BookAdd",
type: "post",
data: {
id: $("#id").val(),
name: $("#name").val(),
author: $("#author").val(),
isbn: $("#isbn").val(),
publish: $("#publish").val()
},
dataType: "text",
success: function (data) {
if (data == "true") {
window.location.href = "listbook.html";
}
}
});
});
});
</script>
</body>
</html>
修改页面
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改数据</title>
<script src="js/jquery.js"></script>
<style type="text/css">
body {
background-color: #17181B;
}
table {
width: 150px;
}
th {
text-align: left;
color: #FBBB46;
}
td {
text-align: center;
color: #FBBB46;
}
caption {
color: #FBBB46;
}
</style>
</head>
<body>
<center>
<form action="#" method="post">
<table>
<caption>修改数据</caption>
<tr>
<th>ID:</th>
</tr>
<tr>
<td><input type="text" id="id"></td>
</tr>
<tr>
<th>图书名称:</th>
</tr>
<tr>
<td><input type="text" id="name"></td>
</tr>
<tr>
<th>图书作者:</th>
</tr>
<tr>
<td><input type="text" id="author"></td>
</tr>
<tr>
<th>图书编号:</th>
</tr>
<tr>
<td><input type="text" id="isbn"></td>
</tr>
<tr>
<th>图书出版社:</th>
</tr>
<tr>
<td><input type="text" id="publish"></td>
</tr>
<tr>
<td><input type="button" value="提交"></td>
</tr>
</table>
</form>
</center>
<script type="text/javascript">
$(function () {
$(":button").on("click", function () {
$.ajax({
url: "http://localhost:8080/10-28/BookUpdate",
type: "post",
data: {
id: $("#id").val(),
name: $("#name").val(),
author: $("#author").val(),
isbn: $("#isbn").val(),
publish: $("#publish").val()
},
dataType: "text",
success: function (data) {
if(data == "true"){
window.location.href = "listbook.html";
}
}
});
});
});
</script>
</body>
</html>