Struts2简易图书管理功能

Struts2简易图书管理功能

1.在第一篇写的Struts2框架基础上在src下创建各个分层结构,首先创建com包再在com包下建hnpi包再在com.hnpi包下建action,been,dao,interceptor,service,util包,如图
在这里插入图片描述
2.在util包下建一个数据库DButil工具类–DButil.java

package com.hnpi.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DButil {
	public static Connection getConn() {

		String url = "jdbc:sqlserver://localhost:1433;databaseName=MyDB";
		String user = "sa";
		String pwd = "1";
		Connection conn = null;

		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			conn = DriverManager.getConnection(url, user, pwd);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	public static void closeConn(Connection conn, PreparedStatement ps,
			ResultSet rs) {

		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {

			e.printStackTrace();
		}

		try {
			if (ps != null) {
				ps.close();
			}
		} catch (SQLException e) {

			e.printStackTrace();
		}

		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {

			e.printStackTrace();
		}
	}
}

3.在bean包下建一个Book.java

package com.hnpi.bean;

public class Book {
	   private int id;
	   private String bookName;
	   private String bookAuthor;
	   private String bookPublish;
	   private String bookIsbn;
	   public int getId() {
		return id;
	   }
	   public void setId(int id) {
		this.id = id;
	   }
	   public String getBookName() {
		return bookName;
	   }
	   public void setBookName(String bookName) {
		this.bookName = bookName;
	   }
		public String getBookAuthor() {
		return bookAuthor;
		}
		public void setBookAuthor(String bookAuthor) {
		this.bookAuthor = bookAuthor;
		}
		public String getBookPublish() {
		return bookPublish;
		}
		public void setBookPublish(String bookPublish) {
		this.bookPublish = bookPublish;
		}
		public String getBookIsbn() {
		return bookIsbn;
		}
		public void setBookIsbn(String bookIsbn) {
		this.bookIsbn = bookIsbn;
		}
	   
	}

4.在dao包下建立一个BookDao.java接口

package com.hnpi.dao;
import java.util.List;

import com.hnpi.bean.Book;

public interface BookDao {
	/**
	 * 查询所有图书
	 * @return
	 */
	public List<Book> selectBooks();
	/**
	 * 增加图书
	 * @param book
	 * @return
	 */
	public boolean addBook(Book book);

	/**
	 * 根据图书ID删除图书
	 * @param bookId
	 * @return
	 */
	public boolean deleteBook(int bookId);
	
	/**
	 * 根据图书ID查询图书
	 * @param bookId
	 * @return
	 */
	public Book selectBookId(int bookId);
	
	/**
	 * 更新图书信息
	 * @param book
	 * @return
	 */
	public boolean updateBook(Book book);

}

5.实现dao在dao.impl下建立BookDaoImpl.java

package com.hnpi.dao.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 com.hnpi.bean.Book;
import com.hnpi.dao.BookDao;
import com.hnpi.util.DButil;

public class BookDaoImpl implements BookDao {

	public List<Book> selectBooks() {
		// TODO 交接数据库
		Connection conn = DButil.getConn();
		
		String sql = "select * from book";
		
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		List<Book> books = new ArrayList<Book>();
		
		try{
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				Book book = new Book();
				book.setId(rs.getInt(1));
				book.setBookName(rs.getString(2));
				book.setBookAuthor(rs.getString(3));
				book.setBookPublish(rs.getString(4));
				book.setBookIsbn(rs.getString(5));
				books.add(book);
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			DButil.closeConn(conn, ps, rs);
		}
		return books;
	}

	public boolean addBook(Book book) {
		Connection conn = DButil.getConn();
		String sql = "insert into book (book_name,book_author,book_isbn,book_publish) values (?,?,?,?)";
		PreparedStatement ps = null;
		int count = 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, book.getBookName());
			ps.setString(2, book.getBookAuthor());
			ps.setString(3, book.getBookIsbn());
			ps.setString(4, book.getBookPublish());
			count = ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.closeConn(conn, ps, null);
		}

		if (count > 0)
			return true;
		else
			return false;
	}

	public boolean deleteBook(int bookId) {
		Connection conn = DButil.getConn();
		String sql = "delete from book where id = ?";
		PreparedStatement ps = null;
		int count = 0;
		try {
			ps = conn.prepareStatement(sql);
			
			ps.setInt(1, bookId);
			count = ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.closeConn(conn, ps, null);
		}

		if (count > 0)
			return true;
		else
			return false;
	}

	public Book selectBookId(int bookId) {
		Connection conn = DButil.getConn();
		String sql = "select * from book where id = ?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		Book book = new Book();
		
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, bookId);
			rs = ps.executeQuery();
			if(rs.next()){
				
				book.setId(rs.getInt(1));
				book.setBookName(rs.getString(2));
				book.setBookAuthor(rs.getString(3));
				book.setBookIsbn(rs.getString(4));
				book.setBookPublish(rs.getString(5));
			
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.closeConn(conn, ps, null);
		}
		return book;
	}

	public boolean updateBook(Book book) {
		Connection conn = DButil.getConn();
		String sql = "update  book  set book_name =  ?,book_author = ?,book_isbn = ?,book_publish = ? where id =?" ;
		PreparedStatement ps = null;
		int count = 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, book.getBookName());
			ps.setString(2, book.getBookAuthor());
			ps.setString(3, book.getBookIsbn());
			ps.setString(4, book.getBookPublish());
			ps.setInt(5, book.getId());
			count = ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.closeConn(conn, ps, null);
		}
		if (count > 0)
			return true;
		else
			return false;
	}

}

6.在service下建立BookService.java接口

package com.hnpi.service;

import java.util.List;

import com.hnpi.bean.Book;

public interface BookService{
	/**
	 * 查询所有图书
	 * @return
	 */
	public List<Book> selectBooks();
	/**
	 * 增加图书
	 * @param book
	 * @return
	 */
	public boolean addBook(Book book);

	/**
	 * 根据图书ID删除图书
	 * @param bookId
	 * @return
	 */
	public boolean deleteBook(int bookId);
	
	/**
	 * 根据图书ID查询图书
	 * @param bookId
	 * @return
	 */
	public Book selectBookId(int bookId);
	
	/**
	 * 更新图书信息
	 * @param book
	 * @return
	 */
	public boolean updateBook(Book book);

}


7.实现service在service.impl下新建实现service接口BookServiceImpl.java

package com.hnpi.service.impl;

import java.util.List;

import com.hnpi.bean.Book;
import com.hnpi.dao.BookDao;
import com.hnpi.dao.impl.BookDaoImpl;
import com.hnpi.service.BookService;

public class BookServiceImpl implements BookService {

	/**
	 * 查询所有图书
	 * @return
	 */
	public List<Book> selectBooks() {
		// TODO 从数据库获取内容进行数据组织
		BookDao bookDao = new BookDaoImpl();
		List<Book> books = bookDao.selectBooks();
		return books;
	}

	/**
	 * 增加图书
	 * @param book
	 * @return
	 */
	public boolean addBook(Book book) {
		BookDao bookDao = new BookDaoImpl();
		return  bookDao.addBook(book);
		
		
	}

	/**
	 * 根据图书ID删除图书
	 * @param bookId
	 * @return
	 */
	public boolean deleteBook(int bookId) {
		BookDao bookDao = new BookDaoImpl();
		return  bookDao.deleteBook(bookId);
		
		
	}
	
	/**
	 * 根据图书ID查询图书
	 * @param bookId
	 * @return
	 */
	public Book selectBookId(int bookId) {
		BookDao bookDao = new BookDaoImpl();
		Book book =  bookDao.selectBookId(bookId);
		return book;

	}


	/**
	 * 更新图书信息
	 * @param book
	 * @return
	 */

	public boolean updateBook(Book book) {
		BookDao bookDao = new BookDaoImpl();
		return  bookDao.updateBook(book);
	}

}

8.创建action 登录界面action LoginAction.java

package com.hnpi.action;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    private String name;
    private String pwd;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String login(){
		if(name!=null && !"".equals(name) &&pwd!=null && !"".equals(pwd) ){
    		if("admin".equals(name) && "123".equals(pwd)){
    		   Map<String,Object>session = ActionContext.getContext().getSession();
    		   session.put("user",name);
    			return "success";
    		}else{
    			return "fail";
    		}
    	}else{
    		return "fail";
    	}
    }
}

9.接下来是图书页面 BookAction.java

package com.hnpi.action;


import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.hnpi.bean.Book;
import com.hnpi.service.BookService;
import com.hnpi.service.impl.BookServiceImpl;
import com.opensymphony.xwork2.ActionSupport;

public class BookAction extends ActionSupport {
	private Book book;
	public Book getBook() {
		return book;
	}

	public void setBook(Book book) {
		this.book = book;
	}
	/**
	 * 查询图书
	 * @return
	 */
	public String bookList(){
		//从数据库获取数据 进行数据准备 然后将数据传至bookList.jsp
		BookService bookService = new BookServiceImpl();
		List<Book> books = bookService.selectBooks();
		
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("books", books);
		return "success";
	}
	
	/**
	 * 准备新增图书
	 * @return
	 */
	public String toAddBook() {
		return "success";
	}
	
	/**
	 * 新增图书
	 * @return
	 */
	public String addBook() {
		BookService bookService = new BookServiceImpl();
		bookService.addBook(book);
		return "success";
	}
	
	/**
	 * 删除图书
	 * @return
	 */
	public String delBook(){
		BookService bookService = new BookServiceImpl();
		bookService.deleteBook(book.getId());
		return "success";
	}
	
	/**
	 * 根据id查询图书  并跳转到更新图书页面
	 * @return
	 */
	public String selectBookId(){
		BookService bookService = new BookServiceImpl();
		Book booksId = bookService.selectBookId(book.getId());
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("booksId", booksId);
		return "success";
	}
	/**
	 * 更新图书
	 * @return
	 */
	public String updateBook(){
		BookService bookService = new BookServiceImpl();
		bookService.updateBook(book);
		return "success";
		
	}
}

10. 接下来是视图层 这里分好层次
在这里插入图片描述
在user下新建登录界面login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>登录页面</title>
  </head>
  
  <body>
    <form action="<%=basePath%>/user/login" method="post">
          用户名:<input type="text" name="name"/><br>
          密码:<input type="text" name="pwd"/><br>
    <input type="submit" value="提交"/>
    </form>
  </body>
</html>

11.接下来在book里新建管理页面 新增页面 修改页面
addbook.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>新增图书</title>

  </head>
  
  <body>
        <form  action="book/addBook" method="post">
		书名:<input type="text" name="book.bookName" /><br /> 
		作者:<input type="text" name="book.bookAuthor" /><br /> 
		ISBN:<input type="text" name="book.bookIsbn" /><br /> 
		出版商:<input type="text" name="book.bookPublish" /><br /> 
		<input type="submit" value="提交" />
	    </form>
  </body>
</html>

bookList.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   <style type="text/css">
    body{
    	margin-left: 200pt;
    }
    table,table tr th, table tr td 
    	{
    		border: 1px solid grey
   		 }
    </style>
    <base href="<%=basePath%>">
    
    <title>图书管理</title>
  </head>
  
  <body>
  <a href='<%=basePath %>book/toAddBook'>新增图书</a>
     <table>
       <thead>
         <tr>
           <th>编号</th>
           <th>书名</th>
           <th>作者</th>
           <th>出版社</th>
           <th>ISBN</th>
           <th>操作</th>
         </tr>
       </thead>
       <tbody>
       <s:iterator value="#request.books" status="book">
           <tr>
             <td><s:property value="id" /><br/></td>
             <td><s:property value="bookName" /><br/></td>
             <td><s:property value="bookAuthor" /><br/></td>
             <td><s:property value="bookPublish" /><br/></td>
             <td><s:property value="bookIsbn" /><br/></td>
             <td><a href="<%=basePath %>book/selectBookId?book.id=<s:property value="id"/>">更新</a> <a href="<%=basePath %>book/delBook?book.id=<s:property value="id"/>">删除</a></td>
           </tr>
           </s:iterator>
       </tbody>
    </table>
  </body>
</html>

manage.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   <style type="text/css">
    body{
    	margin-left: 200pt;
    }
    table,table tr th, table tr td 
    	{
    		border: 1px solid grey
   		 }
    </style>
    <base href="<%=basePath%>">
    
    <title>图书管理</title>
  </head>
  
  <body>
  <a href='<%=basePath %>book/toAddBook'>新增图书</a>
     <table>
       <thead>
         <tr>
           <th>编号</th>
           <th>书名</th>
           <th>作者</th>
           <th>出版社</th>
           <th>ISBN</th>
           <th>操作</th>
         </tr>
       </thead>
       <tbody>
       <s:iterator value="#request.books" status="book">
           <tr>
             <td><s:property value="id" /><br/></td>
             <td><s:property value="bookName" /><br/></td>
             <td><s:property value="bookAuthor" /><br/></td>
             <td><s:property value="bookPublish" /><br/></td>
             <td><s:property value="bookIsbn" /><br/></td>
             <td><a href="<%=basePath %>book/selectBookId?book.id=<s:property value="id"/>">更新</a> <a href="<%=basePath %>book/delBook?book.id=<s:property value="id"/>">删除</a></td>
           </tr>
           </s:iterator>
       </tbody>
    </table>
  </body>
</html>

12.配置我们的struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="user" namespace="/user" extends="struts-default">
        <action name="login" class="com.hnpi.action.LoginAction" method="login">
           <result name="success" type="chain">
           	    <param name="namespace">/book</param>
	            <param name="actionName">BookList</param>
	            <param name="method">bookList</param>
            </result>
			<result name="fail">/user/login.jsp</result>
        </action>
    </package>
    <package name="book" namespace="/book" extends="struts-default">
		<interceptors>
			<interceptor name="userInterceptor" class="com.hnpi.interceptor.UserInterceptor"></interceptor>
			<interceptor-stack name="selfStack">
				<interceptor-ref name="userInterceptor"></interceptor-ref>
				<interceptor-ref name="defaultStack"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
		<default-interceptor-ref name="selfStack"></default-interceptor-ref>
		<global-results>
			<result name="fail">/user/login.jsp</result>
		</global-results>
		<action name="BookList" class="com.hnpi.action.BookAction"
			method="bookList">
			<result name="success">/book/bookList.jsp</result>
		</action>
		<action name="toAddBook" class="com.hnpi.action.BookAction"
			method="toAddBook">
			<result name="success">/book/addBook.jsp</result>
		</action>
		<action name="addBook" class="com.hnpi.action.BookAction"
			method="addBook">
			<result name="success" type="chain">BookList</result>
		</action>
		<action name="selectBookId" class="com.hnpi.action.BookAction"
			method="selectBookId">
			<result name="success">/book/manage.jsp</result>
		</action>
		<action name="updateBook" class="com.hnpi.action.BookAction"
			method="updateBook">
			<result name="success" type="chain">BookList</result>
		</action>
		<action name="delBook" class="com.hnpi.action.BookAction"
			method="delBook">
			<result name="success" type="chain">BookList</result>
		</action>
	</package>
</struts>

13.新建一个数据库 库名表名列名要对好 这里就不做代码展示了

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值