DbUtil
package com.hoppz.exam.Util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbUtil {
private static String url = "jdbc:mysql://localhost:3306/db_studentinfo";
private static String name = "root";
private static String ps = "3789xsx";
private static String jdbcName = "com.mysql.jdbc.Driver";
///背,记得连个都要 throw Exception
public static Connection getCon() throws Exception
{
try {
Class.forName(jdbcName);
}catch( ClassNotFoundException e ){
System.out.println("找不导类,加载失败");
e.printStackTrace();
}
Connection con = (Connection) DriverManager.getConnection(url,name,ps);
return con;
}
public static void closeCon(Connection con) throws Exception {
if(con != null) {
con.close();
}
}
}
BookDao
package com.hoppz.exam.Dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.hoppz.exam.Model.*;
import com.hoppz.exam.Util.*;
import com.sun.crypto.provider.RSACipher;
public class BookDao {
private static final String Interger = null;
/*
* 获得表,主要用于booklist.jsp显示
* */
public static List<Book> getBooklist()
{
List<Book> bookList = new ArrayList<Book>();
try {
Connection con = DbUtil.getCon();
String sql = "select * from t_book";
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while(rs != null && rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
Date date = rs.getDate("date");
Book book = new Book(id,name,date);
System.out.println(id + name + date);
bookList.add(book);
}
///一定要记得关!!
DbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bookList;
}
/*
* 添加图书,用于addBook.jsp
* */
public static boolean addBook(Book book)
{
String sql=" insert into t_book(id,name,date) values(?,?,?)";
String check="select * from t_book where id=?";
boolean flag = false;
try {
///检查这个书是不是已经存在了
Connection con = DbUtil.getCon();
PreparedStatement ps = con.prepareStatement(check);
ps.setString(1,book.getId());
ResultSet qrs = ps.executeQuery();
if(qrs.next()) {
flag = false;
}
else {
///将UtilDate 转化为 SQlDate ,不然无法插入
java.sql.Date sqlDate = new java.sql.Date(book.getDate().getTime());
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1,book.getId());
pstmt.setString(2,book.getName());
pstmt.setDate(3, sqlDate);
pstmt.executeUpdate();
flag = true;;
}
///一定要记得关!!
DbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(flag) return true;
else return false;
}
/*
* 用于删除
* */
public static boolean deleteBook(int id) {
String sql = "delete from t_book where id=?";
String check="select * from t_book where id=?";
boolean flag = false;
try {
Connection con = DbUtil.getCon();
PreparedStatement ps = con.prepareStatement(check);
ps.setInt(1,id);
ResultSet qrs = ps.executeQuery();
if(qrs.next()) {
flag = true;
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1,id);
pstmt.executeUpdate();
}
///一定要记得关!!
DbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(flag) {
return true;
}
else return false;
}
}
UserDao
package com.hoppz.exam.Dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.hoppz.exam.Model.User;
import com.hoppz.exam.Util.DbUtil;
public class UserDao {
public boolean getUser(User user) throws Exception{
DbUtil db = new DbUtil();
Connection con = db.getCon();
User rsUser = null;
Boolean flag = false;
String sql = "select * from t_user where userName=? and password=?";
//重要,有点难背
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1,user.getUserName());
pstmt.setString(2,user.getPassWord());
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
return flag = true;
}
DbUtil.closeCon(con);
if(flag) {
return true;
}
else return false;
}
}
addBookServlet
package com.hoppz.exam.Servlet;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hoppz.exam.Dao.BookDao;
import com.hoppz.exam.Model.Book;
/**
* Servlet implementation class AddBookServlet
*/
@WebServlet("/AddBookServlet")
public class AddBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(233);///其他也有这个主要是用来我看跳转进来没有233
String id = request.getParameter("addBook_id");
String name = request.getParameter("addBook_name");
String stringDate = request.getParameter("addBook_date");
///String to Date
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
Date date = null;
try {
date = format.parse(stringDate);
}catch(ParseException e) {
e.printStackTrace();
}
Book book = new Book(id,name,date);
///
BookDao bookDao = new BookDao();
if( bookDao.addBook(book) ) {
response.sendRedirect("booklist.jsp");
}
else {
System.out.println("图书已存在");
response.sendRedirect("addBook.jsp");
}
}
}
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
</head>
<body>
<br/>
<div class ="columns">
<div class = "column is-4">
</div>
<div class = "column is-4">
<!-- -->
<form class = "box" action = "login" method = "post">
<div class = "field">
<label class = "label">UserName</label>
<div class = "control" >
<input class = "input" type = "text" name ="login_username">
</div>
</div>
<div class = "field">
<label class="label">PassWord</label>
<div class = "control">
<input class = "input" type = "password" name ="login_password">
</div>
</div>
<button class = "button is-primary">Login</button>
</form>
<!-- -->
</div>
<div class = "colunm is-4" >
</div>
</div>
</body>
</html>
BookList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>booklist</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
<%
String name = (String)session.getAttribute("currentName");
if( name == null ){
response.sendRedirect("login.jsp");
}
%>
<!-- 最好用page import -->
<%@ page import ="com.hoppz.exam.Dao.BookDao" %>
<%@ page import ="com.hoppz.exam.Model.Book"%>
<%@ page import ="java.util.List" %>
<%
List<Book> booklist = BookDao.getBooklist();
session.setAttribute("currentBook",booklist);
%>
<script>
function submitForm2(bookid){
//document.getElementById("test").innerHTML=bookname;
var url = 'deleteBook?id=' + bookid;
//window.location.href="DeleteServlet?sid="+sid;
location.href = url;
}
function check(bookid,bookname){
var flag = confirm("确定要删除<"+bookname+">吗?");
if(flag){
submitForm2(bookid);
}
}
</script>
</head>
<body>
<section class="hero is-primary">
<div class = "hero-body">
<p class = "title">欢迎 ${sessionScope.currentName}</p>
</div>
</section>
<div class="columns">
<div class="column is-4"></div>
<div class="column">
<table class="table is-striped is-fullwidth is-hoverable">
<thead>
<tr>
<td>id</td>
<td>name</td>
<td>publicTime</td>
<td>deleteOp</td>
</tr>
</thead>
<tbody>
<c:forEach items="${sessionScope.currentBook}" var = "bookItem" varStatus = "st">
<tr>
<td>${bookItem.id}</td>
<td>${bookItem.name}</td>
<td>${bookItem.date}</td>
<!-- 注意onclick里面的EL表达式要加' ' 才能转换为js的string类型 -->
<td><button class = "button" onclick="check(${bookItem.id} ,'${bookItem.name}')" >delete</button>
</tr>
</c:forEach>
</tbody>
</table>
<a href ="addBook.jsp">addBook</a>
<!-- <div id = "test">233</div> -->
</div>
<div class="column is-4"></div>
</div>
</body>
</html>
addBook.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
<title>Insert title here</title>
<%
String name = (String)session.getAttribute("currentName");
if( name == null ){
response.sendRedirect("login.jsp");
}
%>
<script>
var xmlHttpReq = null;
/* 用这种方式去访问servlet有问题
function postRequest(){
if(window.XMLHttpRequest){
xmlHttpReq = new XMLHttpRequest();
}else if(window.ActionXObject){
xmlHttpReq = new ActiveXOject("Microsft.XMLHTTP");
}
///获取
var id = document.getElementById("addBook_id").value;
var name = document.getElementById("addBook_name").value;
var date = document.getElementById("addBook_date").value;
document.getElementById("myDiv").innerHTML=id+name+date;
var url = "http://localhost:8081/ExamDemo/addbook"
xmlhttp.open("POST",url,true);
xmlhttp.send("id="+id+"&name="+name+"&date="+date);
}
*/
</script>
</head>
<body>
<section class="hero is-primary">
<div class = "hero-body">
<p class = "title">欢迎 ${sessionScope.currentName}</p>
</div>
</section>
<div class="columns">
<div class = "column is-4"></div>
<div class = "column is-4">
<form class = "form" method = "post" action = "addbook">
<div class = "field">
<label class = "label">BookId</label>
<input class="input" type = "text" name = "addBook_id" id = "addBook_id">
</div>
<div class = "field">
<label class = "label">BookName</label>
<input class="input" type = "text" name = "addBook_name" id = "addBook_name">
</div>
<div class = "field">
<label class = "label">PublicationDate</label>
<input class="input" type = "date" name = "addBook_date" id = "addBook_date" placeholder="select date">
</div>
<!-- 如果不写 type="button" 每次点button页面就会自动刷新一次 ,如果写了type = "button"那么就不能重form-action上提交数据到servlet -->
<button class = "button is-primary" >submit</button>
</form>
</div>
<div class = "column is-4" id ="myDiv">
</div>
</div>
</body>
</html>