使用JSP+Servlet+JavaBean构成的MVC模型,完成图书后台管理系统

任务描述:

一、语言和环境

 l  实现技术
    Java  Web技术
 l  环境要求及开发工具
    JDK1.7以上、Eclipse或IntelliJ IDEA、Tomcat 8.0以上

二、程序整体要求

 主要功能:

 1、注册登录功能
    l  注册:信息包括用户名、密码、密码确认、手机号码和邮箱,要使用正则表达式进行校验
    l  登录:注册成功直接跳转到登录页面,登录成功后显示用户名
    l  登录成功后进入管理页面。 
    l  使用过滤器限制不登录不能进入管理页面
2、图书分类管理
l  分类添加:分类id、名字、描述
3、图书管理
 l  图书添加:内容包括图书id、图书名、图书分类、价格、描述
 l  图书查询:列出所有图书完整信息,可以按id、图书名、分类进行查询,使用Ajax局部刷新,显示所有图书时要使用jstl

三、代码

登录界面 index.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+"/";  
	String username = (String)request.getAttribute("username");
	String flag = request.getParameter("flag");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>图书后台管理登录界面</title>
<script type="text/javascript" src="<%=basePath%>/resources/js/jquery-3.3.1.js"></script>
</head>
<script type="text/javascript">
var flag = '<%=flag %>';
if("1"==flag){
	alert("你尚未登陆,或者账号在异地登陆,请重新登陆!");
}
</script>
<body>
	<center>
		<h1>
			登录 | <a href="<%=basePath%>/pages/admin/regist.jsp">注册</a>
		</h1>
		<form action="<%=basePath%>/LoginServlet" method="post">
			<table width="350px" cellspacing="0px" cellpadding="0px" border="1px">
				<tr>
					<td>用户名</td>
					<td><input type="text" name="username" id="username"
						placeholder="用户名为3-12位字母数字或下划线组合"></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td><input type="password" name="password" id="password"
						placeholder="长度为6-12位的纯数字"></td>
				</tr>
				<tr>
					<td colspan="2" style="text-align: center"><input
						type="submit" value="登录"> <input type="reset" value="取消">
					</td>
				</tr>
			</table>
		</form>
	</center>
	<script type="text/javascript">
		$(function(){
			if("<%=username%>"!="null"){
				$("#username").val("<%=username%>");
			}
			if("${msg}"!=""){
				alert('${msg}');
			}
		})
	</script>
</body>
</html>

注册界面 regist.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;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="<%=basePath%>/resources/js/jquery-3.3.1.js"></script>
<title>注册界面</title>
</head>
<body>
	<center>
		<h1>用户注册</h1>
		<form action="" method="post">
			<table width="400px" cellspacing="0px" cellpadding="0px" border="1px">
				<tr>
					<td>用户名</td>
					<td><input type="text" name="username" id="username"
						placeholder="用户名为3-12位字母数字或下划线组合"></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td><input type="password" name="password"
						placeholder="密码长度为6-12位的纯数字" id="password"></td>
				</tr>
				<tr>
					<td>确认密码</td>
					<td><input type="password" name="checkPWD" id="checkPWD"
						placeholder="密码长度为6-12位的纯数字""></td>
				</tr>
				<tr>
					<td>手机号码</td>
					<td><input type="text" name="phone" id="phone" placeholder="请输入正确的手机号码格式"></td>
				</tr>
				<tr>
					<td>邮箱</td>
					<td><input type="email" name="email" id="email" placeholder="请输入正确邮箱格式"
						required="required"></td>
				</tr>
				<tr>
					<td colspan="2" style="text-align: center"><input
						type="submit" id="submit" value="注册"> <input type="reset" value="重置">
					</td>
				</tr>
			</table>
		</form>
	</center>
	<script type="text/javascript">
		$(function(){
			var flag = false;
			var flag1 = false;
			$("#checkPWD").blur(function(){
				var pwd = $("#password").val();
				if($(this).val()!=pwd){
					alert("两次输入的密码不一致");
					$(this).val("");
					flag = false;
				}else{
					flag = true;
				}
			})
			$("input[type='submit']").click(function(){
				var username = $("#username").val();
				var password = $("#password").val();
				var checkPWD = $("#checkPWD").val();
				var phone = $("#phone").val();
				var email = $("#email").val();
				var reg_name = /^[0-9a-zA-Z\w]{3,12}$/;
				var reg_name = /^[0-9a-zA-Z\w]{3,12}$/;
				var reg_pwd = /^\d{6,12}$/;
				var reg_phone = /^1[3456789]\d{9}$/;
				var reg_email = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
				if(reg_name.test(username)){
					if(reg_pwd.test(password)){
						if(reg_pwd.test(checkPWD)){
							if(reg_phone.test(phone)){
								if(reg_email.test(email)){
									flag1 = true;
								}
							}
						}
					}		
				}else{
					flag1 = false;
				} 
				if(flag&&flag1){
					alert("注册成功");
					$("form").attr("action","<%=basePath%>/RegistServlet");
				}else{
					alert("输入参数有误");
				}
			})
		
		})
	</script>
</body>
</html>

RegistServlet

package com.imooc.servlet;
/**
 * @author zhaojiahui
 * 注册Servlet
 */
import java.io.IOException;
import java.util.Enumeration;

import javax.management.loading.PrivateClassLoader;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;

import org.omg.CORBA.PRIVATE_MEMBER;


/**
 * Servlet implementation class RegistServlet
 */
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.print("注册成功");
		request.removeAttribute("username");
		String username = (String)request.getParameter("username");
		String password = (String)request.getParameter("password");
		String phone = (String)request.getParameter("phone");
		String email = (String)request.getParameter("email");
		User user = new User(username,password,phone,email);
		System.out.println(user);
		LibService libService = new LibServiceImpl();
		libService.regist(user);
		request.setAttribute("username", username);
		request.getRequestDispatcher("/index.jsp").forward(request,response);
	}
}

LoginServlet

package com.imooc.servlet;
/**
 * @author zhaojiahui
 * 注册Servlet
 */
import java.io.IOException;
import java.util.Enumeration;

import javax.management.loading.PrivateClassLoader;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;

import org.omg.CORBA.PRIVATE_MEMBER;


/**
 * Servlet implementation class RegistServlet
 */
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.print("注册成功");
		request.removeAttribute("username");
		String username = (String)request.getParameter("username");
		String password = (String)request.getParameter("password");
		String phone = (String)request.getParameter("phone");
		String email = (String)request.getParameter("email");
		User user = new User(username,password,phone,email);
		System.out.println(user);
		LibService libService = new LibServiceImpl();
		libService.regist(user);
		request.setAttribute("username", username);
		request.getRequestDispatcher("/index.jsp").forward(request,response);
	}
}

登录过滤器SessionFilter:

package com.imooc.servlet;

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;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class SessionFilter
 */
@WebFilter("/server.jsp")
public class SessionFilter implements Filter {
	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hrequest = (HttpServletRequest)request;
		HttpServletResponse hresponse = (HttpServletResponse)response;
		
		String loginUser = (String)hrequest.getSession().getAttribute("loginUser");//从session对象中获取登录用户名
		
		if(loginUser==null){//登录用户名不存在,用户未登录,强制重定向至登陆页面
			hresponse.sendRedirect(hrequest.getContextPath()+"/index.jsp?flag=1");
			return;
			
		}else{
			chain.doFilter(request, response);//已登录,转入相应的请求处理
			return;
		}
	}

	
	public void init(FilterConfig fConfig) throws ServletException {
		
	}

}

由场景和运行效果,可以分析出项目中可以抽取如下类和页面结构:

图书类Book:

package com.imooc.servlet;

import java.util.Map;

/**
 * @author zhaojiahui
 * @version 创建时间:2019年9月17日 下午4:19:12
 * @ClassName Book
 * @Description 能够描述图书ID、图书名、图书分类名、价格、描述等
 */
public class Book {
	private String bookID;// 图书ID
	private String name;// 图书名
	private String catgory;// 图书分类名
	private float price;// 价格
	private String remark;// 描述
	// 无参构造

	public Book() {

	}

	// 带参构造
	public Book(String bookID, String name, String catgory, float price, String remark) {
		super();
		this.bookID = bookID;
		this.name = name;
		this.catgory = catgory;
		this.price = price;
		this.remark = remark;
	}

	public String getBookID() {
		return bookID;
	}

	public void setBookID(String bookID) {
		this.bookID = bookID;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCatgory() {
		return catgory;
	}

	public void setCatgory(String catgory) {
		this.catgory = catgory;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	@Override
	public String toString() {
		return "Book [bookID=" + bookID + ", name=" + name + ", catgory=" + catgory + ", price=" + price + ", remark=" + remark
				+ "]";
	}

}

用户类User:

package com.imooc.servlet;

/**
 * @author zhaojiahui
 * @version 创建时间:2019年9月17日 下午4:14:29
 * @ClassName User
 * @Description 能够描述用户名、密码、手机号码和邮箱等
 */
public class User {
	private String username; // 用户名
	private String password; // 密码
	private String phone;// 手机号码
	private String email;// 邮箱

	// 构造方法
	public User() {

	}

	// 带参构造方法
	public User(String username, String password, String phone, String email) {
		super();
		this.username = username;
		this.password = password;
		this.phone = phone;
		this.email = email;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", phone=" + phone + ", email=" + email + "]";
	}

}

数据处理类LibDaoImpl:

package com.imooc.servlet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.tomcat.util.digester.ObjectCreateRule;

import com.sun.org.apache.bcel.internal.generic.NEW;

/**
* @author zhaojiahui
* @version 创建时间:2019年9月17日 下午4:23:28
* @ClassName LibDaoImpl
* @Description 能够描述用户表、图书分类和图书表等
*/
public class LibDaoImpl {
	//用户表
	private static final List<User> userDb = new ArrayList<User>();
	//图书分类
	private static final List<Map<String, Object>> categorys = new ArrayList<>();
	//图书表
	private static final List<Book> books = new ArrayList<>();
	public LibDaoImpl() {
		
	}
	//用户注册:
	public void regist(User user) {
		userDb.add(user);
		System.out.println(userDb);
	}
	
	// 用户登录: 
	public int login(String username, String password) {
		//1代表登录成功  0 代表登录失败
		System.out.println(isUserExist(username));
			for(User user:userDb) {
				if(user.getUsername().equals(username)&&user.getPassword().equals(password)) {
					return 1;
				}
			}
		return 0;
	}
	
	//判断指定的用户名在存储用户信息的集合中是否存在: 
	public int isUserExist(String username) {
		//1代表存在 0代表不存在
		for(User user:userDb) {
			if(user.getUsername().equals(username)) {
				return 1;
			}else {
				return 0;
			}
		}
		return 0;
	}
	
	//添加图书分类:
	public void addBookCatgory(Long id, String catgoryName, String description) {
		Map<String, Object> catgory = new HashMap<>();
		catgory.put("id", id);
		catgory.put("catgoryName", catgoryName);
		catgory.put("description", description);
		categorys.add(catgory);
		System.out.println(categorys);
	}
	
	//获取所有图书分类: 
	public List<Map<String, Object>> getAllBookCatgory(){
		return categorys;
	}
	
	// 添加图书:
	public void addBook(Book book){
		books.add(book);
		System.out.println(books);
	}
	
	//获取所有图书:
	public List<Book> getBook(){
		return books;
	}
	
	//根据条件来查询书籍信息:
	public List<Book> getBooksByCondition(String bookID, String bookName, String catgoryName) {
		System.out.println(bookID+bookName+catgoryName);
		List<Book> book = new ArrayList<>();
		for(Book b:books) {
			if(b.getBookID().equals(bookID)||b.getName().equals(bookName)||b.getCatgory().equals(catgoryName)) {
				book.add(b);
				System.out.println(b);
				break;
			}
		}
		return book;
	}
}

业务类接口LibService:

package com.imooc.servlet;

import java.util.List;
import java.util.Map;

/**
* @author zhaojiahui
* @version 创建时间:2019年9月18日 下午2:54:41
* @ClassName LibService 
* @Description LibDaoImpl类的对象,用于对该类中的方法进行调用
*/
public interface LibService {
	public void regist(User user);
	public int login(String username, String password);
	public int isUserExist(String username);
	public void addBookCatgory(Long id, String catgoryName, String description);
	public List<Map<String, Object>> getAllBookCatgory();
	public void addBook(Book book);
	public List<Book> getBooksByCondition(String bookID, String bookName, String catgoryName);
	public List<Book> getBook();
}

业务类实现 LibServiceImpl:

package com.imooc.servlet;

import java.util.List;
import java.util.Map;

/**
* @author zhaojiahui
* @version 创建时间:2019年9月17日 下午4:35:25
* @ClassName LibServiceImpl
* @Description LibDaoImpl类的对象,用于对该类中的方法进行调用
* @method 此类中的方法形式与LibDaoImpl类一致,用于对LibDaoImpl中对应方法的调用
*/
public class LibServiceImpl implements LibService{
	LibDaoImpl libDao = new LibDaoImpl();

	@Override
	public void regist(User user) {
		libDao.regist(user);
	}

	@Override
	public int login(String username, String password) {
		return libDao.login(username, password);
	}

	@Override
	public int isUserExist(String username) {
		return libDao.isUserExist(username);
	}

	@Override
	public void addBookCatgory(Long id, String catgoryName, String description) {
		libDao.addBookCatgory(id,catgoryName,description);
	}

	@Override
	public List<Map<String, Object>> getAllBookCatgory() {
		return libDao.getAllBookCatgory();
	}

	@Override
	public void addBook(Book book) {
		libDao.addBook(book);
	}

	@Override
	public List<Book> getBooksByCondition(String bookID, String bookName, String catgoryName) {
		return libDao.getBooksByCondition(bookID, bookName, catgoryName);
	}

	@Override
	public List<Book> getBook() {
		return libDao.getBook();
	}
	
}

后台主页server.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String basePath = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>图书后台管理系统</title>
</head>
<!-- frameset框架要放在<body>-->
<frameset rows="20%,*">
	<frame src="${pageContext.request.contextPath }/server/top"></frame>
	<frameset cols="10%,*">
		<frame src="${pageContext.request.contextPath }/server/left"></frame>
		<frame name="main"></frame>
	</frameset>
</frameset>
<body>

</body>
</html>

left.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+"/";  
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>图书后台管理</title>
</head>
<body>
	<p>
		<a href="<%=basePath%>/pages/admin/catgory.jsp" target="main">分类添加</a>
	</p>
	<p>
		<a href="<%=basePath%>/ToAddBookServlet" target="main">图书添加</a>
	</p>
	<p>
		<a href="<%=basePath%>/SelectBookServlet" target="main">图书查询</a>
	</p>
</body>
</html>

top.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String user = (String)request.getSession().getAttribute("loginUser");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<center>
		<h1>
			图书后台管理系统<span style="font-size:12px">您好,<%=user %></span>
		</h1>
	</center>
</body>
</html>

图书分类 catgory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String user = (String)request.getSession().getAttribute("loginUser");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<center>
		<h1>
			图书后台管理系统<span style="font-size:12px">您好,<%=user %></span>
		</h1>
	</center>
</body>
</html>

CatgoryServlet:

package com.imooc.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CatgoryServlet
 */
@WebServlet("/CatgoryServlet")
public class CatgoryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
  
    public CatgoryServlet() {
        super(); 
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		Long id = (long) Integer.parseInt(request.getParameter("id"));
		String catgoryName = request.getParameter("catgoryName");
		String description = request.getParameter("description");
		LibService libService  = new LibServiceImpl();
		libService.addBookCatgory(id, catgoryName, description);
		System.out.println("图书分类添加成功");
	}

}

ToAddBookServlet:

package com.imooc.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

/**
 * Servlet implementation class ToAddBookServlet
 */
@WebServlet("/ToAddBookServlet")
public class ToAddBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ToAddBookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		LibService libService = new LibServiceImpl();
		List<Map<String, Object>> bookCatgory = libService.getAllBookCatgory();
		List<Object> catgoryList = new ArrayList<>();
		for(Map<String, Object>catgory:bookCatgory) {
			catgoryList.add(catgory.get("catgoryName"));
		}
		request.setAttribute("bookCatgory", catgoryList);
		request.getRequestDispatcher("/addBook.jsp").forward(request, response);
	}

}

添加图书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"%>
<%
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>图书添加</title>
</head>
<body>
<center>
		<h1>图书添加</h1>
		<form action="<%=basePath%>/AddBookServlet" method="post">
			<table width="400px" cellspacing="0px" cellpadding="0px" border="1px">
				<tr>
					<td>图书ID</td>
					<td><input type="text" name="id" id ="id" placeholder="请输入数字" pattern="\d+" required="required"></td>
				</tr>
				<tr>
					<td>图书名</td>
					<td><input type="text" name="bookName" id="bookName"></td>
				</tr>
				<tr>
					<td>图书分类</td>
					<td>
						<select name="catgoryName" id="catgoryName">	
						<c:forEach items="${bookCatgory}" var="catgory">
							<option value="${catgory}">${catgory}</option>
						</c:forEach>					
						</select>
					</td>
				</tr>
				<tr>
					<td>价格</td>
					<td><input type="text" name="price" id="price" placeholder="请输入价格" ></td>
				</tr>
				<tr>
					<td>描述</td>
					<td><input type="text" name="description" id="description" placeholder="请输入描述信息"></td>
				</tr>
				<tr>
					<td colspan="2" style="text-align:center">
						<input type="submit" value="添加">
						<input type="reset" value="重置">
					</td>
				</tr>
			</table>
		</form>
	</center>
</body>
</html>

AddBookServlet:

package com.imooc.servlet;

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

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.alibaba.fastjson.JSON;

/**
 * Servlet implementation class AddBookServlet
 */
@WebServlet("/AddBookServlet")
public class AddBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    public AddBookServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String bookID = request.getParameter("id");
		String bookName = request.getParameter("bookName");
		String catgoryName = request.getParameter("catgoryName");
		Float price = (float)Integer.parseInt(request.getParameter("price"));
		String description = request.getParameter("description");
		Book book = new Book(bookID,bookName,catgoryName,price,description);
		LibService libService = new LibServiceImpl();
		libService.addBook(book);
		System.out.println("添加图书成功");
		List<Book> bookList = libService.getBook();
		request.getSession().setAttribute("bookList", bookList);
		request.getRequestDispatcher("/showBooks.jsp").forward(request, response);
	}

}

图书查询showBooks.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="java.util.*,com.imooc.servlet.Book"%>
<%
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;  
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>图书查询</title>
<script type="text/javascript" src="<%=basePath%>/resources/js/jquery-3.3.1.js"></script>
</head>
<body>
<center>
		<h1>图书查询</h1>
		<p>
			图书ID:<input type="text" name="bookID">
			图书名:<input type="text" name="bookName">
			分类:<input type="text" name="catgoryName">
			<input type="submit" value="查询" id="search">
		</p>
		<hr>
		<table width="800px" cellspacing="0px" cellpadding="0px" border="1px">
			<thead>
				<tr>
					<th>图书ID</th>
					<th>书名</th>
					<th>分类</th>
					<th>价格</th>
					<th>描述</th>
				</tr>
			</thead>
			<tbody id="cont">
			<c:forEach items="${bookList }" var="book">
				<tr>
						<td>${book.bookID }</td>
						<td>${book.name }</td>
						<td>${book.catgory }</td>
						<td>${book.price }</td>
						<td>${book.remark }</td>
				</tr>
			</c:forEach>			
					
			</tbody>
		</table>
	</center>
<script type="text/javascript">
	$(function(){
		$("#search").click(function(){
			$.ajax({
		        "url":"<%=basePath%>/SelectBookServlet",
								"data" : {
									bookID : $("input[name=bookID]").val(),
									bookName : $("input[name=bookName]").val(),
									catgoryName : $("input[name=catgoryName]").val()
								},
								"type" : "post",
								"dataType" : "json",
								"success" : function(json) {
									var content = "";
									for (var i = 0; i < json.length; i++) {
										content = content + "" + json[i].bookID
												+ "" + json[i].name
												+ "" + json[i].catgory
												+ "" + json[i].price
												+ ""+ json[i].remark
												+ "";
										 $("#cont>tr").remove();
									}
									$("#cont").html(content);//设置cont也就是中的内容
								}
							});
						});
	})
</script>	
</body>
</html>

SelectBookServlet:

package com.imooc.servlet;

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

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.alibaba.fastjson.JSON;

/**
 * Servlet implementation class SelectBookServlet
 */
@WebServlet("/SelectBookServlet")
public class SelectBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SelectBookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String bookID = request.getParameter("bookID");
		String bookName = request.getParameter("bookName");
		String catgoryName = request.getParameter("catgoryName");
		LibService libService = new LibServiceImpl();
		List<Book> list = libService.getBooksByCondition(bookID, bookName, catgoryName);
		String json = JSON.toJSONString(list);
		System.out.println(json);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println(json);
//		request.getRequestDispatcher("/showBooks.jsp").forward(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

PS:left.jsp top.jsp要在web.xml中进行servlet配置

你可能感兴趣的:(使用JSP+Servlet+JavaBean构成的MVC模型,完成图书后台管理系统)