1. 程式人生 > >Struts2 框架 +SQL Server資料庫 (圖書的增刪改查)

Struts2 框架 +SQL Server資料庫 (圖書的增刪改查)

用資料庫和struts2框架來實現簡單的圖書的管理(增刪改查)

要求: 

    1:登入成功之後跳轉到一個新增的頁面 圖書列表頁面     2:增加圖書的新增頁面及功能     3:增加圖書的刪除功能     4:增加圖書的修改頁面及功能     5:在圖書的新增/修改可以進行中英文的切換     特別注意: 關於圖書的增刪改查 需要進行登入之後才能操作,需要用到攔截器,如果沒有登入則直接跳轉到登入頁面

1. 專案列表

2.addBook.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>新增圖書</title>
<style type="text/css">
    body{
    	margin-left: 300pt;
    }
   </style>
</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>

3.bookList.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>
    <base href="<%=basePath%>">
    
    <title>圖書列表</title>
    <style type="text/css">
    body{
    	margin-left: 200pt;
    }
    table,table tr th, table tr td 
    	{
    		border: 1px solid grey
   		 }
    </style>
  </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>
    	<s:iterator value="#request.books" status="book">
			<tr>
		  		<td><s:property value="id"/></td>
		  		<td><s:property value="bookName"/></td>
		  		<td><s:property value="bookAuthor"/></td>
		  		<td><s:property value="bookIsbn"/></td>
		  		<td><s:property value="bookPublish"/></td>
				<td><a href='<%=basePath %>book/selectBookId?book.id=<s:property value="id"/>'>更新<br /></a>&nbsp;<a href='<%=basePath %>book/delBook?book.id=<s:property value="id"/>'>刪除</a></td>
		  	</tr>
		</s:iterator> 
    
    </table>
  </body>
</html>

4.modifyBook.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>
    <base href="<%=basePath%>">    
    <title>更新頁面</title>
  </head>  
  <body>
    更新內容:
    <form action="book/updateBook" method="post">
	    <table>
		    <thead>
		    		<tr>
		    			<th>編號</th>
		    			<th>圖書名稱</th>
		    			<th>作者</th>
		    			<th>出版社</th>
		    			<th>ISBN</th>   			
		    		</tr>
		    </thead>
		    <s:iterator value="#request.booksId" status="booksId">
		   		<tr>
			  		<td><input type="text" value=" <s:property value="id"/>" name="book.id"/></td>
			  		<td><input type="text" value=" <s:property value="bookName"/>" name="book.bookName"/></td>
			  		<td><input type="text" value=" <s:property value="bookAuthor"/>" name="book.bookAuthor"/></td>
			  		<td><input type="text" value=" <s:property value="bookIsbn"/>" name="book.bookIsbn"/></td>
			  		<td><input type="text" value=" <s:property value="bookPublish"/>" name="book.bookPublish"/></td>
		  		</tr>		  	
		  	</s:iterator> 
	    </table>
	    <input type="submit" value="提交"/>
    </form>
  </body>
</html>

5. login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>

6. BookAction.java

package com.xxs.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

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

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";
		
	}

}

7.LoginAction.java

package com.xxs.action;

import java.util.Map;

import javax.servlet.http.HttpSession;

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(name.equals("xxs")&&pwd.equals("123")){
				
				Map<String, Object> session = ActionContext.getContext().getSession();
				session.put("user", name);
				return "success";
			}else{
				return "fail";
			}
		}else{
			return "fail";
		}
	}
	
}

8.Book.java

package com.xxs.bean;

public class Book {

	private int id;
	private String bookName;
	private String bookAuthor;
	private String bookIsbn;
	private String bookPublish;
	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 getBookIsbn() {
		return bookIsbn;
	}
	public void setBookIsbn(String bookIsbn) {
		this.bookIsbn = bookIsbn;
	}
	public String getBookPublish() {
		return bookPublish;
	}
	public void setBookPublish(String bookPublish) {
		this.bookPublish = bookPublish;
	}
	
	public Book() {
		super();
	}
	public Book(int id, String bookName, String bookAuthor, String bookIsbn,
			String bookPublish) {
		super();
		this.id = id;
		this.bookName = bookName;
		this.bookAuthor = bookAuthor;
		this.bookIsbn = bookIsbn;
		this.bookPublish = bookPublish;
	}
	
	public String toString() {
		return "Book [bookAuthor=" + bookAuthor + ", bookIsbn=" + bookIsbn
				+ ", bookName=" + bookName + ", bookPublish=" + bookPublish
				+ ", id=" + id + "]";
	}
	
	
	
	
}

9.BookDaoImpl.java

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

public class BookDaoImpl implements BookDao{

	@Override
	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;
	}


}

10.BookDao.java

package com.xxs.dao;

import java.util.List;

import com.xxs.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);

	
	

}

11.UserInterceptor.java

package com.xxs.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class UserInterceptor extends AbstractInterceptor{

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String user=(String) ActionContext.getContext().getSession().get("user");
        if (user==null||"".equals(user)) {
            return "fail";
        }
        return invocation.invoke();
	}
	

}

12.BookServiceImpl.java

package com.xxs.service.impl;

import java.util.List;

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

/*
 * 作用1 資料的清洗
 * 作用2 可以呼叫多個dao組合成頁面需要顯示的資料
 */

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);
	}


	

}

13.BookService.java

package com.xxs.service;

import java.util.List;

import com.xxs.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);
}

14.DBUtil.java

package com.xxs.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();
		}

	}

}

15.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.xxs.action.LoginAction" method="login">
    			<result name="success" type="chain">
					<param name="actionName">bookList</param>
					<param name="namespace">/book</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.xxs.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.xxs.action.BookAction" method="bookList">
    			<result name="success">/book/bookList.jsp</result>
    		</action>  
    		
    		
    		<action name="toAddBook" class="com.xxs.action.BookAction"
			method="toAddBook">
			<result name="success">/book/addBook.jsp</result>
			</action>
	
			<action name="addBook" class="com.xxs.action.BookAction"
				method="addBook">
				<result name="success" type="chain">bookList
				
					<!--  <param name="actionName">bookList</param>
					<param name="namespace">/book</param>
					<param name="method">bookList</param>-->
				</result>
			</action>

			<action name="selectBookId" class="com.xxs.action.BookAction"
				method="selectBookId">
				<result name="success">/book/modifyBook.jsp</result>
			</action>

			
			<action name="updateBook" class="com.xxs.action.BookAction"
				method="updateBook">
				<result name="success" type="chain">bookList</result>
			</action>



			<action name="delBook" class="com.xxs.action.BookAction"
				method="delBook">
				<result name="success" type="chain">bookList</result>
			</action>	 			
    	</package>	
    </struts>

16.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
  		<filter-name>struts2</filter-name>
  		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  		<filter-name>struts2</filter-name>
  		<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

建立資料庫  

效果圖