参考资料:https://blog.csdn.net/qq_23994787/article/details/73612870
http://how2j.cn/
实习第一周,写下一些在建立web项目中的操作步骤和个人心得供自己以后可参考,大量参考了如上链接的资料,十分感谢。有一些东西被我省略了但不影响大体项目的完成,如有错误或不当欢迎指出
在数据库名为:how2java中创建表格books
books中包含的信息有:id(每本书的唯一编号)、num(图书编号)、bookname(书名)、publish(出版社名)、author(作者)、status(状态:出借/在库)
auto_increment:会自动生成id号,且是按顺序往下生成(如中间删除了某条数据,再添加,id号不会覆盖原本被删除的号,而是会继续创建新的id号)
default charset=utf-8:解决中文编码问题,如没有这句,则下面添加数据中添加中文就会出错
create table books(
id int(11) AUTO_INCREMENT,
num varchar(50) not null,
bookname varchar(100) not null,
publish varchar(100) not null,
author varchar(50) not null,
status varchar(30) not null,
primary key(id)
)DEFAULT CHARSET=utf8;
select * from books
insert into books values(null,'I202','Java入门到精通','人民教育出版社','张一','在库');
insert into books values(null,'I202','Java入门到精通','人民教育出版社','张一','在库');
insert into books values(null,'I203','HTML解读','清华出版社','李四','在库');
insert into books values(null,'I203','HTML解读','清华出版社','李四','出借');
insert into books values(null,'I203','HTML解读','清华出版社','李四','在库');
insert into books values(null,'P106','毛概精选','政府出版社','毛泽东','在库');
insert into books values(null,'P106','毛概精选','政府出版社','毛泽东','出借');
insert into books values(null,'M109','莫言小说集','上海出版社','莫言','在库');
insert into books values(null,'M109','莫言小说集','上海出版社','莫言','在库');
insert into books values(null,'M109','莫言小说集','上海出版社','莫言','出借');
insert into books values(null,'I123','C语言教程','北大教育出版社','陈三','在库');
insert into books values(null,'I123','C语言教程','北大教育出版社','陈三','在库');
insert into books values(null,'I123','C语言教程','北大教育出版社','陈三','出借');
insert into books values(null,'C106','契科夫小说选','交大出版社','契科夫','出借');
insert into books values(null,'S200','21天学会JSP','火车出版社','宋八','在库');
insert into books values(null,'S200','21天学会JSP','火车出版社','宋八','出借');
insert into books values(null,'S200','21天学会JSP','火车出版社','宋八','出借');
insert into books values(null,'S200','21天学会JSP','火车出版社','宋八','在库');
insert into books values(null,'K170','孙子兵法','上海出版社','孙子','在库');
insert into books values(null,'K170','孙子兵法','上海出版社','孙子','出借');
DAO:存放有关数据层的包
enity:存放实体类
filter:文件流的包,用来解决中文编码问题等
servlet:存放servlet文件
util:其他类包
用该文件作为一个过滤器,对整体项目的中文编码问题进行过滤
package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter{
public EncodingFilter(){
System.out.println("过滤器构造");
}
public void destroy(){
System.out.println("过滤器销毁");
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException{
System.out.println("过滤器初始化");
}
}
url中的地址和数据库名依据自身不同来修改
package util;
import java.sql.*;
public class DBconn {
static String url="jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=utf8";
static String username="root";
static String pwd="admin";
static Connection conn=null;
static ResultSet rs=null;
static PreparedStatement ps=null;
public static void init(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,username,pwd);
}catch(Exception e){
System.out.println("init 数据库驱动初始化失败!");
e.printStackTrace();
}
}
public static int addUpdDel(String sql){
int i=0;
try{
PreparedStatement ps=conn.prepareStatement(sql);
i=ps.executeUpdate();
}catch(SQLException e){
System.out.println("数据库增删改异常!");
e.printStackTrace();
}
return i;
}
public static ResultSet selectsql(String sql){
try{
ps=conn.prepareStatement(sql);
rs=ps.executeQuery(sql);
}catch(SQLException e){
System.out.println("数据库查询异常!");
e.printStackTrace();
}
return rs;
}
public static void closeConn(){
try{
conn.close();
}catch(SQLException e){
System.out.println("数据库关闭异常!");
e.printStackTrace();
}
}
}
这里介绍一个存取方法的快捷操作方式:在敲好属性之后,按下快捷键shift+alt+s后,找到一个Generate Getters and Setters即可快速创建
package enity;
import javax.swing.text.StyledEditorKit.ForegroundAction;
public class Books {
private int id;
private String num;
private String bookname;
private String publish;
private String author;
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public String getPublish() {
return publish;
}
public void setPublish(String publish) {
this.publish = publish;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
在建立完以上的东西之后,创建一个关于图书管理的方法接口,名字为BooksDao
其中调用了enity类包下的实体类Books
register(Books book):新建图书,引入参数类型为Books,参数名book
delete(int id):删除图书,引入参数类型int,参数名id,根据id来删除图书
update(int id,String num,String bookname...):更新图书,引入参数类型如下,根据id来更新图书
getBooksAll():查询所有图书信息,返回类型为Books的列表数组
getBooksSome(String num):查询一部分图书信息(图书在一样的情况下,编号也一样),因此根据num来查询
list():用来返回List
list(int start,int count):start表示从哪个数据开始,count表示哪个数据作为结束,用来做分页查询使用
getTotal():用来返回数据总数
package DAO;
import java.util.List;
import enity.Books;
public interface BooksDao {
public boolean register(Books book); //新建图书
public boolean delete(int id); //删除图书
public boolean update(int id,String num,String bookname,String publish,String author,String status); //更新图书
public List getBooksAll(); //查询所有图书信息
public List getBooksSome(String num); //查询一部分图书信息
public List list();
public List list(int start,int count);
public int getTotal();
}
创建了接口,就应该在接口下写各方法的具体实现了,取名为BooksDaoImpl
其中需要注意的是,如数据类型为int,则在写SQL代码的时候,如:("select * from xx where id="+id)
若为String类型,则为:("select * from xx where num=' "+num+" ' " ) 中间的空格仅为看清楚使用,实际情况不需要空格,但需要注意为以上格式。
package DAO;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import enity.Books;
import util.DBconn;
public class BooksDaoImpl implements BooksDao{
public boolean register(Books book){ //新建图书
boolean flag=false;
DBconn.init();
int i=DBconn.addUpdDel("insert into book"
+ "s(num,bookname,publish,author,status)"+"values('"+book.getNum()+"','"+book.getBookname()+"','"+book.getPublish()+"','"+book.getAuthor()+"','"+book.getStatus()+"')");
if(i>0){
flag=true;
}
DBconn.closeConn();
return flag;
}
public boolean delete(int id){ //根据id删除图书
boolean flag=false;
DBconn.init();
String sql="delete from books where id="+id;
int i=DBconn.addUpdDel(sql);
if(i>0){
flag=true;
}
DBconn.closeConn();
return flag;
}
public boolean update(int id,String num,String bookname,String publish,String author,String status){ //更新图书
boolean flag=false;
DBconn.init();
String sql="update books set num='"+num+"',bookname='"+bookname+"',publish='"+publish+"',author='"+author+"',status='"+status+"' where id="+id;
int i=DBconn.addUpdDel(sql);
if(i>0){
flag=true;
}
DBconn.closeConn();
return flag;
}
public List getBooksAll(){ //显示所有图书信息
List list=new ArrayList();
try{
DBconn.init();
ResultSet rs=DBconn.selectsql("select * from books");
while(rs.next()){
Books book=new Books();
book.setId(rs.getInt("id"));
book.setNum(rs.getString("num"));
book.setBookname(rs.getString("bookname"));
book.setPublish(rs.getString("publish"));
book.setAuthor(rs.getString("author"));
book.setStatus(rs.getString("status"));
list.add(book);
}
DBconn.closeConn();
return list;
}catch(SQLException e){
e.printStackTrace();
}
return null;
}
public List getBooksSome(String num){
List list=new ArrayList();
try{
DBconn.init();
ResultSet rs=DBconn.selectsql("select * from books where num='"+num+"'");
while(rs.next()){
Books book=new Books();
book.setId(rs.getInt("id"));
book.setNum(rs.getString("num"));
book.setBookname(rs.getString("bookname"));
book.setPublish(rs.getString("publish"));
book.setAuthor(rs.getString("author"));
book.setStatus(rs.getString("status"));
list.add(book);
}
DBconn.closeConn();
return list;
}catch(SQLException e){
e.printStackTrace();
}
return null;
}
public List list(){
return list(0,Short.MAX_VALUE);
}
public List list(int start,int count){
List books=new ArrayList();
try{
DBconn.init();
//String sql="select * from books order by id desc limit ?,?";
ResultSet rs=DBconn.selectsql("select * from books order by id asc limit "+start+","+count);
while(rs.next()){
Books book=new Books();
book.setId(rs.getInt("id"));
book.setNum(rs.getString("num"));
book.setBookname(rs.getString("bookname"));
book.setPublish(rs.getString("publish"));
book.setAuthor(rs.getString("author"));
book.setStatus(rs.getString("status"));
books.add(book);
}
DBconn.closeConn();
return books;
}catch(SQLException e){
e.printStackTrace();
}
return null;
}
public int getTotal(){
int total=0;
try{
DBconn.init();
ResultSet rs=DBconn.selectsql("select count(*) from books");
while(rs.next()){
total=rs.getInt(1);
}
DBconn.closeConn();
}catch(SQLException e){
e.printStackTrace();
}
return total;
}
}
由以上的接口以及我们想要的功能来看,分别创建了以下的servlet文件来进行交互:
1、BookesAllSearchServlet.java:查询所有图书信息
2、BooksBianjiServlet.java:进入编辑模式
3、BooksDeleteServlet.java:删除图书
4、BooksRegisterServlet.java:新建图书
5、BooksSomeSearchServlet.java:查询部分图书信息
6、BooksUpdateServlet.java:更新图书信息
注:doGet和doPost可以用service代替,会自动识别是用Get还是Post方法
BookesAllSearchServlet
package 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 DAO.BooksDaoImpl;
import DAO.BooksDao;
import enity.Books;
public class BookesAllSearchServlet 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{
int start=0;
int count=5;
try{
start=Integer.parseInt(request.getParameter("start"));
}catch(NumberFormatException e){
}
int next=start+count;
int pre=start-count;
int total=new BooksDaoImpl().getTotal();
int last;
if(0==total%count)
last=total-count;
else
last=total-total%count;
pre=pre<0 ? 0:pre;
next=next>last ? last :next;
request.setAttribute("pre", pre);
request.setAttribute("next", next);
request.setAttribute("last", last);
List bookAll=new BooksDaoImpl().list(start, count);
request.setAttribute("bookAll", bookAll);
request.getRequestDispatcher("/BooksAllShow.jsp").forward(request, response);
}
}
解读:
BooksBianjiServlet
package 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 DAO.BooksDaoImpl;
import DAO.BooksDao;
import enity.Books;
public class BooksBianjiServlet 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{
int start=0;
int count=5;
try{
start=Integer.parseInt(request.getParameter("start"));
}catch(NumberFormatException e){
}
int next=start+count;
int pre=start-count;
int total=new BooksDaoImpl().getTotal();
int last;
if(0==total%count)
last=total-count;
else
last=total-total%count;
pre=pre<0 ? 0:pre;
next=next>last ? last :next;
request.setAttribute("pre", pre);
request.setAttribute("next", next);
request.setAttribute("last", last);
List bookAll=new BooksDaoImpl().list(start, count);
request.setAttribute("bookAll", bookAll);
request.getRequestDispatcher("/BooksUpdate.jsp").forward(request, response);
}
}
解读:这一页的区别在于跳转的页面不同,这一步是跳转到编辑模式的页面
BooksDeleteServlet
package 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 DAO.BooksDao;
import DAO.BooksDaoImpl;
public class BooksDeleteServlet 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{
String id=request.getParameter("id");
int bookId=Integer.parseInt(id);
BooksDao bd=new BooksDaoImpl();
if(bd.delete(bookId)){
request.setAttribute("xiaoxi","删除成功");
request.getRequestDispatcher("/BookesAllSearchServlet").forward(request, response);
}else{
response.sendRedirect("fail.html");
}
}
}
解读:response.sendRedirect("fail.html"):也是一个跳转作用,是重新定向,前后页面不是一个request
而request.getRequestDispatcher是请求转发,前后页面共享一个request
BooksRegisterServlet
package 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 DAO.BooksDao;
import DAO.BooksDaoImpl;
import enity.Books;
public class BooksRegisterServlet 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{
if("".equals(request.getParameter("num")) || "".equals(request.getParameter("bookname")) ||"".equals(request.getParameter("publish")) ||"".equals(request.getParameter("author")) ||"".equals(request.getParameter("status"))){
request.getRequestDispatcher("/fail.html").forward(request, response);
}else{
String num=request.getParameter("num");
String bookname=request.getParameter("bookname");
String publish=request.getParameter("publish");
String author=request.getParameter("author");
String status=request.getParameter("status");
Books book=new Books();
book.setNum(num);
book.setBookname(bookname);
book.setPublish(publish);
book.setAuthor(author);
book.setStatus(status);
BooksDao bd=new BooksDaoImpl();
if(bd.register(book)){
request.getRequestDispatcher("/BookesAllSearchServlet").forward(request, response);
}
else
{
request.getRequestDispatcher("/login.html").forward(request, response);
}
}
}
}
解读:
BooksSomeSearchServlet
package 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 DAO.BooksDaoImpl;
import DAO.BooksDao;
import enity.Books;
public class BooksSomeSearchServlet 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{
BooksDao bd=new BooksDaoImpl();
String num=request.getParameter("num");
List bookSome=bd.getBooksSome(num);
request.setAttribute("bookSome", bookSome);
request.getRequestDispatcher("/BooksSomeShow.jsp").forward(request, response);
}
}
BooksUpdateServlet
package 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 org.w3c.dom.Document;
import DAO.BooksDao;
import DAO.BooksDaoImpl;
import enity.Books;
public class BooksUpdateServlet 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{
String id=request.getParameter("id");
int bookId=Integer.parseInt(id);
String num=request.getParameter("num");
String bookname=request.getParameter("bookname");
String publish=request.getParameter("publish");
String author=request.getParameter("author");
String status=request.getParameter("status");
BooksDao bd=new BooksDaoImpl();
if(bd.update(bookId,num,bookname,publish,author,status)){
request.setAttribute("xiaoxi", "更新成功");
request.getRequestDispatcher("/BookesAllSearchServlet").forward(request, response);
}else{
response.sendRedirect("fail.html");
}
}
}
创建完servlet文件之后,便需要给他们增加映射表以来让前端找得到这些servlet文件,以此来建立连接
EncodingFilter
filter.EncodingFilter
EncodingFilter
/*
BookesAllSearchServlet
servlet.BookesAllSearchServlet
BooksRegisterServlet
servlet.BooksRegisterServlet
BooksSomeSearchServlet
servlet.BooksSomeSearchServlet
BooksDeleteServlet
servlet.BooksDeleteServlet
BooksUpdateServlet
servlet.BooksUpdateServlet
BooksBianjiServlet
servlet.BooksBianjiServlet
BookesAllSearchServlet
/BookesAllSearchServlet
BooksRegisterServlet
/BooksRegisterServlet
BooksSomeSearchServlet
/BooksSomeSearchServlet
BooksDeleteServlet
/BooksDeleteServlet
BooksUpdateServlet
/BooksUpdateServlet
BooksBianjiServlet
/BooksBianjiServlet
解读:
前端代码有用html和jsp书写的页面,如下:
1、BooksAllShow.jsp:显示所有图书的界面
2、BooksManager.jsp:图书管理主界面
3、BooksRegister.jsp:新建图书界面
4、BooksSomeShow.jsp:显示一部分图书界面
5、BooksUpdate.jsp:更新图书界面
6、fail.html:失败操作界面
BooksAllShow.jsp
解读已放在代码注释中
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
图书页面
${xiaoxi}
BooksManager.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
登录页面
${xiaoxi}
BooksRegister.jsp
注:form最好写在table外层
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
编辑页面
BooksSomeShow.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
图书页面
${xiaoxi}
ID
图书编号
书名
出版社
作者
状态
删除
编辑
BooksUpdate.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
登录页面
ID
图书编号
书名
出版社
作者
状态
确定
[首 页]
[上一页]
[下一页]
[末 页]
fail.html
登录页面
录入数据不能为空!请重试!
点击返回用户登录界面
点击返回新建图书界面
点击返回注册用户界面
注:其中的login.html和zhuce.html是我再做了一个用户登录的界面连接到这边来,原理一样
首先是用户登录界面(详细代码和过程就没有贴出来了,与图书管理的建立过程是一样的)
登录进去之后:
点击查看所有图书之后:
点击编辑之后会进入编辑模式: