• 自定义MVC增删改查


    目录

    一、搭建自定义MVC框架环境

    1.将框架导成jar包,然后导入新工程,并且将框架的依赖jar包导入

     2.将分页标签相关文件、以及相关助手类导入,框架的配置文件添加以及web.xml的配置

    二、基础的增删改

     三、通用的增删改

     四、查询删除及重复表单提交问题

    五、新增修改的前端实现


    一、搭建自定义MVC框架环境

    1.将框架导成jar包,然后导入新工程,并且将框架的依赖jar包导入

    如图:导出自己的jar包

     

     

     取个名字

     找到该jar包,放入新建项目的lib下,该包为核心包

    再导入其他依赖包

     

     2.将分页标签相关文件、以及相关助手类导入,框架的配置文件添加以及web.xml的配置

     配置中央控制器的.xml的坏境

    web.xml的源码

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    3. <display-name>T280_mvc_crud</display-name>
    4. <servlet>
    5. <servlet-name>mvc</servlet-name>
    6. <servlet-class>com.cdl.framework.DispatcherServlet</servlet-class>
    7. <init-param>
    8. <param-name>configLaction</param-name>
    9. <param-value>/wuyanzu</param-value>
    10. </init-param>
    11. </servlet>
    12. <servlet-mapping>
    13. <servlet-name>mvc</servlet-name>
    14. <url-pattern>*.action</url-pattern>
    15. </servlet-mapping>
    16. </web-app>

    将助手类一级tld的配置文件拿过来,如图结构

     注意:目前所有的包的内容均再通用分页的博客中有

    以后的开元框架都从这一步开始

    二、基础的增删改

    建一个com.cdl.entity的包,里面放实体类

    Book

    1. package com.cdl.entity;
    2. public class Book {
    3. private int bid;
    4. private String bname;
    5. private float price;
    6. @Override
    7. public String toString() {
    8. return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
    9. }
    10. public int getBid() {
    11. return bid;
    12. }
    13. public void setBid(int bid) {
    14. this.bid = bid;
    15. }
    16. public String getBname() {
    17. return bname;
    18. }
    19. public void setBname(String bname) {
    20. this.bname = bname;
    21. }
    22. public float getPrice() {
    23. return price;
    24. }
    25. public void setPrice(float price) {
    26. this.price = price;
    27. }
    28. public Book() {
    29. // TODO Auto-generated constructor stub
    30. }
    31. public Book(int bid, String bname, float price) {
    32. this.bid = bid;
    33. this.bname = bname;
    34. this.price = price;
    35. }
    36. }

    在com.cdl.dao中写一个bookdao

    1. package com.cdl.dao;
    2. import java.sql.Connection;
    3. import java.sql.ResultSet;
    4. import java.sql.SQLException;
    5. import java.util.ArrayList;
    6. import java.util.List;
    7. import com.cdl.entity.Book;
    8. import com.cdl.util.BaseDao;
    9. import com.cdl.util.CallBack;
    10. import com.cdl.util.DBAccess;
    11. import com.cdl.util.PageBean;
    12. import com.cdl.util.StringUtils;
    13. import com.mysql.jdbc.PreparedStatement;
    14. public class BookDao extends BaseDao<Book>{
    15. //查询
    16. public List<Book> list(Book book,PageBean pageBean) throws Exception{
    17. String sql = "select * from t_mvc_book where 1=1 ";
    18. String bname = book.getBname();
    19. if(StringUtils.isNotBlank(bname)) {
    20. sql += " and bname like '%"+bname+"%' ";
    21. }
    22. int bid = book.getBid();
    23. // 前台jsp传递到后台,只要传了就有值,没传就是默认值,默认值就是0
    24. if(bid != 0) {
    25. sql += " and bid = "+bid;
    26. }
    27. return super.executeQuery(sql, pageBean, rs -> {
    28. List<Book> list = new ArrayList<Book>();
    29. try {
    30. while(rs.next()) {
    31. list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
    32. }
    33. } catch (SQLException e) {
    34. // TODO Auto-generated catch block
    35. e.printStackTrace();
    36. }
    37. return list;
    38. });
    39. }
    40. // 增
    41. public int add(Book book) throws Exception {
    42. Connection con = DBAccess.getConnection();
    43. String sql = "insert into t_mvc_book values(?,?,?)";
    44. java.sql.PreparedStatement pst = con.prepareStatement(sql);
    45. pst.setObject(1, book.getBid());
    46. pst.setObject(2, book.getBname());
    47. pst.setObject(3, book.getPrice());
    48. return pst.executeUpdate();
    49. }
    50. // 删
    51. public int del(Book book) throws Exception {
    52. Connection con = DBAccess.getConnection();
    53. String sql = "delete from t_mvc_book where bid=?";
    54. java.sql.PreparedStatement pst = con.prepareStatement(sql);
    55. pst.setObject(1, book.getBid());
    56. return pst.executeUpdate();
    57. }
    58. // 改
    59. public int edit(Book book) throws Exception {
    60. Connection con = DBAccess.getConnection();
    61. String sql = "update t_mvc_book set bname=?,price=? where bid=?";
    62. java.sql.PreparedStatement pst = con.prepareStatement(sql);
    63. pst.setObject(3, book.getBid());
    64. pst.setObject(1, book.getBname());
    65. pst.setObject(2, book.getPrice());
    66. return pst.executeUpdate();
    67. }
    68. }

    在当前类,快捷键ctrl+n,输入junit,建立一个测试类

    1. package com.cdl.dao;
    2. import static org.junit.Assert.*;
    3. import java.util.List;
    4. import org.junit.Test;
    5. import com.cdl.entity.Book;
    6. import com.cdl.util.PageBean;
    7. public class BookDaoTest {
    8. private BookDao bookDao = new BookDao();
    9. @Test
    10. public void testList() {
    11. try {
    12. List<Book> list = bookDao.list(new Book(), new PageBean());
    13. for (Book book : list) {
    14. System.out.println(book);
    15. }
    16. } catch (Exception e) {
    17. // TODO Auto-generated catch block
    18. e.printStackTrace();
    19. }
    20. }
    21. @Test
    22. public void testAdd() {
    23. new Book(123,"asdf",4567);
    24. }
    25. @Test
    26. public void testDel() {
    27. Book book2 = new Book(123,"8989",4567);
    28. try {
    29. bookDao.del(book2);
    30. } catch (Exception e) {
    31. // TODO Auto-generated catch block
    32. e.printStackTrace();
    33. }
    34. }
    35. @Test
    36. public void testEdit() {
    37. Book book2 = new Book(123,"8989",4567);
    38. try {
    39. bookDao.edit(book2);
    40. } catch (Exception e) {
    41. // TODO Auto-generated catch block
    42. e.printStackTrace();
    43. }
    44. }
    45. }

    运行结果:

     三、通用的增删改

    BaseDao

    1. package com.cdl.util;
    2. import java.lang.reflect.Field;
    3. import java.sql.Connection;
    4. import java.sql.ResultSet;
    5. import java.util.ArrayList;
    6. import java.util.List;
    7. import com.cdl.entity.Book;
    8. /**
    9. * T代表是实体类,可以是book user goods...
    10. *
    11. * @author 陈冬丽
    12. *
    13. * @param <T>
    14. */
    15. public class BaseDao<T> {
    16. /*public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
    17. //**
    18. * 1.拿到数据库连接
    19. * 2.拿到域定义对象(preparestatement)
    20. * 3.执行SQL语句
    21. *//*
    22. Connection con = DBAccess.getConnection();//连接对象 //重复代码1
    23. java.sql.PreparedStatement pst = con.prepareStatement(sql );//执行对象 //重复代码2
    24. ResultSet rs = pst.executeQuery();//重复代码3
    25. while(rs.next()){
    26. //实例化并且赋值加入集合中去
    27. list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
    28. }
    29. return list;
    30. //查询不同的表,必然要处理不同的结果集
    31. // 接口是调用放来实现
    32. return callBack.foreach(rs);
    33. }*/
    34. public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
    35. // select * from t_mvc_book where bname like '%圣墟%';
    36. // 从上面得到 select count(1) as n from (select * from t_mvc_book where bname like '%圣墟%') t;
    37. // 目的是为了得到总记录数->得到总页数
    38. // select * from t_mvc_book where bname like '%圣墟%' limit 10,10;
    39. /*
    40. 1.拿到数据库连接
    41. 2.拿到域定义对象(preparestatement)
    42. 3.执行SQL语句*/
    43. Connection con = null;//连接对象 //重复代码1
    44. java.sql.PreparedStatement pst = null;//执行对象 //重复代码2
    45. ResultSet rs = null;//重复代码3
    46. if(pageBean !=null && pageBean.isPagination()) {//分页
    47. String countSQL = getCountSQL(sql);
    48. con = DBAccess.getConnection();//连接对象 //重复代码1
    49. pst = con.prepareStatement(countSQL);//执行对象 //重复代码2
    50. rs = pst.executeQuery();//重复代码3
    51. if(rs.next()) {
    52. // pageBean包含了当前实体类的总记录数
    53. pageBean.setTotal(rs.getString("n"));
    54. }
    55. String pageSQL = getPageSQL(sql,pageBean);
    56. con = DBAccess.getConnection();//连接对象 //重复代码1
    57. pst = con.prepareStatement(pageSQL);//执行对象 //重复代码2
    58. rs = pst.executeQuery();//重复代码3
    59. }
    60. else {//不分页
    61. con = DBAccess.getConnection();//连接对象 //重复代码1
    62. pst = con.prepareStatement(sql);//执行对象 //重复代码2
    63. rs = pst.executeQuery();//重复代码3
    64. }
    65. return callBack.foreach(rs);
    66. }
    67. /**
    68. * 拼装第n页的数据
    69. *
    70. * @param sql
    71. * @param pageBean
    72. * @return
    73. */
    74. private String getPageSQL(String sql, PageBean pageBean) {
    75. return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
    76. }
    77. /**
    78. * 拼装符合条件总记录数的SQL
    79. * @param sql
    80. * @return
    81. */
    82. private String getCountSQL(String sql) {
    83. // select * from t_mvc_book where bname like '%圣墟%';
    84. // 从上面得到 select count(1) as n from (select * from t_mvc_book where bname like '%圣墟%') t;
    85. return "select count(1) as n from ("+sql+") t";
    86. }
    87. public int executeUpdate(String sql,T t,String[] attrs) throws Exception {
    88. Connection con = DBAccess.getConnection();
    89. java.sql.PreparedStatement pst = con.prepareStatement(sql);
    90. // 将t 的某一个属性对应的值加到pst 对象中
    91. for (int i = 0; i < attrs.length; i++) {
    92. Field f = t.getClass().getDeclaredField(attrs[i]);
    93. f.setAccessible(true);
    94. pst.setObject(i + 1,f.get(t));
    95. }
    96. return pst.executeUpdate();
    97. }
    98. }

    BookDao

    1. package com.cdl.dao;
    2. import java.sql.Connection;
    3. import java.sql.ResultSet;
    4. import java.sql.SQLException;
    5. import java.util.ArrayList;
    6. import java.util.List;
    7. import com.cdl.entity.Book;
    8. import com.cdl.util.BaseDao;
    9. import com.cdl.util.CallBack;
    10. import com.cdl.util.DBAccess;
    11. import com.cdl.util.PageBean;
    12. import com.cdl.util.StringUtils;
    13. import com.mysql.jdbc.PreparedStatement;
    14. public class BookDao extends BaseDao<Book>{
    15. //查询
    16. public List<Book> list(Book book,PageBean pageBean) throws Exception{
    17. String sql = "select * from t_mvc_book where 1=1 ";
    18. String bname = book.getBname();
    19. if(StringUtils.isNotBlank(bname)) {
    20. sql += " and bname like '%"+bname+"%' ";
    21. }
    22. int bid = book.getBid();
    23. // 前台jsp传递到后台,只要传了就有值,没传就是默认值,默认值就是0
    24. if(bid != 0) {
    25. sql += " and bid = "+bid;
    26. }
    27. return super.executeQuery(sql, pageBean, rs -> {
    28. List<Book> list = new ArrayList<Book>();
    29. try {
    30. while(rs.next()) {
    31. list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
    32. }
    33. } catch (SQLException e) {
    34. // TODO Auto-generated catch block
    35. e.printStackTrace();
    36. }
    37. return list;
    38. });
    39. }
    40. // 增
    41. // public int add(Book book) throws Exception {
    42. // Connection con = DBAccess.getConnection();
    43. // String sql = "insert into t_mvc_book values(?,?,?)";
    44. // java.sql.PreparedStatement pst = con.prepareStatement(sql);
    45. // pst.setObject(1, book.getBid());
    46. // pst.setObject(2, book.getBname());
    47. // pst.setObject(3, book.getPrice());
    48. // return pst.executeUpdate();
    49. // }
    50. public int add(Book book) throws Exception {
    51. String sql = "insert into t_mvc_book values(?,?,?)";
    52. return super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
    53. }
    54. // 删
    55. // public int del(Book book) throws Exception {
    56. // Connection con = DBAccess.getConnection();
    57. // String sql = "delete from t_mvc_book where bid=?";
    58. // java.sql.PreparedStatement pst = con.prepareStatement(sql);
    59. // pst.setObject(1, book.getBid());
    60. // return pst.executeUpdate();
    61. // }
    62. public int del(Book book) throws Exception {
    63. String sql = "delete from t_mvc_book where bid=?";
    64. return super.executeUpdate(sql, book, new String[] {"bid"});
    65. }
    66. // 改
    67. // public int edit(Book book) throws Exception {
    68. // Connection con = DBAccess.getConnection();
    69. // String sql = "update t_mvc_book set bname=?,price=? where bid=?";
    70. // java.sql.PreparedStatement pst = con.prepareStatement(sql);
    71. // pst.setObject(3, book.getBid());
    72. // pst.setObject(1, book.getBname());
    73. // pst.setObject(2, book.getPrice());
    74. // return pst.executeUpdate();
    75. // }
    76. public int edit(Book book) throws Exception {
    77. String sql = "update t_mvc_book set bname=?,price=? where bid=?";
    78. return super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
    79. }
    80. }

    BookDaoTest

    1. package com.cdl.dao;
    2. import static org.junit.Assert.*;
    3. import java.util.List;
    4. import org.junit.Test;
    5. import com.cdl.entity.Book;
    6. import com.cdl.util.PageBean;
    7. public class BookDaoTest {
    8. private BookDao bookDao = new BookDao();
    9. @Test
    10. public void testList() {
    11. try {
    12. List<Book> list = bookDao.list(new Book(), new PageBean());
    13. for (Book book : list) {
    14. System.out.println(book);
    15. }
    16. } catch (Exception e) {
    17. // TODO Auto-generated catch block
    18. e.printStackTrace();
    19. }
    20. }
    21. @Test
    22. public void testAdd() {
    23. Book book = new Book(123,"asdf",4567);
    24. try {
    25. bookDao.add(book);
    26. } catch (Exception e) {
    27. // TODO Auto-generated catch block
    28. e.printStackTrace();
    29. }
    30. }
    31. @Test
    32. public void testDel() {
    33. Book book2 = new Book(123,"8989",4567);
    34. try {
    35. bookDao.del(book2);
    36. } catch (Exception e) {
    37. // TODO Auto-generated catch block
    38. e.printStackTrace();
    39. }
    40. }
    41. @Test
    42. public void testEdit() {
    43. Book book2 = new Book(123,"8989",4567);
    44. try {
    45. bookDao.edit(book2);
    46. } catch (Exception e) {
    47. // TODO Auto-generated catch block
    48. e.printStackTrace();
    49. }
    50. }
    51. }

    运行增加

     四、查询删除及重复表单提交问题

    建一个com.cdl.web

    BookAction

    1. package com.cdl.web;
    2. import java.util.List;
    3. import javax.servlet.http.HttpServletRequest;
    4. import javax.servlet.http.HttpServletResponse;
    5. import com.cdl.dao.BookDao;
    6. import com.cdl.entity.Book;
    7. import com.cdl.framework.ActionSupport;
    8. import com.cdl.framework.ModelDriven;
    9. import com.cdl.util.PageBean;
    10. public class BookAction extends ActionSupport implements ModelDriven<Book>{
    11. private Book book = new Book();
    12. private BookDao bookDao = new BookDao();
    13. @Override
    14. public Book getModel() {
    15. // TODO Auto-generated method stub
    16. return book;
    17. }
    18. // 增
    19. public String add(HttpServletRequest req,HttpServletResponse resp) {
    20. try {
    21. bookDao.add(book);
    22. } catch (Exception e) {
    23. // TODO: handle exception
    24. e.printStackTrace();
    25. }
    26. // 代表跳到查询界面
    27. return "toList";
    28. }
    29. // 删
    30. public String del(HttpServletRequest req,HttpServletResponse resp) {
    31. try {
    32. bookDao.del(book);
    33. } catch (Exception e) {
    34. // TODO: handle exception
    35. e.printStackTrace();
    36. }
    37. // 代表跳到查询界面
    38. return "toList";
    39. }
    40. // 改
    41. public String edit(HttpServletRequest req,HttpServletResponse resp) {
    42. try {
    43. bookDao.edit(book);
    44. } catch (Exception e) {
    45. // TODO: handle exception
    46. e.printStackTrace();
    47. }
    48. // 代表跳到查询界面
    49. return "toList";
    50. }
    51. // 查
    52. public String list(HttpServletRequest req,HttpServletResponse resp) {
    53. try {
    54. PageBean pageBean = new PageBean();
    55. pageBean.setRequest(req);
    56. List<Book> list = bookDao.list(book, pageBean);
    57. req.setAttribute("list", list);
    58. req.setAttribute("pageBean", pageBean);
    59. } catch (Exception e) {
    60. // TODO: handle exception
    61. e.printStackTrace();
    62. }
    63. // 执行查询
    64. return "list";
    65. }
    66. // 跳转到新增/修改界面
    67. public String preEdit(HttpServletRequest req,HttpServletResponse resp) {
    68. try {
    69. int bid = book.getBid();
    70. if(bid != 0) {
    71. // 传递bid到后台,有且只能查出一条数据,意味着list集合中也只有一条
    72. List<Book> list = bookDao.list(book, null);
    73. req.setAttribute("b", list.get(0));
    74. }
    75. } catch (Exception e) {
    76. // TODO: handle exception
    77. e.printStackTrace();
    78. }
    79. // 代表跳到编辑界面
    80. return "toEdit";
    81. }
    82. }

    wuyanzu.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <config>
    3. <action path="/book" type="com.cdl.web.BookAction">
    4. <forward name="list" path="/bookList.jsp" redirect="false" />
    5. <forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
    6. <forward name="toList" path="/book.action?methodName=list" redirect="false" />
    7. </action>
    8. </config>

    bookList.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <link
    8. href="css/bootstrap.css"
    9. rel="stylesheet">
    10. <script src="js/bootstrap.js"></script>
    11. <title>书籍列表</title>
    12. <style type="text/css">
    13. .page-item input {
    14. padding: 0;
    15. width: 40px;
    16. height: 100%;
    17. text-align: center;
    18. margin: 0 6px;
    19. }
    20. .page-item input, .page-item b {
    21. line-height: 38px;
    22. float: left;
    23. font-weight: 400;
    24. }
    25. .page-item.go-input {
    26. margin: 0 10px;
    27. }
    28. </style>
    29. </head>
    30. <body>
    31. <form class="form-inline"
    32. action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
    33. <div class="form-group mb-2">
    34. <input type="text" class="form-control-plaintext" name="bname"
    35. placeholder="请输入书籍名称">
    36. </div>
    37. <button type="submit" class="btn btn-primary mb-2">查询</button>
    38. </form>
    39. <table class="table table-striped">
    40. <thead>
    41. <tr>
    42. <th scope="col">书籍ID</th>
    43. <th scope="col">书籍名</th>
    44. <th scope="col">价格</th>
    45. </tr>
    46. </thead>
    47. <tbody>
    48. <c:forEach items="${list}" var="book">
    49. <tr>
    50. <td>${book.bid}</td>
    51. <td>${book.bname}</td>
    52. <td>${book.price}</td>
    53. </tr>
    54. </c:forEach>
    55. </tbody>
    56. </table>
    57. <z:page pageBean="${pageBen}"></z:page>
    58. </body>
    59. </html>

     bookList.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <link
    8. href="css/bootstrap.css"
    9. rel="stylesheet">
    10. <script src="js/bootstrap.js"></script>
    11. <title>书籍列表</title>
    12. <style type="text/css">
    13. .page-item input {
    14. padding: 0;
    15. width: 40px;
    16. height: 100%;
    17. text-align: center;
    18. margin: 0 6px;
    19. }
    20. .page-item input, .page-item b {
    21. line-height: 38px;
    22. float: left;
    23. font-weight: 400;
    24. }
    25. .page-item.go-input {
    26. margin: 0 10px;
    27. }
    28. </style>
    29. </head>
    30. <body>
    31. <form class="form-inline"
    32. action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
    33. <div class="form-group mb-2">
    34. <input type="text" class="form-control-plaintext" name="bname"
    35. placeholder="请输入书籍名称">
    36. </div>
    37. <button type="submit" class="btn btn-primary mb-2">查询</button>
    38. </form>
    39. <table class="table table-striped">
    40. <thead>
    41. <tr>
    42. <th scope="col">书籍ID</th>
    43. <th scope="col">书籍名</th>
    44. <th scope="col">价格</th>
    45. <th scope="col">操作</th>
    46. </tr>
    47. </thead>
    48. <tbody>
    49. <c:forEach items="${list}" var="book">
    50. <tr>
    51. <td>${book.bid}</td>
    52. <td>${book.bname}</td>
    53. <td>${book.price}</td>
    54. <td>
    55. <a href="${pageContext.request.contextPath}/book.action?methodName=preEdit?bid=${book.bid}">编辑</a>
    56. <a href="${pageContext.request.contextPath}/book.action?methodName=del?bid=${book.bid}">删除</a>
    57. </td>
    58. </tr>
    59. </c:forEach>
    60. </tbody>
    61. </table>
    62. <z:page pageBean="${pageBean}"></z:page>
    63. </body>
    64. </html>

    效果图:

     当点击删除后

     因为地址栏将参数又带回去了

    将wuyanzu.xml的配置的提交方式改变

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <config>
    3. <action path="/book" type="com.cdl.web.BookAction">
    4. <forward name="list" path="/bookList.jsp" redirect="false" />
    5. <forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
    6. <forward name="toList" path="/book.action?methodName=list" redirect="true" />
    7. </action>
    8. </config>

    五、新增修改的前端实现

    新增界面

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>Insert title here</title>
    8. </head>
    9. <body>
    10. <form action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
    11. bid:<input type="text" name="bid" value="${b.bid}">
    12. bname:<input type="text" name="bname" value="${b.bname}">
    13. price:<input type="text" name="price" value="${b.price}">
    14. <input type="submit" vaule="提交">
    15. </form>
    16. </body>
    17. </html>

    效果:

     

    此时的bookList.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <link
    8. href="css/bootstrap.css"
    9. rel="stylesheet">
    10. <script src="js/bootstrap.js"></script>
    11. <title>书籍列表</title>
    12. <style type="text/css">
    13. .page-item input {
    14. padding: 0;
    15. width: 40px;
    16. height: 100%;
    17. text-align: center;
    18. margin: 0 6px;
    19. }
    20. .page-item input, .page-item b {
    21. line-height: 38px;
    22. float: left;
    23. font-weight: 400;
    24. }
    25. .page-item.go-input {
    26. margin: 0 10px;
    27. }
    28. </style>
    29. </head>
    30. <body>
    31. <form class="form-inline"
    32. action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
    33. <div class="form-group mb-2">
    34. <input type="text" class="form-control-plaintext" name="bname"
    35. placeholder="请输入书籍名称">
    36. </div>
    37. <button type="submit" class="btn btn-primary mb-2">查询</button>
    38. <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath}/book.action?methodName=preEdit">新增</a>
    39. </form>
    40. <table class="table table-striped">
    41. <thead>
    42. <tr>
    43. <th scope="col">书籍ID</th>
    44. <th scope="col">书籍名</th>
    45. <th scope="col">价格</th>
    46. <th scope="col">操作</th>
    47. </tr>
    48. </thead>
    49. <tbody>
    50. <c:forEach items="${list}" var="book">
    51. <tr>
    52. <td>${book.bid}</td>
    53. <td>${book.bname}</td>
    54. <td>${book.price}</td>
    55. <td>
    56. <a href="${pageContext.request.contextPath}/book.action?methodName=preEdit?bid=${book.bid}">编辑</a>
    57. <a href="${pageContext.request.contextPath}/book.action?methodName=del?bid=${book.bid}">删除</a>
    58. </td>
    59. </tr>
    60. </c:forEach>
    61. </tbody>
    62. </table>
    63. <z:page pageBean="${pageBean}"></z:page>
    64. </body>
    65. </html>

     注意:过滤器

    1. package com.cdl.util;
    2. import java.io.IOException;
    3. import java.util.Iterator;
    4. import java.util.Map;
    5. import java.util.Set;
    6. import javax.servlet.Filter;
    7. import javax.servlet.FilterChain;
    8. import javax.servlet.FilterConfig;
    9. import javax.servlet.ServletException;
    10. import javax.servlet.ServletRequest;
    11. import javax.servlet.ServletResponse;
    12. import javax.servlet.annotation.WebFilter;
    13. import javax.servlet.http.HttpServletRequest;
    14. import javax.servlet.http.HttpServletResponse;
    15. /**
    16. * 中文乱码处理
    17. *
    18. */
    19. @WebFilter("*.action")
    20. public class EncodingFiter implements Filter {
    21. private String encoding = "UTF-8";// 默认字符集
    22. public EncodingFiter() {
    23. super();
    24. }
    25. public void destroy() {
    26. }
    27. public void doFilter(ServletRequest request, ServletResponse response,
    28. FilterChain chain) throws IOException, ServletException {
    29. HttpServletRequest req = (HttpServletRequest) request;
    30. HttpServletResponse res = (HttpServletResponse) response;
    31. // 中文处理必须放到 chain.doFilter(request, response)方法前面
    32. res.setContentType("text/html;charset=" + this.encoding);
    33. if (req.getMethod().equalsIgnoreCase("post")) {
    34. req.setCharacterEncoding(this.encoding);
    35. } else {
    36. Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
    37. Set set = map.keySet();// 取出所有参数名
    38. Iterator it = set.iterator();
    39. while (it.hasNext()) {
    40. String name = (String) it.next();
    41. String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
    42. for (int i = 0; i < values.length; i++) {
    43. values[i] = new String(values[i].getBytes("ISO-8859-1"),
    44. this.encoding);
    45. }
    46. }
    47. }
    48. chain.doFilter(request, response);
    49. }
    50. public void init(FilterConfig filterConfig) throws ServletException {
    51. String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
    52. if (null != s && !s.trim().equals("")) {
    53. this.encoding = s.trim();
    54. }
    55. }
    56. }

  • 相关阅读:
    方法调用过程
    操作系统基础知识1
    git与svn简单的使用方法
    【web课程设计】基于html鲜花商城项目的设计与实现
    20221106 今天的世界发生了什么
    黑客是什么?想成为黑客需要学习什么?
    设置visual studio代码自动提示
    vue下载Excel文件
    HTML+CSS一个简单的电影网页制作作业,学生个人html静态网页制作成品代码, html电影速递网
    【Java基础】ArrayList类概述、常用方法及存储字符串并遍历
  • 原文地址:https://blog.csdn.net/weixin_62735525/article/details/125513439