这次根据Struts2完成图书管理项目,
一个完整的的系统都有增删改查四个功能,
因为我这个无法进行修改,就叫项目
一,创建Struts2框架
不会创建框架的同学
在我以前的博客里有详细教程可以参考以下
直通车struts2创建教程
二,项目结构
com.hnpi.action:控制层
com.hnpi.bean和service:都是逻辑层
com.hnpi.util:工具类
这个项目完全是根据MVC层次做出
数据库结构
三,编写jsp
这些属于图书管理,所以都创建在WebRoot下的book文件夹里
图书列表
listBook.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ 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='<%=basePath %>book/toUpdateBook?book.id=<s:property value="id"/>'>更新</a> <a href='<%=basePath %>book/delBook?book.id=<s:property value="id"/>'>删除</a></td>
</tr>
</s:iterator>
<!--
<c:forEach items="${requestScope.books}" var="book">
<tr>
<td>${book.id }</td>
<td>${book.bookName }</td>
<td>${book.bookAuthor }</td>
<td>${book.bookIsbn }</td>
<td>${book.bookPublish }</td>
<td><a href='<%=basePath %>book/toUpdateBook?book.id=${book.id }'>更新</a> <a href='<%=basePath %>book/delBook?book.id=${book.id }'>删除</a></td>
</tr>
</c:forEach>
-->
</table>
</body>
</html>
添加加图书页面
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>
这些等会都会有关联
2,编写登陆login.jsp页面
因为这个页面是关于用户的 我们就直接写在 user 文件夹里
<%@ 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>
四,编写action控制层
这里都是普通的class类
LoginAction.java这里的用户名和密码我们就直接写死了,就不再注册
用户名admin 密码 123
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("admin")&&pwd.equals("123")){
Map<String, Object> session = ActionContext.getContext().getSession();
session.put("user", name);
return "success";
}else{
return "error";
}
}else{
return "error";
}
}
}
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 listBook() {
BookService bookService = new BookServiceImpl();
List<Book> books = new ArrayList<Book>();
books = bookService.selectAllBook();
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";
}
}
五,编写bean包里的class类
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 + "]";
}
}
六,配置拦截器
我们再com.hnpi.interceptor包下创建一个UserInterceptor.class类
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();
}
}
七,编写工具类
就是一个简单的数据库连接
我们再util包下创建一个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();
}
}
}
八,编写逻辑层中的service
创建接口
我们再service包下创建接口文件
注意 是接口哦
BookService.java
package com.hnpi.service;
import java.util.List;
import com.hnpi.bean.Book;
public interface BookService {
/**
* 增加图书
* @param book
* @return
*/
public boolean addBook(Book book);
/**
* 根据图书ID删除图书
* @param bookId
* @return
*/
public boolean deleteBook(int bookId);
/**
* 更新图书信息
* @param book
* @return
*/
public boolean updateBook(Book book);
/**
* 根据图书编号查询图书
* @param BookId
* @return
*/
public Book selectBookById(int bookId);
/**
* 查询所有图书
* @return
*/
public List<Book> selectAllBook();
}
在service包的impl包实现该接口
创建一个BookServiceImpl.java的class类
package com.hnpi.service.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.service.BookService;
import com.hnpi.util.DBUtil;
public class BookServiceImpl implements BookService {
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 List<Book> selectAllBook() {
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;
}
public Book selectBookById(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(6, book.getId());
count = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeConn(conn, ps, null);
}
if (count > 0)
return true;
else
return false;
}
}
九,配置src目录下的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" extends="struts-default" namespace="/user">
<action name="login" class="com.hnpi.action.LoginAction"
method="login">
<result name="success" type="chain">
<param name="actionName">listBookAction</param>
<param name="namespace">/book</param>
<param name="method">listBook</param>
</result>
<result name="error" type="redirect">/user/login.jsp</result>
</action>
</package>
<package name="default" extends="struts-default" namespace="/book">
<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="listBookAction" class="com.hnpi.action.BookAction" method="listBook">
<result name="success">/book/listBook.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">listBookAction</result>
</action>
<action name="toModifyBook" class="com.hnpi.action.BookAction"
method="toModifyBook">
<result name="success">/book/modifuBook.jsp</result>
</action>
<action name="modifyBook" class="com.hnpi.action.BookAction"
method="modifyBook">
<result name="success" type="chain">listBookAction</result>
</action>
<action name="delBook" class="com.hnpi.action.BookAction"
method="delBook">
<result name="success" type="chain">listBookAction</result>
</action>
</package>
</struts>
最后注意
记得导入jar包
更新功能暂时无法使用,
成功截图
用户名跟密码我们都已经写死了,
登陆成功进入图书列表 失败重新进入登陆界面
点击新增图书,这里我为了节省时间就随便写点了(手动滑稽)
谢谢大家