您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

JavaEE期末考 Struts实例

Struts实例

  • 代码
    • Web代码
      • List.jsp
      • Edit.jsp
    • 配置文件
      • 默认包下的struts.xml
      • WEB-INF下的web.xml
    • Java代码
      • action包
        • BookAction.java
      • dao包
        • BookDao.java
        • BookDaoImpl.java
      • db包
        • DBConnection.java
      • factory包
        • DAOFactory.java
      • model包
        • Book.java
      • service包
        • BookService.java
      • p1包和pojo包为空
  • 使用的库文件
  • 注意

代码

Web代码

List.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Book List</title>
    <style type="text/css">
        table {
            border: 1px solid black;
            border-collapse: collapse;
        }
        
        table thead tr th {
            border: 1px solid black;
            padding: 3px;
            background-color: #cccccc;
        }
        
        table tbody tr td {
            border: 1px solid black;
            padding: 3px;
        }
    </style>
</head>
<body>    
    <h2>Book List</h2>
    <s:form action="Remove" theme="simple">
        <table cellspacing="0">
            <thead>
                <tr>
                    <th>Select</th>
                    <th>ISBN</th>
                    <th>Title</th>
                    <th>Price</th>
                    <th>Operation</th>
                </tr>
            </thead>
            <tbody>
                <s:iterator value="books">
                    <tr>
                        <td><input type="checkbox" name="isbns" value='<s:property value="isbn" />' /></td>
                        <td><s:property value="isbn" /></td>
                        <td><s:property value="title" /></td>
                        <td>$<s:property value="price" /></td>
                        <td>
                            <a href='<s:url action="Edit"><s:param name="isbn" value="isbn" /></s:url>'>
                                Edit
                            </a>
                            &nbsp;
                            <a href='<s:url action="Remove"><s:param name="isbn" value="isbn" /></s:url>'>
                                Delete
                            </a>
                        </td>
                    </tr>
                </s:iterator>
            </tbody>
        </table>
        <s:submit value="Remove" /><a href="Edit.jsp">Add Book</a>
    </s:form>    
</body>
</html>

Edit.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Book</title>
</head>
<body>    
    <h2>
        <s:if test="null == book">
            Add Book
        </s:if>
        <s:else>
            Edit Book
        </s:else>
    </h2>
    <s:form action="Store" >
        <s:textfield name="book.isbn" label="ISBN" />
        <s:textfield name="book.title" label="Title" />
        <s:textfield name="book.price" label="Price" />
        <s:submit />
    </s:form>
</body>
</html>

配置文件

默认包下的struts.xml

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Book</title>
</head>
<body>    
    <h2>
        <s:if test="null == book">
            Add Book
        </s:if>
        <s:else>
            Edit Book
        </s:else>
    </h2>
    <s:form action="Store" >
        <s:textfield name="book.isbn" label="ISBN" />
        <s:textfield name="book.title" label="Title" />
        <s:textfield name="book.price" label="Price" />
        <s:submit />
    </s:form>
</body>
</html>

WEB-INF下的web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	 version="3.1">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <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>

Java代码

action包

BookAction.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package action;
import java.util.Collection;

import dao.BookDaoImpl;
import model.Book;
import service.BookService;
import factory.DAOFactory;

 import com.opensymphony.xwork2.ActionSupport;
import dao.BookDao;
 

public class BookAction extends ActionSupport {
    
    private String isbn;
    private String[] isbns;
    private Book book;
    private Collection<Book> books;
    private BookDao dao;

    public BookAction() throws Exception{
        this.dao = DAOFactory.getIEmpDAOInstance();
    }
    
   
        
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String[] getIsbns() {
        return isbns;
    }

    public void setIsbns(String[] isbns) {
        this.isbns = isbns;
    }
        
    public Collection<Book> getBooks() {
        return books;
    }

    public void setBooks(Collection<Book> books) {
        this.books = books;
    }

    public String load() throws Exception {
        book = dao.findByBookIsbn(isbn);
        return SUCCESS;
    }

    public String list() throws Exception {
        books = dao.findAll();
        return SUCCESS;
    }
        
    public String store() throws Exception {
        dao.storeBook(book);
        return SUCCESS;
    }
    
    public String remove() throws Exception {
        if(null != isbn) {
            dao.removeBook(isbn);
        } else {
            dao.removeBooks(isbns);
        }
        return SUCCESS;
    }
}

dao包

BookDao.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;


import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import model.Book;

public interface BookDao {
    /*private static final BookDao instance;
    private static final ConcurrentMap<String, Book> data;
    
    static {
        instance = new BookDao();
        data = new ConcurrentHashMap<String, Book>();
        data.put("978-0735619678", new Book("978-0735619678", "Code Complete, Second Edition", 32.99));
        data.put("978-0596007867", new Book("978-0596007867", "The Art of Project Management", 35.96));
        data.put("978-0201633610", new Book("978-0201633610", "Design Patterns: Elements of Reusable Object-Oriented Software", 43.19));
        data.put("978-0596527341", new Book("978-0596527341", "Information Architecture for the World Wide Web: Designing Large-Scale Web Sites", 25.19));
        data.put("978-0735605350", new Book("978-0735605350", "Software Estimation: Demystifying the Black Art", 25.19));
    }
    
    private BookDao() {}
    
    
    
    public Collection<Book> getBooks() {
        return data.values();
    }
    
    public Book getBook(String isbn) {
        return data.get(isbn);
    }
    
    public void storeBook(Book book) {
        data.put(book.getIsbn(), book);
    }
        
    public void removeBook(String isbn) {
        data.remove(isbn);
    }
    
    public void removeBooks(String[] isbns) {
        for(String isbn : isbns) {
            data.remove(isbn);
        }
    }*/
    
    /**
     * 
     * @param product
     * @return
     * @throws Exception 
     */
    
    public boolean storeBook(Book book) throws Exception;
    
    public List<Book> findAll()throws Exception;
    public Book findByBookIsbn(String isbn)throws Exception;
    public boolean updateBook(Book book) throws Exception;
    public boolean removeBook(String isbn)throws Exception;
    public boolean removeBooks(String[] isbns)throws Exception;
    
}

BookDaoImpl.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import model.Book;

/**
 *
 * @author lenovo
 */
public class BookDaoImpl implements BookDao{
    private Connection conn=null;
    private PreparedStatement pstmt=null;
     public BookDaoImpl(Connection conn){
        this.conn=conn;
    }

    @Override
    public boolean storeBook(Book book) throws Exception {
        boolean flag=false;
        String sql="insert into book(isbn,title,price) values(?,?,?)";
        this.pstmt=this.conn.prepareStatement(sql);
        this.pstmt.setString(1,book.getIsbn());
        this.pstmt.setString(2,book.getTitle());
        this.pstmt.setDouble(3,book.getPrice());
        
        if(this.pstmt.executeUpdate()>0){
            flag=true;
        }
        this.pstmt.close();
        return flag;
    }

    @Override
    public List<Book> findAll() throws Exception {
        List<Book> list=new ArrayList<Book>();
        String sql="select isbn,title,price from book";
        this.pstmt=this.conn.prepareStatement(sql);
        ResultSet rs=this.pstmt.executeQuery();
        Book book=null;
        while(rs.next()){
            book=new Book();
            book.setIsbn(rs.getString(1));
            book.setTitle(rs.getString(2));
            book.setPrice(rs.getDouble(3));
            list.add(book);
        }
        this.pstmt.close();
        return list;
    }

    @Override
    public boolean updateBook(Book book)throws Exception {
        boolean flag=false;
        String sql="update book set title=?,price=? where isbn=?";
        this.pstmt=this.conn.prepareStatement(sql);
        this.pstmt.setString(3,book.getIsbn());
        this.pstmt.setString(1,book.getTitle());
        this.pstmt.setDouble(2,book.getPrice());
        
        if(this.pstmt.executeUpdate()>0){
            flag=true;
        }
        this.pstmt.close();
        return flag;
    }
    
    @Override
    
    public boolean removeBook(String isbn) throws Exception {
        boolean flag=false;
        String sql="delete from book where isbn=? ";
        this.pstmt=this.conn.prepareStatement(sql);
        this.pstmt.setString(1,isbn);
        if(this.pstmt.executeUpdate()>0){
            flag=true;
        }
        this.pstmt.close();
        return flag;
    }

    @Override
    public boolean removeBooks(String[] isbns) throws Exception {
        boolean flag=false;
        int count=0;
        for(String isbn : isbns){
            String sql="delete from book where isbn=? ";
            this.pstmt=this.conn.prepareStatement(sql);
            this.pstmt.setString(1,isbn);
            count += this.pstmt.executeUpdate();
        }
        if(count>0){
            flag=true;
        }
        this.pstmt.close();
        
        return flag;
    }

    @Override
    public Book findByBookIsbn(String isbn) throws Exception {
        String sql="select isbn,title,price from book where isbn=? ";
        this.pstmt=this.conn.prepareStatement(sql);
        this.pstmt.setString(1,isbn);
        ResultSet rs=this.pstmt.executeQuery();
        Book book=null;
        while(rs.next()){
            book=new Book();
            book.setIsbn(rs.getString(1));
            book.setTitle(rs.getString(2));
            book.setPrice(rs.getDouble(3));
        }
        this.pstmt.close();
        return book;
       
    }
}

db包

DBConnection.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package db;
 
import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {
    private static final String Driver="com.mysql.cj.jdbc.Driver";
    private static final String Url="jdbc:mysql://127.0.0.1:3306/daoTest";
    private static final String User="root";
    private static final String Password="0606";
    private Connection conn=null;
    
    //进行数据库连接
    public DBConnection() throws Exception{
        try{
            //用反射加载数据库驱动
            Class.forName(Driver);
            this.conn=DriverManager.getConnection(Url,User,Password);
        }
        catch (Exception e) {
            throw e;
        }
    }
    //取得数据库的连接
    public Connection getConnection(){
        return this.conn;        
    }
    //关闭数据库
    public void close() throws Exception{
        if(this.conn!=null){
            try {
                this.conn.close();
                
            } catch (Exception e) {
                throw e;
            }
        }
    }
    
}

factory包

DAOFactory.java

package factory;

import  dao.BookDao;
import  service.BookService;

public class DAOFactory {
    public static BookDao getIEmpDAOInstance() throws Exception{
        //取得业务操作类
        return new BookService();
    }
}

model包

Book.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

public class Book {
    private String isbn;
    private String title;
    private double price;
    
    public Book() {        
    }
    
    public Book(String isbn, String title, double price) {
        this.isbn = isbn;
        this.title = title;
        this.price = price;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }    
}

service包

BookService.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package service;

 
import java.util.List;

import  dao.BookDao;
import  dao.BookDaoImpl;
import  db.DBConnection;
import  model.Book;

/**
 * 操作数据库
 *
 */
public class BookService implements BookDao{
    
    private DBConnection dbconn=null;
    private BookDao dao=null;
    //在构造方法中实例化数据库连接,同时实例化dao对象
    public BookService() throws Exception{
        this.dbconn=new DBConnection();
        //实例化ProductDao的实现类
        this.dao=new BookDaoImpl(this.dbconn.getConnection());                
    }    

   
    @Override
    public boolean storeBook(Book book) throws Exception {
        boolean flag=false;
        try{
            if(this.dao.findByBookIsbn(book.getIsbn())==null){
                //如果要插入的产品编号不存在
                flag=this.dao.storeBook(book);//新增一条产品信息
            } else {
                flag=this.updateBook(book);
            }
        }
        catch (Exception e) {
            throw e;
        }finally{
            this.dbconn.close();
        }
        
        return flag;
    }

    @Override
    public List<Book> findAll() throws Exception {
        List<Book> all=null; //定义产品返回的集合
        try {
            all=this.dao.findAll();
        } catch (Exception e) {
            throw e;
        }finally{
            this.dbconn.close();
        }
        return all;
    }

    @Override
    public boolean updateBook(Book book) throws Exception {
        return this.dao.updateBook(book);
    }

    @Override
    public Book findByBookIsbn(String isbn) throws Exception {
        Book book=null;
        try {
            book=this.dao.findByBookIsbn(isbn);
        } catch (Exception e) {
            throw e;
        }finally{
            this.dbconn.close();
        }
        return book;
    }

    @Override
    public boolean removeBook(String isbn) throws Exception {
        
        boolean flag=false;
        try{
            if(this.dao.findByBookIsbn(isbn)!=null){
                //如果要删除的产品编号存在
                flag=this.dao.removeBook(isbn);
            }
        }
        catch (Exception e) {
            throw e;
        }finally{
            this.dbconn.close();
        }
        
        return flag;
    }

    @Override
    public boolean removeBooks(String[] isbns) throws Exception {
        
        return this.dao.removeBooks(isbns);
        
    }

}

p1包和pojo包为空

使用的库文件

在这里插入图片描述

注意

1.机房环境下使用的数据库连接库文件为5.1.23版本,并且在数据库连接即DBConnection文件中要将

private static final String Driver="com.mysql.cj.jdbc.Driver";

修改为(去掉cj)

private static final String Driver="com.mysql.jdbc.Driver";

2.记得修改数据库连接的数据库表名及连接用户密码


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进