JavaSE學習總結(十九)—— Java Web 綜合應用(JSP、Servlet、IDEA、MySQL、JUnit、AJAX、JSON)


一、使用Servlet+JDBC+MySQL+IDEA實現商品管理

1.1、創建項目

打開IntelliJ IDEA開發工具、點擊Create New Project創建一個新的Web項目

 

選擇Java Enterprice(Java企業級開發)、選擇項目使用的JDK、Java EE版本、如果沒有Tomcat則需要配置,請看我的另一篇博客:

《IDEA整合Tomcat與操作技巧》、選擇Web應用、點擊下一步Next

輸入項目名稱與項目路徑、注意盡量避免中文路徑

點擊Finish完成后的結果如下圖所示:

如果對Tomcat有特別的要求則需要進一步配置,可以參考tomcat配置一文,鏈接在上面已給出。

1.2、添加依賴

項目中需要依賴許多的包,包含:JSTL、MySQL驅動、JUnit等

Apache Tomcat JSTL 獲取:

官方下載地址:http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/

先打開項目結構,ctrl+alt+shift+s是快捷鍵

點擊Libraries(庫)、添加、Java

選擇包所在的位置

 

將包添加到項目的Lib目錄中,否則在部署時不會被引用

點擊Fix修正后的結果如下

 依賴包的方法就是這樣了,依賴其它包的方法是一樣的。

1.3、創建數據庫與表

這個綜合應用中需要使用到兩個表,SQL腳本如下:

腳本:

#創建商品類型表 [] 
CREATE TABLE `category` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '編號',
  `name` varchar(128) NOT NULL COMMENT '類型名稱',
  `parentId` int(11) unsigned DEFAULT NULL COMMENT '父節點編號',
  PRIMARY KEY (`id`),
  UNIQUE KEY `un_category_name` (`name`),
  KEY `fk_category_parentId` (`parentId`),
  CONSTRAINT `fk_category_parentId` FOREIGN KEY (`parentId`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='商品分類';


#創建商品表
drop table if exists goods;  #刪除表

create table if not exists goods
(
    `id` int not null primary key auto_increment comment '編號',
    `title` varchar(128) not null unique key comment '商品名稱',
    `category_id` int unsigned COMMENT '商品類型編號',
    `add_date` TIMESTAMP default now() comment '上貨時間',
    `picture` varchar(64) comment '圖片',
    `state` int default 1 comment '狀態',
    FOREIGN key (`category_id`) REFERENCES category(`id`)
)COMMENT='商品'

#修改表,增加列
ALTER table goods add details text COMMENT '詳細介紹';
ALTER table goods add price DECIMAL(11,2) COMMENT '價格';

#添加記錄,單行
insert into goods(title,category_id,picture,price,details,state) 
VALUES('魅族魅藍note1 ',4,'pic(1).jpg',999,'好手機',default);

#添加記錄,多行
insert into goods(title,category_id,picture,price,details) 
select '魅族魅藍note2',4,'pic(2).jpg',889,'好手機' UNION
select 'iphone X',4,'pic(3).jpg',5889,'好手機' UNION
select '龍蝦',1,'pic(4).jpg',9.85,'好吃' 

#查詢
select * from goods

#備份

SELECT
goods.id,
goods.title,
goods.category_id,
goods.add_date,
goods.picture,
goods.state,
goods.details,
goods.price
FROM
goods

select SYSDATE();
SELECT now();


#11 mssql不支持limit語句,是非常遺憾的,只能用top 取代limt 0,N,row_number() over()函數取代limit N,M

limit是mysql的語法
select * from table limit m,n
其中m是指記錄開始的index,從0開始,表示第一條記錄
n是指從第m+1條開始,取n條。
select * from tablename limit 2,4
即取出第3條至第6條,4條記錄


select * from goods LIMIT 5,3;

select * from goods LIMIT 0,3;

#相當於 select * from goods limit 0,5
select * from goods limit 5,-1


select * from goods limit 2,(select count(*)-2 from goods)


#index 1  第幾頁,頁號 
#size  3  每頁記錄數


skip=(index-1)*size, take=size

1 0,3
2 3,3
3 6,3
4 9,3 

select * from goods 


insert into goods(
goods.title,
goods.category_id,
goods.picture,
goods.state,
goods.details,
goods.price)
SELECT
CONCAT(title,'_',id*8),
id%4+1,
CONCAT('pic(',id,'.jpg'),
id%2,
CONCAT('詳細:,非常好,給你點',id,'個贊'),
goods.price+id*8
FROM
goods



select CONCAT('a','b','c');


#枚舉類型
ENUM是枚舉類型,它雖然只能保存一個值,卻能夠處理多達65535個預定義的值。下面是我寫的一個mysql語句


drop table student
CREATE TABLE student(
id INT(11) PRIMARY key auto_increment,
name VARCHAR(10) not null,
sex ENUM('boy','girl','secret') DEFAULT 'secret',
addDate timestamp DEFAULT now(),
)ENGINE=INNODB

表的數據結構是:

如果sex列中插入了除bor,girl,secret之外的其它字符,則視為空字符串


insert into student(name,sex) values('tom','boy');
select * from student;


insert into student(name,sex) values('tom','male');
insert into student(name,sex) values('tom','female');

insert into student(name,sex) values('tom',DEFAULT);

#添加記錄
insert into student set name='rose',sex='girl'
insert into student(name,sex) values ('jack','boy'),('lili','girl'),('candy',default)


select now();
select SYSDATE();
select CURRENT_DATE
select CURRENT_TIMESTAMP
select cur_date()

#MicroSoft SQL Server


select DISTINCT details from goods;

BEGIN
declare @cnt INTEGER;
set @cnt:=100;
select @cnt;
end

begin
declare cnts int;
end

begin
 delimeterDECLARE xname VARCHAR(5) DEFAULT 'bob';
 DECLARE newname VARCHAR(5);
 DECLARE xid INT;
end;

begin
  declare @cnts int;
  call ups_getCntByPrice 1000,@cnts out;
end;

    delimiter ;
BEGIN
  declare @cnts int;
end;

declare
declare var1 int default 0;
end;





select `add`(100,100);
select title,`add`(price,100) from goods;

select now();

select Md5(Md5(輸入))=='003d712c491c59a86b7ad2207892c704';

select Md5('xx520');


select max(price) into @maxprice from goods;
select @maxprice

set @maxprice:=999;
select @maxprice;
View Code

 查詢結果:

1.4、創建商品實體(Bean)

獲得表的定義信息(DDL):

根據DDL創建類,先新建一個包:

 創建一個實體類:

 右鍵Generate(生成)屬性與重寫toString方法,快捷鍵是:alt+insert

 

完成的實體類如下:

package com.zhangguo.mall.entities;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 商品實體
 */
public class Goods {

    /**編號*/
    private int id;
    /**商品名稱*/
    private String title;
    /**商品類型編號*/
    private int category_id;
    /**上貨時間*/
    private Date add_date;
    /**圖片*/
    private String picture;
    /**狀態*/
    private int state;
    /**詳細介紹*/
    private String details;
    /**價格*/
    private BigDecimal price;

    public int getId() {
        return id;
    }

    public Goods setId(int id) {
        this.id = id;
        return this;
    }

    public String getTitle() {
        return title;
    }

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

    public int getCategory_id() {
        return category_id;
    }

    public Goods setCategory_id(int category_id) {
        this.category_id = category_id;
        return this;
    }

    public Date getAdd_date() {
        return add_date;
    }

    public Goods setAdd_date(Date add_date) {
        this.add_date = add_date;
        return this;
    }

    public String getPicture() {
        return picture;
    }

    public Goods setPicture(String picture) {
        this.picture = picture;
        return this;
    }

    public int getState() {
        return state;
    }

    public Goods setState(int state) {
        this.state = state;
        return this;
    }

    public String getDetails() {
        return details;
    }

    public Goods setDetails(String details) {
        this.details = details;
        return this;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public Goods setPrice(BigDecimal price) {
        this.price = price;
        return this;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", category_id=" + category_id +
                ", add_date=" + add_date +
                ", picture='" + picture + '\'' +
                ", state=" + state +
                ", details='" + details + '\'' +
                ", price=" + price +
                '}';
    }
}
View Code

1.5、創建工具層(Utils)

封裝常用的輔助工具包,如JDBC操作、JSON操作等

JDBCUtils完成數據訪問:

package com.zhangguo.mall.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCUtils {

    public static String DRIVER = "com.mysql.jdbc.Driver";
    public static String URL = "jdbc:mysql://localhost:3306/nfmall?useUnicode=true&characterEncoding=UTF-8";
    public static String USER_NAME = "root";
    public static String PASSWORD = "uchr@123";

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private JDBCUtils() {

    }

    /**
     * Get connection
     * 獲得連接對象
     * @return
     */
    public static Connection getconnnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     * Close connection
     * 關閉連接
     * @param rs
     * @param st
     * @param con
     */
    public static void close(ResultSet rs, Statement st, Connection con) {
        try {
            try {
                if (rs != null) {
                    rs.close();
                }
            } finally {
                try {
                    if (st != null) {
                        st.close();
                    }
                } finally {
                    if (con != null)
                        con.close();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Close connection
     * 
     * @param rs
     */
    public static void close(ResultSet rs) {
        Statement st = null;
        Connection con = null;
        try {
            try {
                if (rs != null) {
                    st = rs.getStatement();
                    rs.close();
                }
            } finally {
                try {
                    if (st != null) {
                        con = st.getConnection();
                        st.close();
                    }
                } finally {
                    if (con != null) {
                        con.close();
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Close connection
     * 
     * @param st
     * @param con
     */
    public static void close(Statement st, Connection con) {
        try {
            try {
                if (st != null) {
                    st.close();
                }
            } finally {
                if (con != null)
                    con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * insert/update/delete
     * 執行增刪改
     * @param sql
     * @param args
     * @return
     */
    public static int update(String sql, Object... args) {
        int result = 0;
        Connection con = getconnnection();
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(ps, con);
        }

        return result;
    }

    /**
     * query, because need to manually close the resource, so not recommended
     * for use it
     * 查詢,根據sql與參數 返回 結果集
     * @param sql
     * @param args
     * @return ResultSet
     */
    public static ResultSet query(String sql, Object... args) {
        ResultSet result = null;
        Connection con = getconnnection();
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            result = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Query a single record
     * 
     * @param sql
     * @param args
     * @return Map<String,Object>
     */
    public static Map<String, Object> queryForMap(String sql, Object... args) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String, Object>> list = queryForList(sql, args);
        if (list.size() > 0) {
            result = list.get(0);
        }
        return result;
    }

    /**
     * Query a single record
     * 返回強類型的單個對象
     * @param sql
     * @param args
     * @return <T>
     */
    public static <T> T queryForObject(String sql, Class<T> clz, Object... args) {
        T result = null;
        List<T> list = queryForList(sql, clz, args);
        if (list.size() > 0) {
            result = list.get(0);
        }
        return result;
    }

    /**
     * Query a single record
     * 
     * @param sql
     * @param args
     * @return List<Map<String,Object>>
     */
    public static List<Map<String, Object>> queryForList(String sql, Object... args) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        Connection con = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            con = getconnnection();
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    map.put(rsmd.getColumnLabel(i), rs.getObject(i));
                }
                result.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, con);
        }
        return result;
    }

    /**
     * Query a single record
     * 查詢,返回 一個強類型的集合
     * @param sql
     * @param args
     * @return List<T>
     */
    public static <T> List<T> queryForList(String sql, Class<T> clz, Object... args) {
        List<T> result = new ArrayList<T>();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = getconnnection();
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                T obj = clz.newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = rsmd.getColumnName(i);
                    String methodName = "set" + columnName.substring(0, 1).toUpperCase()
                            + columnName.substring(1, columnName.length());
                    Method method[] = clz.getMethods();
                    for (Method meth : method) {
                        if (methodName.equals(meth.getName())) {
                            meth.invoke(obj, rs.getObject(i));
                        }
                    }
                }
                result.add(obj);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, con);
        }
        return result;
    }
}
View Code

1.6、創建商品的數據訪問層(DAO) 

初步完成的Dao,代碼如下

package com.zhangguo.mall.dao;

import com.zhangguo.mall.entities.Goods;
import com.zhangguo.mall.utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**商品數據訪問*/
public class GoodsDao {
    /**獲得所有商品*/
    public List<Goods> getAllGoods(){
        //要執行的sql
        String sql="SELECT\n" +
                "goods.id,\n" +
                "goods.title,\n" +
                "goods.category_id,\n" +
                "goods.add_date,\n" +
                "goods.picture,\n" +
                "goods.state,\n" +
                "goods.details,\n" +
                "goods.price\n" +
                "FROM\n" +
                "goods";
        //結果集
        ResultSet rs=null;
        //將要返回的集合
        List<Goods> entities=new ArrayList<>();
        try{
            //通過工具類的query方法獲得結果集,執行查詢
            rs=JDBCUtils.query(sql);
            //通過游標獲得單行數據
            while (rs.next()){
                //實例化單個商品對象
                Goods entity=new Goods();
                //設置實體的屬性值,從當前行中獲得數據
                entity.setId(rs.getInt("id"));
                entity.setTitle(rs.getString("title"));
                entity.setCategory_id(rs.getInt("category_id"));
                entity.setAdd_date(rs.getDate("add_date"));
                entity.setPicture(rs.getString("picture"));
                entity.setState(rs.getInt("state"));
                entity.setDetails(rs.getString("details"));
                entity.setPrice(rs.getBigDecimal("price"));
                //將實體添加到集合中
                entities.add(entity);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            //確保可以關閉對象
            JDBCUtils.close(rs);
        }
        //返回結果
        return entities;
    }

    public static void main(String[] args) {
        GoodsDao dao=new GoodsDao();
        System.out.println(dao.getAllGoods());
    }
}
View Code

此時的項目結構與通過main方法測試的結果:

 

1.7、JUnit單元測試

JUnit是一個Java語言的單元測試框架。它由Kent Beck和Erich Gamma建立,逐漸成為源於Kent Beck的sUnit的xUnit家族中最為成功的一個JUnit有它自己的JUnit擴展生態圈。多數Java的開發環境都已經集成了JUnit作為單元測試的工具。

官網:https://junit.org/

Junit 測試也是程序員測試,即所謂的白盒測試,它需要程序員知道被測試的代碼如何完成功能,以及完成什么樣的功能

我們知道 Junit 是一個單元測試框架,那么使用 Junit 能讓我們快速的完成單元測試。

通常我們寫完代碼想要測試這段代碼的正確性,那么必須新建一個類,然后創建一個 main() 方法,然后編寫測試代碼。如果需要測試的代碼很多呢?那么要么就會建很多main() 方法來測試,要么將其全部寫在一個 main() 方法里面。這也會大大的增加測試的復雜度,降低程序員的測試積極性。而 Junit 能很好的解決這個問題,簡化單元測試,寫一點測一點,在編寫以后的代碼中如果發現問題可以較快的追蹤到問題的原因,減小回歸錯誤的糾錯難度。

1.7.1、常用注解

1.@Test: 測試方法

    a)(expected=XXException.class)如果程序的異常和XXException.class一樣,則測試通過

    b)(timeout=100)如果程序的執行能在100毫秒之內完成,則測試通過

2.@Ignore: 被忽略的測試方法:加上之后,暫時不運行此段代碼

3.@Before: 每一個測試方法之前運行

4.@After: 每一個測試方法之后運行

5.@BeforeClass: 方法必須必須要是靜態方法(static 聲明),所有測試開始之前運行,注意區分before,是所有測試方法

6.@AfterClass: 方法必須要是靜態方法(static 聲明),所有測試結束之后運行,注意區分 @After

1.7.2、編寫測試類的注意事項 

①測試方法上必須使用@Test進行修飾

②測試方法必須使用public void 進行修飾,不能帶任何的參數

③新建一個源代碼目錄來存放我們的測試代碼,即將測試代碼和項目業務代碼分開

④測試類所在的包名應該和被測試類所在的包名保持一致

⑤測試單元中的每個方法必須可以獨立測試,測試方法間不能有任何的依賴

⑥測試類使用Test作為類名的后綴(不是必須)

⑦測試方法使用test作為方法名的前綴(不是必須)

 1.7.3、使用Junit

添加junit的依賴包:

 在需要測試的代碼中右鍵->generate->JUnit Test->對應版本

編寫測試代碼,如下所示:

需要測試的類:

package com.zhangguo.mall.utils;

public class MathUtils {
    public int add(int a, int b) {
        return a + b;
    }

    public int sub(int a, int b) {
        return a - b;
    }

    public int div(int a, int b) {
        if (b == 0) {
            throw new java.lang.ArithmeticException();
        }
        return a / b;
    }

    public int mut(int a, int b) {
        return a * b;
    }
}

測試類:

package test.com.zhangguo.mall.utils;

import com.zhangguo.mall.utils.MathUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;

/**
 * MathUtils Tester.
 *
 * @author <Authors name>
 * @version 1.0
 * @since <pre>09/05/2018</pre>
 */
public class MathUtilsTest {

    MathUtils mathUtils=null;
    @Before  //每個測試方法運行前都會執行的方法
    public void before() throws Exception {
        mathUtils=new MathUtils();
    }

    @After  //每個測試方法運行后都會執行的方法
    public void after() throws Exception {

    }

    /**
     * Method: add(int a, int b)
     */
    @Test  //被測試的方法
    public void testAdd() throws Exception {
        int result=mathUtils.add(100,100);
        //斷言
        Assert.assertEquals(300,result);
    }

    /**
     * Method: sub(int a, int b)
     */
    @Test
    public void testSub() throws Exception {

    }

    /**
     * Method: div(int a, int b)
     */
    @Test(expected = java.lang.ArithmeticException.class)
    public void testDiv() throws Exception {
        int result=mathUtils.div(100,0);
    }

    /**
     * Method: mut(int a, int b)
     */
    @Test
    public void testMut() throws Exception {
//TODO: Test goes here... 
    }


} 
View Code

運行所有測試方法

 運行單個測試方法

 測試dao,沒有問題

1.8、控制器

package com.zhangguo.mall.controller;

import com.zhangguo.mall.dao.GoodsDao;
import com.zhangguo.mall.entities.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/GoodsServlet")
public class GoodsServlet extends HttpServlet {
    GoodsDao goodsDao;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置編碼
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        //請求類型
        String action = request.getParameter("action");

        goodsDao=new GoodsDao();
        //如果是列表
        if(action.equals("list")){
            //獲得所有商品
            List<Goods> goods=goodsDao.getAllGoods();
            //附加數據,傳遞給視圖
            request.setAttribute("goods",goods);

            //轉發到顯示頁面
            request.getRequestDispatcher("WEB-INF/views/goods/list.jsp").forward(request,response);

        }else{
            response.getWriter().write("action不能為空");
        }

        response.getWriter().write(new Date().toString());

    }
}
View Code

結構:

1.9、表示層

商品展示頁面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>商品管理</title>
</head>
<body>
<h2>商品管理</h2>
<div>
    <table width="100%" border="1">
        <tr>
            <th>
                序號
            </th>
            <th>
                編號
            </th>
            <th>
                名稱
            </th>
            <th>
                價格
            </th>
            <th>
                日期
            </th>
            <th>
                狀態
            </th>
        </tr>
        <c:forEach items="${goods}" var="entity" varStatus="state">
            <tr>
                <td>
                        ${state.index+1}
                </td>
                <td>
                        ${entity.id}
                </td>
                <td>
                        ${entity.title}
                </td>
                <td>
                        ${entity.price}
                </td>
                <td>
                        ${entity.add_date}
                </td>
                <td>
                        ${entity.state}
                </td>
            </tr>
        </c:forEach>
    </table>
</div>
</body>
</html>
View Code

 

結構:

 

運行結果:

 

1.10、分頁

1.10.1、后台

數據訪問:

package com.zhangguo.mall.dao;

import com.zhangguo.mall.entities.Goods;
import com.zhangguo.mall.utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**商品數據訪問*/
public class GoodsDao {
    /**獲得所有商品*/
    public List<Goods> getAllGoods(){
        //要執行的sql
        String sql="SELECT\n" +
                "goods.id,\n" +
                "goods.title,\n" +
                "goods.category_id,\n" +
                "goods.add_date,\n" +
                "goods.picture,\n" +
                "goods.state,\n" +
                "goods.details,\n" +
                "goods.price\n" +
                "FROM\n" +
                "goods";
        //結果集
        ResultSet rs=null;
        //將要返回的集合
        List<Goods> entities=new ArrayList<>();
        try{
            //通過工具類的query方法獲得結果集,執行查詢
            rs=JDBCUtils.query(sql);
            //通過游標獲得單行數據
            while (rs.next()){
                //實例化單個商品對象
                Goods entity=new Goods();
                //設置實體的屬性值,從當前行中獲得數據
                entity.setId(rs.getInt("id"));
                entity.setTitle(rs.getString("title"));
                entity.setCategory_id(rs.getInt("category_id"));
                entity.setAdd_date(rs.getDate("add_date"));
                entity.setPicture(rs.getString("picture"));
                entity.setState(rs.getInt("state"));
                entity.setDetails(rs.getString("details"));
                entity.setPrice(rs.getBigDecimal("price"));
                //將實體添加到集合中
                entities.add(entity);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            //確保可以關閉對象
            JDBCUtils.close(rs);
        }
        //返回結果
        return entities;
    }


    /**獲得總記錄數*/
    public int getCount(){
        String sql="select count(*) as count from goods";
        Map<String,Object> result=JDBCUtils.queryForMap(sql);
        return Integer.parseInt(result.get("count")+"");
    }


    /**獲得所有商品*/
    public List<Goods> getGoodsPager(int pageNo,int size){

        //要跳過多少記錄,從0開始
        int skip=(pageNo)*size;
        //獲得多少條記錄
        int take=size;

        //要執行的sql
        String sql="SELECT\n" +
                "goods.id,\n" +
                "goods.title,\n" +
                "goods.category_id,\n" +
                "goods.add_date,\n" +
                "goods.picture,\n" +
                "goods.state,\n" +
                "goods.details,\n" +
                "goods.price\n" +
                "FROM\n" +
                "goods limit ?,?";
        //結果集
        ResultSet rs=null;
        //將要返回的集合
        List<Goods> entities=new ArrayList<>();
        try{
            //通過工具類的query方法獲得結果集,執行查詢
            rs=JDBCUtils.query(sql,skip,take);
            //通過游標獲得單行數據
            while (rs.next()){
                //實例化單個商品對象
                Goods entity=new Goods();
                //設置實體的屬性值,從當前行中獲得數據
                entity.setId(rs.getInt("id"));
                entity.setTitle(rs.getString("title"));
                entity.setCategory_id(rs.getInt("category_id"));
                entity.setAdd_date(rs.getDate("add_date"));
                entity.setPicture(rs.getString("picture"));
                entity.setState(rs.getInt("state"));
                entity.setDetails(rs.getString("details"));
                entity.setPrice(rs.getBigDecimal("price"));
                //將實體添加到集合中
                entities.add(entity);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            //確保可以關閉對象
            JDBCUtils.close(rs);
        }
        //返回結果
        return entities;
    }

}
View Code

控制器:

package com.zhangguo.mall.controller;

import com.zhangguo.mall.dao.GoodsDao;
import com.zhangguo.mall.entities.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/GoodsServlet")
public class GoodsServlet extends HttpServlet {
    GoodsDao goodsDao;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置編碼
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        //請求類型
        String action = request.getParameter("action");

        goodsDao=new GoodsDao();
        //如果是列表
        if(action.equals("list")){

            String pageNoStr=request.getParameter("pageNo");
            String pageSizeStr=request.getParameter("pageSize");

            if(pageNoStr!=null&&pageSizeStr!=null){
                int pageNo =Integer.parseInt(pageNoStr);
                int pageSize =Integer.parseInt(pageSizeStr);
                //獲得所有商品
                List<Goods> goods=goodsDao.getGoodsPager(pageNo,pageSize);
                //附加數據,傳遞給視圖
                request.setAttribute("goods",goods);
                //總記錄數
                request.setAttribute("count",goodsDao.getCount());
                //當前頁號
                request.setAttribute("pageNo",pageNo);
                //需要首次加載
                request.setAttribute("load_first_page","false");
            }else{
                //需要首次加載
                request.setAttribute("load_first_page","true");
            }
            //轉發到顯示頁面
            request.getRequestDispatcher("WEB-INF/views/goods/list.jsp").forward(request,response);



        }else{
            response.getWriter().write("action不能為空");
        }

        response.getWriter().write(new Date().toString());

    }
}


            /*
            //默認為第1頁
            int pageNo=1;
            //如果參數中存在頁號,則取出
            String pageNoStr=request.getParameter("pageNo");
            if(pageNoStr!=null&&!pageNoStr.equals("")) {
                pageNo = Integer.parseInt(pageNoStr);
            }

            //默認每頁條記錄
            int pageSize =5;
            String pageSizeStr=request.getParameter("pageSize");
            if(pageSizeStr!=null&&!pageSizeStr.equals("")) {
                pageSize = Integer.parseInt(pageSizeStr);
            }
            */
View Code

單元測試:

package test.com.zhangguo.mall.dao;

import com.zhangguo.mall.dao.GoodsDao;
import com.zhangguo.mall.entities.Goods;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;

import java.util.List;

/**
 * GoodsDao Tester.
 *
 * @author <Authors name>
 * @version 1.0
 * @since <pre>09/07/2018</pre>
 */
public class GoodsDaoTest {

    GoodsDao dao=null;
    @Before
    public void before() throws Exception {
        dao=new GoodsDao();
    }

    @After
    public void after() throws Exception {
    }

    /**
     * Method: getGetCount()
     */
    @Test
    public void testGetCount() throws Exception {
        Assert.assertEquals(35,dao.getCount());
    }

    /**
     * Method: getAllGoods()
     */
    @Test
    public void testGetAllGoods() throws Exception {

    }

    /**
     * Method: getGoodsPager(int pageNo, int size)
     */
    @Test
    public void testGetGoodsPager() throws Exception {
        List<Goods> list=dao.getGoodsPager(1,10);
        System.out.println(list);
        Assert.assertEquals(10,list.size());
    }


} 
View Code

結果:

1.10.2、前台

代碼:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>商品管理</title>
</head>
<body>
<h2>商品管理</h2>
<div>
    <table width="100%" border="1">
        <tr>
            <th>
                序號
            </th>
            <th>
                編號
            </th>
            <th>
                名稱
            </th>
            <th>
                價格
            </th>
            <th>
                日期
            </th>
            <th>
                狀態
            </th>
        </tr>
        <c:forEach items="${goods}" var="entity" varStatus="state">
            <tr>
                <td>
                        ${state.index+1}
                </td>
                <td>
                        ${entity.id}
                </td>
                <td>
                        ${entity.title}
                </td>
                <td>
                        ${entity.price}
                </td>
                <td>
                        ${entity.add_date}
                </td>
                <td>
                        ${entity.state}
                </td>
            </tr>
        </c:forEach>
    </table>
    <div id="pagination"></div>
</div>
<link rel="stylesheet" href="../../../js/pagination22/pagination.css" type="text/css"/>
<script src="../../../js/jquery/jquery-1.11.3.min.js"></script>
<script src="../../../js/pagination22/jquery.pagination2.2.js"></script>

<script>
    var load_first_page=<c:out value="${load_first_page}"></c:out>;
    var pageCount='<c:out value="${count}"></c:out>'||0;
    var pageSize=5;
    var current_page='<c:out value="${pageNo}"></c:out>'||0;
    $("#pagination").pagination(pageCount, {
        items_per_page: pageSize,
        next_text: "下一頁",
        next_show_always: true,
        prev_text: "上一頁",
        prev_show_always: true,
        current_page:current_page,
        num_edge_entries:2,
        load_first_page:load_first_page,   //是否首次加載,是否首次就執行handlePaginationClick
        callback: handlePaginationClick
    });

    function handlePaginationClick(pageNo, pagination_container) {
        location.href="GoodsServlet?action=list&pageNo="+pageNo+"&pageSize="+pageSize;

    }
</script>
</body>
</html>
View Code

結果:

二、使用Servlet+JDBC+MySQL+IDEA+AJAX實現商品管理

2.1、JSON工具類

package com.zhangguo.mall.utils;

import java.text.SimpleDateFormat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {
    /**
     * 序列化成json
     * */
    public static String toJson(Object obj) {
        // 對象映射器
        ObjectMapper mapper = new ObjectMapper();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd HH:mm:ss");
        mapper.setDateFormat(sdf);
        
        String result = null;
        // 序列化user對象為json字符串
        try {
            result = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 反序列化成對象
     * */
    public static <T> T toObject(String json,Class<T> valueType) {
        //對象映射器
        ObjectMapper mapper=new ObjectMapper();
        T result=null;
        try {
            result=mapper.readValue(json,valueType);

        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

測試:

package test.com.zhangguo.mall.utils;

import com.zhangguo.mall.utils.JsonUtils;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;

/**
 * JsonUtils Tester.
 *
 * @author <Authors name>
 * @version 1.0
 * @since <pre>09/10/2018</pre>
 */
public class JsonUtilsTest {

    @Before
    public void before() throws Exception {
    }

    @After
    public void after() throws Exception {
    }

    /**
     * Method: toJson(Object obj)
     */
    @Test
    public void testToJson() throws Exception {
        Student tom=new Student(9001,"湯姆");
        System.out.println(JsonUtils.toJson(tom));
    }

    /**
     * Method: toObject(String json, Class<T> valueType)
     */
    @Test
    public void testToObject() throws Exception {

        String json="{\"id\":9002,\"name\":\"馬力\"}";
        System.out.println(JsonUtils.toObject(json,Student.class));
    }


} 
View Code

結果:

2.2、商品列表服務(提供JSON數據接口)

Servlet:

package com.zhangguo.mall.controller;

import com.zhangguo.mall.dao.GoodsDao;
import com.zhangguo.mall.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/GoodsApi")
public class GoodsApi extends HttpServlet {
    GoodsDao goodsDao;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置編碼
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        //請求類型
        String action = request.getParameter("action");
        
        goodsDao=new GoodsDao();
        //如果是列表
        if(action.equals("list")) {
            //R
            response.getWriter().write(JsonUtils.toJson(goodsDao.getAllGoods()));
        }else{
            response.getWriter().write("action不能為空");
        }
    }
}
View Code

結果:

2.3、使用jQuery+AJAX消費服務

index.html頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>天狗商城</title>

</head>
<body>
<h2>天狗商城</h2>

<table border="1" width="100%" id="tabGoods">
    <tr>
        <th>序號</th>
        <th>編號</th>
        <th>名稱</th>
        <th>價格</th>
        <th>日期</th>
        <th>狀態</th>
        <th>操作</th>
    </tr>

</table>

<script src="js/jquery/jquery-1.11.3.js"></script>
<script>

    var app={
        init:function () {
            app.load();
        },
        load:function () {
            $.ajax({
                url:"GoodsApi?action=list",
                type:"get",
                dataType:"json",
                success:function (data) {

                    for(var i=0;i<data.length;i++){
                        var obj=data[i];
                        var tr=$("<tr/>");

                        $("<td/>").text(i+1).appendTo(tr);
                        $("<td/>").text(obj.id).appendTo(tr);
                        $("<td/>").text(obj.title).appendTo(tr);
                        $("<td/>").text(obj.price).appendTo(tr);
                        $("<td/>").text(obj.add_date).appendTo(tr);
                        $("<td/>").text(obj.state>0?"正常":"凍結").appendTo(tr);

                        $("<td/>").text("刪除").appendTo(tr);

                        $("#tabGoods").append(tr);
                    }

                },
                error:function (xhr, textStatus, errorThrown) {
                    alert("錯誤,"+textStatus+","+errorThrown);
                }
            });
        }
    };

    app.init();

</script>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>天狗商城</title>

</head>
<body>
<h2>天狗商城</h2>

<table border="1" width="100%" id="tabGoods">
    <tr>
        <th>序號</th>
        <th>編號</th>
        <th>名稱</th>
        <th>價格</th>
        <th>日期</th>
        <th>狀態</th>
        <th>操作</th>
    </tr>

</table>

<script src="js/jquery/jquery-1.11.3.js"></script>
<script>

    var app={
        init:function () {
            app.load();
        },
        load:function () {
            $.ajax({
                url:"GoodsApi?action=list",
                type:"get",
                dataType:"json",
                success:function (data) {

                    for(var i=0;i<data.length;i++){
                        var obj=data[i];
                        var tr=$("<tr/>");

                        $("<td/>").text(i+1).appendTo(tr);
                        $("<td/>").text(obj.id).appendTo(tr);
                        $("<td/>").text(obj.title).appendTo(tr);
                        $("<td/>").text(obj.price).appendTo(tr);
                        $("<td/>").text(obj.add_date).appendTo(tr);
                        $("<td/>").text(obj.state>0?"正常":"凍結").appendTo(tr);

                        $("<td/>").text("刪除").appendTo(tr);

                        $("#tabGoods").append(tr);
                    }

                },
                error:function (xhr, textStatus, errorThrown) {
                    alert("錯誤,"+textStatus+","+errorThrown);
                }
            });
        }
    };

    app.init();

</script>
</body>
</html>
View Code

運行結果:

2.4、刪除商品功能

刪除服務:

dao:

package com.zhangguo.mall.dao;

import com.zhangguo.mall.entities.Goods;
import com.zhangguo.mall.utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**商品數據訪問*/
public class GoodsDao {
    /**獲得所有商品*/
    public List<Goods> getAllGoods(){
        //要執行的sql
        String sql="SELECT\n" +
                "goods.id,\n" +
                "goods.title,\n" +
                "goods.category_id,\n" +
                "goods.add_date,\n" +
                "goods.picture,\n" +
                "goods.state,\n" +
                "goods.details,\n" +
                "goods.price\n" +
                "FROM\n" +
                "goods";
        //結果集
        ResultSet rs=null;
        //將要返回的集合
        List<Goods> entities=new ArrayList<>();
        try{
            //通過工具類的query方法獲得結果集,執行查詢
            rs=JDBCUtils.query(sql);
            //通過游標獲得單行數據
            while (rs.next()){
                //實例化單個商品對象
                Goods entity=new Goods();
                //設置實體的屬性值,從當前行中獲得數據
                entity.setId(rs.getInt("id"));
                entity.setTitle(rs.getString("title"));
                entity.setCategory_id(rs.getInt("category_id"));
                entity.setAdd_date(rs.getDate("add_date"));
                entity.setPicture(rs.getString("picture"));
                entity.setState(rs.getInt("state"));
                entity.setDetails(rs.getString("details"));
                entity.setPrice(rs.getBigDecimal("price"));
                //將實體添加到集合中
                entities.add(entity);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            //確保可以關閉對象
            JDBCUtils.close(rs);
        }
        //返回結果
        return entities;
    }


    /**獲得總記錄數*/
    public int getCount(){
        String sql="select count(*) as count from goods";
        Map<String,Object> result=JDBCUtils.queryForMap(sql);
        return Integer.parseInt(result.get("count")+"");
    }


    /**獲得所有商品*/
    public List<Goods> getGoodsPager(int pageNo,int size){

        //要跳過多少記錄,從0開始
        int skip=(pageNo)*size;
        //獲得多少條記錄
        int take=size;

        //要執行的sql
        String sql="SELECT\n" +
                "goods.id,\n" +
                "goods.title,\n" +
                "goods.category_id,\n" +
                "goods.add_date,\n" +
                "goods.picture,\n" +
                "goods.state,\n" +
                "goods.details,\n" +
                "goods.price\n" +
                "FROM\n" +
                "goods limit ?,?";
        //結果集
        ResultSet rs=null;
        //將要返回的集合
        List<Goods> entities=new ArrayList<>();
        try{
            //通過工具類的query方法獲得結果集,執行查詢
            rs=JDBCUtils.query(sql,skip,take);
            //通過游標獲得單行數據
            while (rs.next()){
                //實例化單個商品對象
                Goods entity=new Goods();
                //設置實體的屬性值,從當前行中獲得數據
                entity.setId(rs.getInt("id"));
                entity.setTitle(rs.getString("title"));
                entity.setCategory_id(rs.getInt("category_id"));
                entity.setAdd_date(rs.getDate("add_date"));
                entity.setPicture(rs.getString("picture"));
                entity.setState(rs.getInt("state"));
                entity.setDetails(rs.getString("details"));
                entity.setPrice(rs.getBigDecimal("price"));
                //將實體添加到集合中
                entities.add(entity);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            //確保可以關閉對象
            JDBCUtils.close(rs);
        }
        //返回結果
        return entities;
    }

    /**根據編號刪除*/
    public int delete(int id){
        return JDBCUtils.update("delete from goods where id=?",id);
    }

    /**添加*/
    public int add(Goods entity){
        String sql="insert into goods(title,category_id,picture,price,details,state,add_date) \n" +
                "VALUES(?,3,'pic(1).jpg',?,?,default,?);";
        return JDBCUtils.update(sql,entity.getTitle(),entity.getPrice(),entity.getDetails(),entity.getAdd_date());
    }
}
View Cod

controller:

package com.zhangguo.mall.controller;

import com.zhangguo.mall.dao.GoodsDao;
import com.zhangguo.mall.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;

@WebServlet("/GoodsApi")
public class GoodsApi extends HttpServlet {
    GoodsDao goodsDao;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    PrintWriter write;
    public void out(String outString){
        try {
            write.write(outString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置編碼
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        write=response.getWriter();

        //請求類型
        String action = request.getParameter("action");

        goodsDao=new GoodsDao();
        //如果是列表
        if(action.equals("list")) {

            //R r=R.ok(goodsDao.getAllGoods()).put("a",100).put("b",200).put("dateTime",new Date());
            out(R.ok(goodsDao.getAllGoods()).Json());
        }
        else if(action.equals("del")) {
            int id=Integer.parseInt(request.getParameter("id"));
            if(goodsDao.delete(id)>0) {
                out(R.ok().Json());
            }else{
                out(R.error().Json());
            }
        }
        else{
            out(R.error("action不能為空").Json());
        }
    }
}

/**封裝返回結果*/
class R extends HashMap{
    public R(int code, String msg, Object data) {
        this.put("code",code);
        this.put("msg",msg);
        this.put("data",data);
    }

    public String Json(){
        return JsonUtils.toJson(this);
    }

    public R put(Object key, Object value) {
        super.put(key, value);
        return this;
    }

    public static R ok(String msg, Object data){
        return new R(1,msg,data);
    }
    public static R ok(Object data){
        return new R(1,"請求成功!",data);
    }
    public static R ok(){
        return new R(1,"請求成功!",null);
    }

    public static R error(String msg, Object data){
        return new R(0,msg,data);
    }
    public static R error(String msg){
        return new R(0,msg,null);
    }
    public static R error(){
        return new R(0,"請求失敗!",null);
    }

}
View Code

UI調用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>天狗商城</title>

</head>
<body>
<h2>天狗商城</h2>

<table border="1" width="100%" id="tabGoods">
    <tr>
        <th>序號</th>
        <th>編號</th>
        <th>名稱</th>
        <th>價格</th>
        <th>日期</th>
        <th>狀態</th>
        <th>操作</th>
    </tr>

</table>

<form id="formGoods">
<fieldset>
    <legend>商品信息</legend>
    <p>
        <label for="title">名稱:</label>
        <input id="title" name="title" type="text"/>
    </p>
    <p>
        <label for="price">價格:</label>
        <input id="price" name="price" type="text"/>
    </p>
    <p>
        <label for="add_date">日期:</label>
        <input id="add_date" name="add_date" type="text"/>
    </p>
    <p>
        <label for="details">詳細:</label>
        <textarea id="details" name="details" rows="5" cols="50"></textarea>
    </p>
    <p>
        <button>添加</button>
    </p>
</fieldset>
</form>


<script src="js/jquery/jquery-1.11.3.js"></script>
<script>

    var app={
        init:function () {
            app.load();
        },
        load:function () {
            $.ajax({
                url:"GoodsApi?action=list",
                type:"get",
                dataType:"json",
                success:function (data) {
                    if(data.code==1) {
                        for (var i = 0; i < data.data.length; i++) {
                            var obj = data.data[i];
                            var tr = $("<tr/>").data("obj",obj);

                            $("<td/>").text(i + 1).appendTo(tr);
                            $("<td/>").text(obj.id).appendTo(tr);
                            $("<td/>").text(obj.title).appendTo(tr);
                            $("<td/>").text(obj.price).appendTo(tr);
                            $("<td/>").text(obj.add_date).appendTo(tr);
                            $("<td/>").text(obj.state > 0 ? "正常" : "凍結").appendTo(tr);

                            var del=$("<a/>").html("刪除").prop("href","#").addClass("del");
                            $("<td/>").append(del).appendTo(tr);

                            $("#tabGoods").append(tr);
                        }
                        app.del();
                    }

                },
                error:function (xhr, textStatus, errorThrown) {
                    alert("錯誤,"+textStatus+","+errorThrown);
                }
            });
        },
        del:function () {
            $(".del").click(function () {
               if(confirm("您確定要刪除嗎?")){
                   var obj=$(this).closest("tr").data("obj");
                   var that=this;

                   $.ajax({
                       url:"GoodsApi?action=del",
                       type:"get",
                       data:{"id":obj.id},
                       dataType:"json",
                       success:function (data) {
                           if(data.code==1) {
                               $(that).closest("tr").remove();  //刪除當前行
                           }
                           alert(data.msg);
                       },
                       error:function (xhr, textStatus, errorThrown) {
                           alert("錯誤,"+textStatus+","+errorThrown);
                       }
                   });

               }
                return false;
            });
        }
    };

    app.init();

</script>
</body>
</html>
View Code

運行結果:

2.5、新增商品功能

dao數據訪問:

    /**添加*/
    public int add(Goods entity){
        String sql="insert into goods(title,category_id,picture,price,details,state,add_date) \n" +
                "VALUES(?,3,'pic(1).jpg',?,?,default,?);";
        return JDBCUtils.update(sql,entity.getTitle(),entity.getPrice(),entity.getDetails(),entity.getAdd_date());
    }

控制器,服務:

package com.zhangguo.mall.controller;

import com.zhangguo.mall.dao.GoodsDao;
import com.zhangguo.mall.entities.Goods;
import com.zhangguo.mall.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@WebServlet("/GoodsApi")
public class GoodsApi extends HttpServlet {
    GoodsDao goodsDao;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    PrintWriter write;
    public void out(String outString){
        try {
            write.write(outString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置編碼
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        write=response.getWriter();

        //請求類型
        String action = request.getParameter("action");

        goodsDao=new GoodsDao();
        //如果是列表
        if(action.equals("list")) {

            //R r=R.ok(goodsDao.getAllGoods()).put("a",100).put("b",200).put("dateTime",new Date());
            out(R.ok(goodsDao.getAllGoods()).Json());
        }
        else if(action.equals("del")) {
            int id=Integer.parseInt(request.getParameter("id"));
            if(goodsDao.delete(id)>0) {
                out(R.ok().Json());
            }else{
                out(R.error().Json());
            }
        }
        else if(action.equals("add")) {
            Goods entity=new Goods();

            //從客戶端獲得提交的參數
            String title=request.getParameter("title");
            String price=request.getParameter("price");
            String add_date=request.getParameter("add_date");
            String details=request.getParameter("details");

            entity.setTitle(title);
            //先將字符串類型的價格轉換成double類型,再轉換成定點小數
            entity.setPrice(new BigDecimal(Double.parseDouble(price)));


            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            try {
                entity.setAdd_date(sdf.parse(add_date));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            entity.setDetails(details);

            if(goodsDao.add(entity)>0) {
                out(R.ok().Json());
            }else{
                out(R.error().Json());
            }
        }
        else{
            out(R.error("action不能為空").Json());
        }
    }
}

/**封裝返回結果*/
class R extends HashMap{
    public R(int code, String msg, Object data) {
        this.put("code",code);
        this.put("msg",msg);
        this.put("data",data);
    }

    public String Json(){
        return JsonUtils.toJson(this);
    }

    public R put(Object key, Object value) {
        super.put(key, value);
        return this;
    }

    public static R ok(String msg, Object data){
        return new R(1,msg,data);
    }
    public static R ok(Object data){
        return new R(1,"請求成功!",data);
    }
    public static R ok(){
        return new R(1,"請求成功!",null);
    }

    public static R error(String msg, Object data){
        return new R(0,msg,data);
    }
    public static R error(String msg){
        return new R(0,msg,null);
    }
    public static R error(){
        return new R(0,"請求失敗!",null);
    }

}
View Code

前端頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>天狗商城</title>

</head>
<body>
<h2>天狗商城</h2>

<table border="1" width="100%" id="tabGoods">
    <tr>
        <th>序號</th>
        <th>編號</th>
        <th>名稱</th>
        <th>價格</th>
        <th>日期</th>
        <th>狀態</th>
        <th>操作</th>
    </tr>

</table>

<form id="formGoods">
<fieldset>
    <legend>商品信息</legend>
    <p>
        <label for="title">名稱:</label>
        <input id="title" name="title" type="text"/>
    </p>
    <p>
        <label for="price">價格:</label>
        <input id="price" name="price" type="text"/>
    </p>
    <p>
        <label for="add_date">日期:</label>
        <input id="add_date" name="add_date" type="date"/>
    </p>
    <p>
        <label for="details">詳細:</label>
        <textarea id="details" name="details" rows="5" cols="50"></textarea>
    </p>
    <p>
        <button id="btnAdd" type="button">添加</button>
    </p>
</fieldset>
</form>


<script src="js/jquery/jquery-1.11.3.js"></script>
<script>

    var app={
        init:function () {
            app.load();
            app.bind();
        },
        load:function () {
            $.ajax({
                url:"GoodsApi?action=list",
                type:"get",
                dataType:"json",
                success:function (data) {
                    if(data.code==1) {
                        $("#tabGoods tr:gt(0)").remove();
                        for (var i = 0; i < data.data.length; i++) {
                            var obj = data.data[i];
                            var tr = $("<tr/>").data("obj",obj);

                            $("<td/>").text(i + 1).appendTo(tr);
                            $("<td/>").text(obj.id).appendTo(tr);
                            $("<td/>").text(obj.title).appendTo(tr);
                            $("<td/>").text(obj.price).appendTo(tr);
                            $("<td/>").text(obj.add_date).appendTo(tr);
                            $("<td/>").text(obj.state > 0 ? "正常" : "凍結").appendTo(tr);

                            var del=$("<a/>").html("刪除 ").prop("href","#").addClass("del");

                            var edit=$("<a/>").html(" | 編輯").prop("href","#").addClass("edit");
                            $("<td/>").append(del).append(edit).appendTo(tr);

                            $("#tabGoods").append(tr);
                        }
                        app.del();
                    }

                },
                error:function (xhr, textStatus, errorThrown) {
                    alert("錯誤,"+textStatus+","+errorThrown);
                }
            });
        },
        del:function () {
            $(".del").click(function () {
               if(confirm("您確定要刪除嗎?")){
                   var obj=$(this).closest("tr").data("obj");
                   var that=this;


                   $.ajax({
                       url:"GoodsApi?action=del",
                       type:"get",
                       data:{"id":obj.id},
                       dataType:"json",
                       success:function (data) {
                           if(data.code==1) {
                               $(that).closest("tr").remove();  //刪除當前行
                           }
                           alert(data.msg);
                       },
                       error:function (xhr, textStatus, errorThrown) {
                           alert("錯誤,"+textStatus+","+errorThrown);
                       }
                   });

               }
                return false;
            });
        },
        bind:function () {  //用於綁定事件
            $("#btnAdd").click(function () {
                $.ajax({
                    url:"GoodsApi?action=add",
                    type:"post",
                    data:$("#formGoods").serialize(),
                    dataType:"json",
                    success:function (data) {
                        if(data.code==1) {
                            app.load();
                        }
                        alert(data.msg);
                    },
                    error:function (xhr, textStatus, errorThrown) {
                        alert("錯誤,"+textStatus+","+errorThrown);
                    }
                });

            });

            $("#tabGoods").on("click",".edit",function () {
                var obj=$(this).closest("tr").data("obj");
                var that=this;
                alert(JSON.stringify(obj));
            });
        }
    };

    app.init();

</script>
</body>
</html>
View Code

運行結果:

2.6、編輯商品功能

dao數據訪問:

    /**編輯*/
    public int edit(Goods entity){
        String sql="update goods set title=?,price=?,details=?,add_date=? where id=?";
        return JDBCUtils.update(sql,entity.getTitle(),entity.getPrice(),entity.getDetails(),entity.getAdd_date(),entity.getId());
    }

控制器,服務:

package com.zhangguo.mall.controller;

import com.zhangguo.mall.dao.GoodsDao;
import com.zhangguo.mall.entities.Goods;
import com.zhangguo.mall.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@WebServlet("/GoodsApi")
public class GoodsApi extends HttpServlet {
    GoodsDao goodsDao;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    PrintWriter write;

    public void out(String outString) {
        try {
            write.write(outString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置編碼
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        write = response.getWriter();

        //請求類型
        String action = request.getParameter("action");

        goodsDao = new GoodsDao();
        //如果是列表
        if (action.equals("list")) {

            //R r=R.ok(goodsDao.getAllGoods()).put("a",100).put("b",200).put("dateTime",new Date());
            out(R.ok(goodsDao.getAllGoods()).Json());
        } else if (action.equals("del")) {
            int id = Integer.parseInt(request.getParameter("id"));
            if (goodsDao.delete(id) > 0) {
                out(R.ok().Json());
            } else {
                out(R.error().Json());
            }
        } else if (action.equals("add")) {
            Goods entity = new Goods();

            //從客戶端獲得提交的參數
            String title = request.getParameter("title");
            String price = request.getParameter("price");
            String add_date = request.getParameter("add_date");
            String details = request.getParameter("details");

            entity.setTitle(title);
            //先將字符串類型的價格轉換成double類型,再轉換成定點小數
            entity.setPrice(new BigDecimal(Double.parseDouble(price)));


            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                entity.setAdd_date(sdf.parse(add_date));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            entity.setDetails(details);

            if (goodsDao.add(entity) > 0) {
                out(R.ok().Json());
            } else {
                out(R.error().Json());
            }
        } else if (action.equals("edit")) {
            Goods entity = new Goods();

            //從客戶端獲得提交的參數
            int id = Integer.parseInt(request.getParameter("id"));
            String title = request.getParameter("title");
            String price = request.getParameter("price");
            String add_date = request.getParameter("add_date");
            String details = request.getParameter("details");

            entity.setId(id);
            entity.setTitle(title);
            //先將字符串類型的價格轉換成double類型,再轉換成定點小數
            entity.setPrice(new BigDecimal(Double.parseDouble(price)));


            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                entity.setAdd_date(sdf.parse(add_date));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            entity.setDetails(details);

            if (goodsDao.edit(entity) > 0) {
                out(R.ok().Json());
            } else {
                out(R.error().Json());
            }
        } else {
            out(R.error("action不能為空").Json());
        }
    }
}

/**
 * 封裝返回結果
 */
class R extends HashMap {
    public R(int code, String msg, Object data) {
        this.put("code", code);
        this.put("msg", msg);
        this.put("data", data);
    }

    public String Json() {
        return JsonUtils.toJson(this);
    }

    public R put(Object key, Object value) {
        super.put(key, value);
        return this;
    }

    public static R ok(String msg, Object data) {
        return new R(1, msg, data);
    }

    public static R ok(Object data) {
        return new R(1, "請求成功!", data);
    }

    public static R ok() {
        return new R(1, "請求成功!", null);
    }

    public static R error(String msg, Object data) {
        return new R(0, msg, data);
    }

    public static R error(String msg) {
        return new R(0, msg, null);
    }

    public static R error() {
        return new R(0, "請求失敗!", null);
    }

}
View Code

前端頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>天狗商城</title>

</head>
<body>
<h2>天狗商城</h2>

<table border="1" width="100%" id="tabGoods">
    <tr>
        <th>序號</th>
        <th>編號</th>
        <th>名稱</th>
        <th>價格</th>
        <th>日期</th>
        <th>狀態</th>
        <th>操作</th>
    </tr>

</table>

<form id="formGoods">
<fieldset>
    <legend>商品信息</legend>
    <p>
        <label for="title">名稱:</label>
        <input id="title" name="title" type="text"/>
    </p>
    <p>
        <label for="price">價格:</label>
        <input id="price" name="price" type="text"/>
    </p>
    <p>
        <label for="add_date">日期:</label>
        <input id="add_date" name="add_date" type="date"/>
    </p>
    <p>
        <label for="details">詳細:</label>
        <textarea id="details" name="details" rows="5" cols="50"></textarea>
    </p>
    <p>
        <input id="id" name="id" value="" type="hidden"/>
        <button id="btnAdd" type="button">添加</button>
        <button id="btnEdit" type="button">更新</button>
    </p>
</fieldset>
</form>


<script src="js/jquery/jquery-1.11.3.js"></script>
<script>

    var app={
        init:function () {
            app.load();
            app.bind();
        },
        load:function () {
            $.ajax({
                url:"GoodsApi?action=list",
                type:"get",
                dataType:"json",
                success:function (data) {
                    if(data.code==1) {
                        $("#tabGoods tr:gt(0)").remove();
                        for (var i = 0; i < data.data.length; i++) {
                            var obj = data.data[i];
                            var tr = $("<tr/>").data("obj",obj);

                            $("<td/>").text(i + 1).appendTo(tr);
                            $("<td/>").text(obj.id).appendTo(tr);
                            $("<td/>").text(obj.title).appendTo(tr);
                            $("<td/>").text(obj.price).appendTo(tr);
                            $("<td/>").text(obj.add_date).appendTo(tr);
                            $("<td/>").text(obj.state > 0 ? "正常" : "凍結").appendTo(tr);

                            var del=$("<a/>").html("刪除 ").prop("href","#").addClass("del");

                            var edit=$("<a/>").html(" | 編輯").prop("href","#").addClass("edit");
                            $("<td/>").append(del).append(edit).appendTo(tr);

                            $("#tabGoods").append(tr);
                        }
                        app.del();
                    }

                },
                error:function (xhr, textStatus, errorThrown) {
                    alert("錯誤,"+textStatus+","+errorThrown);
                }
            });
        },
        del:function () {
            $(".del").click(function () {
               if(confirm("您確定要刪除嗎?")){
                   var obj=$(this).closest("tr").data("obj");
                   var that=this;


                   $.ajax({
                       url:"GoodsApi?action=del",
                       type:"get",
                       data:{"id":obj.id},
                       dataType:"json",
                       success:function (data) {
                           if(data.code==1) {
                               $(that).closest("tr").remove();  //刪除當前行
                           }
                           alert(data.msg);
                       },
                       error:function (xhr, textStatus, errorThrown) {
                           alert("錯誤,"+textStatus+","+errorThrown);
                       }
                   });

               }
                return false;
            });
        },
        bind:function () {  //用於綁定事件
            $("#btnAdd").click(function () {
                $.ajax({
                    url:"GoodsApi?action=add",
                    type:"post",
                    data:$("#formGoods").serialize(),
                    dataType:"json",
                    success:function (data) {
                        if(data.code==1) {
                            app.load();
                        }
                        alert(data.msg);
                    },
                    error:function (xhr, textStatus, errorThrown) {
                        alert("錯誤,"+textStatus+","+errorThrown);
                    }
                });

            });

            $("#tabGoods").on("click",".edit",function () {
                var obj=$(this).closest("tr").data("obj");
                var that=this;
                //alert(JSON.stringify(obj));
                $("#id").val(obj.id);
                $("#title").val(obj.title);
                $("#price").val(obj.price);
                $("#add_date").val(obj.add_date);
                $("#details").val(obj.details);

                return false;
            });

            $("#btnEdit").click(function () {
                $.ajax({
                    url:"GoodsApi?action=edit",
                    type:"post",
                    data:$("#formGoods").serialize(),
                    dataType:"json",
                    success:function (data) {
                        if(data.code==1) {
                            app.load();
                        }
                        alert(data.msg);
                    },
                    error:function (xhr, textStatus, errorThrown) {
                        alert("錯誤,"+textStatus+","+errorThrown);
                    }
                });

            });

        }
    };

    app.init();

</script>
</body>
</html>
View Code

運行結果:

三、視頻

https://www.bilibili.com/video/av9219224/

四、示例

https://git.coding.net/zhangguo5/NFMall1.git

五、作業

5.1、使用MVC模式完成一個簡單學生選課系統

所有的dao要求有單元測試

表結構可以參考MySQL強化練習

要求分頁

5.2、MySQL強化練習 

5.3、內部測試

JavaWeb內部測試(一)

JavaWeb內部測試(二)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM