本篇開始使用 jstl 這個 jsp 的標籤庫,在同一個 Servlet 中實現處理 CRUD 請求,以及使用 jdbc 數據庫基本操做。而後你會發現 Servlet 和 jdbc 仍是有不少不方便之處,而後在篇章五將開始正式使用框架。html
使用 jstl 是爲了先後端分離,試想若是 jsp 中嵌入一堆的 java 代碼片斷,那樣的話前端就很難開發除非它懂 java 技術,或者得由後端開發這個。前端
<c:choose> <c:when test="${empty fileMap or fn:length(fileMap) == 0}"> <p>您尚未上傳文件,請點擊這裏上傳:<a href=/file/add>上傳文件</a></p> </c:when> <c:otherwise> <c:forEach items="${fileMap}" var="entry"> <p>文件名: ${entry.key} <a href="/file/download?fileName=${entry.value}" >下載</a></p> </c:forEach> </c:otherwise> </c:choose>
第二個:用到的有格式化浮點數的語句java
<c:forEach items="${bookList}" var="book"> <tr> <th>ids</th> <th><input type="checkbox" value="${book.id}" /></th> <td>${book.name}</td> <td><fmt:formatNumber value="${book.price}" pattern="0.00"/></td> <td>${book.pageCount}</td> <td><a href="/book?method=update&id=${book.id}">編輯</a> <a href="/book?method=delete&id=${book.id}">刪除</a></td> </tr> </c:forEach>
差點忘記說了,上邊有取數的操做,好比最開始的${bookList}、${fileMap},它是怎樣從 Servlet 傳遞到 jsp 中的呢?mysql
答案是 servlet 中用 request.setAttribute("bookList", bookList);這種方式。web
3. 數據庫操做 jdbcspring
建立數據庫鏈接的基本動做步驟sql
public class JDBCTest { public static void main(String[] args) { String driver = "com.mysql.jdbc.Driver"; String dbName = "spring"; String passwrod = "root"; String userName = "root"; String url = "jdbc:mysql://localhost:3308/" + dbName; String sql = "select * from users"; try { Class.forName(driver); Connection conn = DriverManager.getConnection(url, userName, passwrod); PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { System.out.println("id : " + rs.getInt(1) + " name : " + rs.getString(2) + " password : " + rs.getString(3)); } // 關閉記錄集 if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } // 關閉聲明 if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } // 關閉連接對象 if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } }
@WebServlet(name = "bookServlet", urlPatterns = {"/book"}) public class BookServlet extends HttpServlet { @Override public void init() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ request.setCharacterEncoding("UTF-8"); String method = request.getParameter("method"); Connection conn; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webpractice", "root", "Circle233???"); switch (method) { case "list": list(request, response, conn); break; case "add": add(request, response); break; case "create": create(request, response, conn); break; case "delete": delete(request, response, conn); break; case "update": update(request, response, conn); break; case "updateOp": updateOp(request, response, conn); break; default: break; } } catch (Exception e) { e.printStackTrace(); } } private void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.getRequestDispatcher("/WEB-INF/page/book_add.jsp").forward(request, response); } private void create(HttpServletRequest request, HttpServletResponse response, Connection conn) throws IOException, ServletException { String message; PreparedStatement ps = null; String insertSql = "insert into books(name, price, page_count) values(?,?,?)"; try { String name = request.getParameter("name"); String pricePara = request.getParameter("price"); double price = Double.valueOf(pricePara); String pageCountPara = request.getParameter("pageCount"); int pageCount = Integer.parseInt(pageCountPara); ps = conn.prepareStatement(insertSql); ps.setString(1, name); ps.setDouble(2, price); ps.setInt(3, pageCount); ps.executeUpdate(); message = "添加書籍成功!"; request.setAttribute("message",message); request.setAttribute("suggestURL", "/book?method=list"); request.setAttribute("declaration", "查看書籍列表"); request.getRequestDispatcher("/WEB-INF/page/message.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); message = "添加書籍出錯!"; request.setAttribute("message",message); request.setAttribute("suggestURL", "/book?method=add"); request.setAttribute("declaration", "從新添加書籍"); request.getRequestDispatcher("/WEB-INF/page/message.jsp").forward(request, response); } finally { returnResource(null, ps, conn); } } private void delete(HttpServletRequest request, HttpServletResponse response, Connection conn) throws IOException, ServletException { String message; PreparedStatement ps = null; String deleteSql = "delete from books where id = (?)"; try { String id = request.getParameter("id"); ps = conn.prepareStatement(deleteSql); ps.setString(1, id); ps.executeUpdate(); message = "刪除書籍成功!"; request.setAttribute("message",message); request.setAttribute("suggestURL", "/book?method=list"); request.setAttribute("declaration", "查看書籍列表"); request.getRequestDispatcher("/WEB-INF/page/message.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); message = "刪除書籍出錯!"; request.setAttribute("message",message); request.setAttribute("suggestURL", "/book?method=list"); request.setAttribute("declaration", "回到書籍列表"); request.getRequestDispatcher("/WEB-INF/page/message.jsp").forward(request, response); } finally { returnResource(null, ps, conn); } } private void update(HttpServletRequest request, HttpServletResponse response, Connection conn) throws IOException, ServletException { PreparedStatement ps = null; ResultSet rs = null; String message; try { String queryOneSql = "select * from books where id = ?"; ps = conn.prepareStatement(queryOneSql); ps.setString(1, request.getParameter("id")); rs = ps.executeQuery(); if (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); double price = rs.getDouble("price"); int pageCount = rs.getInt("page_count"); Book book = new Book(name, price, pageCount); book.setId(id); request.setAttribute("book", book); request.getRequestDispatcher("/WEB-INF/page/book_update.jsp").forward(request, response); } else { message = "沒有查到對應書籍,請刷新列表頁面!"; request.setAttribute("message",message); request.setAttribute("suggestURL", "/book?method=list"); request.setAttribute("declaration", "回到書籍列表"); request.getRequestDispatcher("/WEB-INF/page/message.jsp").forward(request, response); } } catch (Exception e) { e.printStackTrace(); message = "編輯書籍出錯!"; request.setAttribute("message",message); request.setAttribute("suggestURL", "/book?method=list"); request.setAttribute("declaration", "回到書籍列表"); request.getRequestDispatcher("/WEB-INF/page/message.jsp").forward(request, response); } finally { returnResource(rs, ps, conn); } } private void updateOp(HttpServletRequest request, HttpServletResponse response, Connection conn) throws IOException, ServletException { PreparedStatement ps = null; ResultSet rs = null; String message; try { String updateSql = "update books set name = ?, price = ?, page_count = ? where id = ?"; ps = conn.prepareStatement(updateSql); ps.setString(1, request.getParameter("name")); ps.setDouble(2, Double.valueOf(request.getParameter("price"))); ps.setInt(3, Integer.parseInt(request.getParameter("pageCount"))); ps.setInt(4, Integer.parseInt(request.getParameter("id"))); int result = ps.executeUpdate(); System.out.println("result: " + result); if (result == 1) { message = "修改書籍成功!"; request.setAttribute("message", message); request.setAttribute("suggestURL", "/book?method=list"); request.setAttribute("declaration", "查看書籍列表"); request.getRequestDispatcher("/WEB-INF/page/message.jsp").forward(request, response); } else { message = "修改書籍失敗!"; request.setAttribute("message", message); request.setAttribute("suggestURL", "/book?method=list"); request.setAttribute("declaration", "回到書籍列表"); request.getRequestDispatcher("/WEB-INF/page/message.jsp").forward(request, response); } } catch (Exception e) { e.printStackTrace(); message = "修改書籍失敗!"; request.setAttribute("message", message); request.setAttribute("suggestURL", "/book?method=list"); request.setAttribute("declaration", "回到書籍列表"); request.getRequestDispatcher("/WEB-INF/page/message.jsp").forward(request, response); } finally { returnResource(rs, ps, conn); } } private void list(HttpServletRequest request, HttpServletResponse response, Connection conn) throws IOException, ServletException{ PreparedStatement ps = null; ResultSet rs = null; try { List<Book> list = new ArrayList<>(); ps = conn.prepareStatement("select * from books"); rs = ps.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); double price = rs.getDouble("price"); int pageCount = rs.getInt("page_count"); Book book = new Book(name, price, pageCount); book.setId(id); list.add(book); } request.setAttribute("bookList", list); request.getRequestDispatcher("/WEB-INF/page/book_list.jsp").forward(request, response); } catch (SQLException e) { e.printStackTrace(); } finally { returnResource(rs, ps, conn); } } private void returnResource(ResultSet rs, PreparedStatement ps, Connection conn) { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
book_add.jsp數據庫
<%-- Created by IntelliJ IDEA. User: yixin Date: 2018/7/12 Time: 14:49 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>添加新書籍</title> </head> <body> <form action="/book?method=create" method="post" > 書名:<input name="name" type="text"><br /> 價格:<input name="price" type="text"><br /> 頁數:<input name="pageCount" type="number"> <br /> <input type="submit" value="提交"> <input type="reset" value="重置"> </form> <a href="/index.html">回到首頁</a> </body> </html>
book_list.jsp後端
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ page isELIgnored ="false" %> <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>書籍展現頁</title> </head> <body> <div> <h2><span>購買過的書籍列表</span></h2> <c:choose> <c:when test="${empty bookList}"> <tr>沒有內容</tr> </c:when> <c:otherwise> <table border="1"> <tr> <th><input type="checkbox" id="chbAll"></th> <th>編號</th> <th>書名</th> <th>價格</th> <th>頁數</th> <th>操做</th> </tr> <tbody> <c:forEach items="${bookList}" var="book"> <tr> <th>ids</th> <th><input type="checkbox" value="${book.id}" /></th> <td>${book.name}</td> <td><fmt:formatNumber value="${book.price}" pattern="0.00"/></td> <td>${book.pageCount}</td> <td><a href="/book?method=update&id=${book.id}">編輯</a> <a href="/book?method=delete&id=${book.id}">刪除</a></td> </tr> </c:forEach> </tbody> </table> </c:otherwise> </c:choose> <div> <p> <a href="/book?method=add">添加書籍</a> <a href="/index.html">返回首頁</a> </p> </div> </div> </body> </html>
book_update.jsp框架
<%-- Created by IntelliJ IDEA. User: yinjd Date: 2018/7/15 Time: 17:33 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored ="false" %> <!DOCTYPE HTML> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>修改書籍</title> </head> <body> <form action="/book?method=updateOp" method="post" > 書名:<input name="name" type="text" value="${book.name}"><br /> 價格:<input name="price" type="text" value="${book.price}"><br /> 頁數:<input name="pageCount" type="number" value="${book.pageCount}"> <br /> <input type="hidden" name="id" value="${book.id}"><br /> <input type="submit" value="提交"> </form> </body> </html>
message.jsp
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> <%@ page isELIgnored ="false" %> <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>消息頁</title> </head> <body> <p>${message}</p> <p>點擊這裏><a href="${suggestURL}">${declaration}</a></p> </body> </html>
index.html
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>歡迎頁</title> </head> <body> <a href="/file/list">上傳文件列表</a><br /> <a href="/book?method=list">購買書籍列表</a> </body> </html>
5. 效果展現頁