1. 程式人生 > >用Struts寫一個簡單的圖書管理

用Struts寫一個簡單的圖書管理

用Struts2寫一個簡單的圖書管理

1.在搭建完整的strust2下完成此專案,如有未完成,請參考第一篇部落格,strust2的搭建過程 首先新建一個普通的javaweb專案,如圖所示: 在這裡插入圖片描述 2.把自己所需要的.jar包匯入到檔案中,如下圖所示: 在這裡插入圖片描述 3.在自己專案檔案下建立包,注意,一定要在SRC下建立,如下圖: 在這裡插入圖片描述 在這裡插入圖片描述 4.在webRoot 下建立檔案,如下圖所示: 在這裡插入圖片描述 BookAction.java程式碼如下:

package com.hnpi.action;

import java.util.ArrayList;
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() {
		BookService bookService = new BookServiceImpl();
		List<Book> books = new ArrayList<Book>();
		books = bookService.selectBooks();
		
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("books", books);

		return "success";
	}
	
}

LoginAction.java程式碼如下:

package com.hnpi.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(){
		System.out.println(name+":"+pwd);
		if(name !=null &&!"".equals(name) && pwd !=null &&!"".equals(pwd)){
			//判斷
			if(name.equals("fuxian")&&pwd.equals("123")){
				
				Map<String, Object> session = ActionContext.getContext().getSession();
				session.put("user", name);
				return "success";
			}else{
				return "error";
			}
		}else{
			return "error";
		}
	}
	
}

Book.java程式碼如下:

package com.hnpi.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 + "]";
	}
	
}

BookDao.java程式碼如下:

package com.hnpi.dao;

import java.util.List;

import com.hnpi.bean.Book;

public interface BookDao {

	public List<Book> selectBooks();

}

BookDaoFileImpl.java程式碼如下:

package com.hnpi.dao.impl;

import java.util.List;

import com.hnpi.bean.Book;
import com.hnpi.dao.BookDao;

public class BookDaoFileImpl implements BookDao{

	public List<Book> selectBooks() {
		// TODO 讀取檔案的程式碼
		return null;
	}

}

BookDaoImpl.java程式碼如下:

package com.hnpi.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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() {
		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.setBookIsbn(rs.getString(4));
				book.setBookPublish(rs.getString(5));
				books.add(book);
			}

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

		return books;
	}

}

BookDaoRedisImpl.java程式碼如下:

package com.hnpi.dao.impl;

import java.util.List;

import com.hnpi.bean.Book;
import com.hnpi.dao.BookDao;

public class BookDaoRedisImpl  implements BookDao{

	public List<Book> selectBooks() {
		// TODO 訪問快取的程式碼
		return null;
	}

}

UserInterceptor.java程式碼如下:

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

BookService.java程式碼如下:

package com.hnpi.service;

import java.util.List;

import com.hnpi.bean.Book;

public interface BookService {

	

	/**
	 * 查詢所有圖書
	 * @return
	 */
	public List<Book> selectBooks();
	
	
}

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.BookDaoFileImpl;
import com.hnpi.dao.impl.BookDaoImpl;
import com.hnpi.service.BookService;

public class BookServiceImpl implements BookService {

	

	public List<Book> selectBooks() {
		BookDao bookDao = new BookDaoImpl();
		return bookDao.selectBooks();
	}

}

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) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			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();
		}

	}

}

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>
   </package>
   </struts>

bookList.jsp程式碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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>
    
    <title>圖書列表</title>
    
    <style type="text/css">
    body{
    	margin-left: 300pt;
    }
    table,table tr th, table tr td 
    	{
    		border: 1px solid grey
   		 }
    </style>
  </head>
  
  <body>
  <a href='<%=basePath %>book/toAddBook'>新增圖書</a>
  <table>
  <thead>
  	<tr>
  		<td>ID</td>
  		<td>書名</td>
  		<td>作者</td>
  		<td>ISBN</td>
  		<td>出版社</td>
  		<td>操作</td>
  	</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='#'>更新</a>&nbsp;&nbsp;<a href='#'>刪除</a></td>
  	</tr>
  </s:iterator> 
  
    </table>
  </body>
</html>

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="user/login" method="post">
    	使用者名稱:<input type="text" name="name"/><br />
    	密碼:<input type="text" name="pwd"/><br />
    	<input type="submit" value="提交" />
    </form>
  </body>
</html>

以上內容僅供參考,如有錯誤,請留言聯絡