javaee实验:使用mvc模式 设计一个图书管理系统
太多了把报告粘贴过来了,仅供参考
实习三 EL、JSTL及MVC
一、实习要求与目的
1.掌握标签库的使用
2.掌握EL及JSTL常用标签及方法
3.掌握MVC的编程模式,完成一个完整的信息管理系统
二、实习内容
使用EL、JSTL及MVC完成一个图书管理系统,要求完成图书信息的添加、修改、删除、查询与显示;并添加用户管理功能,只有登录用户才能完成图书的管理操作。
三、扩展
试着使用过滤器作为控制器完成实习内容。
四、实验代码
代码在最下面
工程结构如下图:
这个实验的工程结构中Model是cn.cie.dao和entity包中的dao层和实体类,Controller是一个过滤器和一个Servlet,其中Servlet主要是用作一个中间的统一控制,里面没有代码逻辑,代码逻辑主要都是通过过滤器实现,然后View就是几个jsp页面了。主要思路都比较清晰,其中有些细节需要注意,比如增加记录时id的自动设置等。
六、实验结果
1.登录控制
用户表中有一个用户
还未登录时直接访问/ctrl都会跳转到登录界面要求登录
登录成功后:
和数据库book表中的数据对应的上:
添加数据:
数据表中显示增加一条记录,id顺延:
修改图书信息:
把价格改为99
删除图书:
在图书对应的选项里点击删除选项即可删除图书信息:
数据表中的记录显示已经被删除
代码太多了,又不能直接发文件。。下面只粘控制器和dao层
工程放在仓库了:https://gitee.com/majun_real/mvc-library-management-system/tree/master
提示:所谓的id自动增长可以通过创建表定义列时设置,而本文是写了一个函数来获取最大id(原因是我写这个作业的时候不知道可以在数据表上设置自动增长。。。大家写的时候在只要对数据表的id字段设置自动增长就好了。。)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>shiyan3</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.11.v20150529</version>
<configuration>
<webAppConfig>
<contextPath>/</contextPath>
</webAppConfig>
<httpConnector>
<port>80</port>
</httpConnector>
</configuration>
</plugin>
</plugins>
</build>
</project>
MyCtrlFilter.java
package cn.cie.controlles;
import cn.cie.dao.BookDao;
import cn.cie.dao.UserDao;
import cn.cie.entity.Book;
import cn.cie.entity.User;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebFilter(filterName = "MyCtrlFilter",urlPatterns ={"/ctrl"})
public class MyCtrlFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request1=(HttpServletRequest) request;
HttpServletResponse response1=(HttpServletResponse) response;
String user = request.getParameter("user");
String password = request.getParameter("password");
String sessionuser=(String) request1.getSession().getAttribute("user");
UserDao userDao=new UserDao();
if(user==null)
{
if(sessionuser==null)//之前没有登录过
{
request1.getSession().setAttribute("err","还未登陆,请登陆");
response1.sendRedirect("login.jsp");
return;
}
}
else //从login.jsp访问
{
//是否勾选记住密码,写cookie
String memory=request.getParameter("memory");
if(memory!=null)
{
Cookie c1=new Cookie("user",user);
Cookie c2=new Cookie("password",password);
response1.addCookie(c1);
response1.addCookie(c2);
}
//判断用户名和密码
boolean flag=false;
try {
List<User> users=userDao.listuser();
for (User u:users
) {
if (u.getUser().equals(user)){
if(u.getPassword().equals(password)){ //用户名和密码都正确
flag=true;
request1.getSession().setAttribute("user",user);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
request1.setAttribute("errMsg",e.getMessage());
request1.getRequestDispatcher("error.jsp").forward(request1,response1);
}
if(flag==false)
{
request1.getSession().setAttribute("err","用户名或密码错误");
response1.sendRedirect("login.jsp");
return;
}
}
String act = request1.getParameter("act");
BookDao bookDaodao = new BookDao();
try{
if("list".equals(act)){
List<Book> books = bookDaodao.list();
request1.setAttribute("books",books);
request1.getRequestDispatcher("list.jsp").forward(request1,response1);
}
else if("add".equals(act)) {
request1.getRequestDispatcher("edit.jsp").forward(request1,response1);
}
else if("edit".equals(act)) {
String ids = request1.getParameter("id");
Integer id = Integer.parseInt(ids);
Book book = bookDaodao.getById(id);
request1.setAttribute("book",book);
request1.getRequestDispatcher("edit.jsp").forward(request1,response1);
}
else if("save".equals(act)) {
String tuh = request1.getParameter("tuh");
String name = request1.getParameter("name");
String className = request1.getParameter("book_type");
String scorces = request1.getParameter("price");
Float sc = Float.parseFloat(scorces);
Book book = new Book();
String id = request1.getParameter("id");
if(id != null && !"".equals(id)){//id非空是对已存在记录编辑的情况
Integer ids = Integer.parseInt(id);
book.setId(ids);
}
book.settuh(tuh);
book.setName(name);
book.setbook_type(className);
book.setprice(sc);
bookDaodao.insertOrUpdate(book);
response1.sendRedirect("ctrl?act=list");
}
else if("delete".equals(act)) {
String ids = request1.getParameter("id");
Integer id = Integer.parseInt(ids);
bookDaodao.deleteById(id);
response1.sendRedirect("ctrl?act=list");
}
else {
throw new Exception("非法请求!!");
}
}
catch (Exception e){
e.printStackTrace();
request1.setAttribute("errMsg",e.getMessage());
request1.getRequestDispatcher("error.jsp").forward(request1,response1);
}
//chain.doFilter(request1, response1);
}
}
Servlet.java
没啥东西,就是借他的路径中转一下
package cn.cie.controlles;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "Servlet", value = "/ctrl")
public class Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
BaseDao.java
package cn.cie.dao;
import java.sql.*;
public class BaseDao {
static String driverName = "com.mysql.jdbc.Driver";
static String url = "jdbc:mysql://localhost/mvc?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
static String userName = "root";
static String passwd = "";
static Connection con = null;
void getCon() throws ClassNotFoundException, SQLException {//ok
Class.forName(driverName);
if(con == null || con.isClosed()){
con = DriverManager.getConnection(url,userName,passwd);
}
}
protected ResultSet select(String sql) throws SQLException, ClassNotFoundException {//ok
getCon();
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery(sql);
return rs;
}
protected ResultSet select(String sql, Object[] params) throws SQLException, ClassNotFoundException {//ok
getCon();
PreparedStatement pstat = con.prepareStatement(sql);
for(int i = 1; i <= params.length; i++){
pstat.setObject(i,params[i - 1]);
}
ResultSet rs = pstat.executeQuery();
return rs;
}
protected int save(String sql,Object[] params) throws SQLException, ClassNotFoundException {//ok
getCon();
PreparedStatement pstat = con.prepareStatement(sql);
for(int i = 1; i <= params.length; i++){
pstat.setObject(i,params[i - 1]);
}
int rs = pstat.executeUpdate();
pstat.close();
return rs;
}
protected int getNewid()throws SQLException, ClassNotFoundException //zijixiede
{
getCon();
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery("select max(id) id from book ");
if(!rs.next()) return 1;//当前表中没有数据
return rs.getInt(1)+1;//取第一列的数据,即最大的id
}
void closeCon(){//ok
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
BookDao.java
package cn.cie.dao;
import cn.cie.entity.Book;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BookDao extends BaseDao {
static String SELECT = "select * from book";
static String SELECTBYID = "select * from book where id=?";
static String INSERT = "insert into book set tuh=?,name=?,book_type=?,price=?,id=?";
static String UPDATE = "update book set tuh=?,name=?,book_type=?,price=? where id=?";
static String DELETE = "delete from book where id = ?";
public List<Book> list() throws SQLException, ClassNotFoundException {
List<Book> books = new ArrayList<>();
ResultSet rs = select(SELECT);
while (rs.next()){
Book book = new Book();
book.setId(rs.getInt("id"));
book.settuh(rs.getString("tuh"));
book.setName(rs.getString("name"));
book.setbook_type(rs.getString("book_type"));
book.setprice(rs.getFloat("price"));
books.add(book);
}
rs.close();
return books;
}
public void insertOrUpdate(Book book) throws SQLException, ClassNotFoundException {
Object[] params = new Object[5];
params[0] = book.gettuh();
params[1] = book.getName();
params[2] = book.getbook_type();
params[3] = book.getprice();
if(book.getId() == null){//插入的情况,需要加id
params[4]=Integer.valueOf(getNewid());
save(INSERT,params);
}
else {//更新的情况
params[4]=book.getId();
save(UPDATE,params);
}
}
public void deleteById(Integer id) throws SQLException, ClassNotFoundException {
Object[] params = new Object[1];
params[0] = id;
save(DELETE,params);
}
public Book getById(Integer id) throws SQLException, ClassNotFoundException {//ok
Object[] params = new Object[1];
params[0] = id;
ResultSet rs = select(SELECTBYID,params);
rs.next();
Book book = new Book();
book.setId(rs.getInt("id"));
book.settuh(rs.getString("tuh"));
book.setName(rs.getString("name"));
book.setbook_type(rs.getString("book_type"));
book.setprice(rs.getFloat("price"));
return book;
}
}
UserDao.java
package cn.cie.dao;
import cn.cie.entity.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDao extends BaseDao {
static String SELECTUSER = "select * from usertable";
public List<User> listuser() throws SQLException, ClassNotFoundException{
List<User> users = new ArrayList<>();
ResultSet rs = select(SELECTUSER);
while (rs.next()){
User user = new User();
user.setUser(rs.getString("user"));
user.setPassword(rs.getString("password"));
users.add(user);
}
rs.close();
return users;
}
}
Book.java
package cn.cie.entity;
public class Book {
private Integer id;
private String tuh;
private String name;
private String book_type;
private Float price;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", tuh='" + tuh + '\'' +
", name='" + name + '\'' +
", book_type='" + book_type + '\'' +
", price=" + price +
'}';
}
public String gettuh() {
return tuh;
}
public void settuh(String tuh) {
this.tuh = tuh;
}
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 getbook_type() {
return book_type;
}
public void setbook_type(String book_type) {
this.book_type = book_type;
}
public Float getprice() {
return price;
}
public void setprice(Float price) {
this.price = price;
}
}
User.java
package cn.cie.entity;
public class User {
private String user;
private String password;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}