目录
1.将框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去
3.框架的配置文件添加、以及web.xml的配置-以后开源框架的使用从这一步开始
1.将框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去
打成jar包步骤:
2.将分页标签相关文件、及相关助手类导入
相关代码
tag
package com.ruojuan.tag;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.ruojuan.util.PageBean;
public class PageTag extends BodyTagSupport{
private PageBean pageBean;
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.print(toHML());
} catch (Exception e) {
e.printStackTrace();
}
return super.doStartTag();
}
private String toHML() {
//String
StringBuffer sb = new StringBuffer();
//隐藏的from表单,作用保存上一次
sb.append("<form action='"+pageBean.getUrl()+"' id='pageBeanForm' method='post'>");
sb.append(" <input type='hidden' name='page' value=''>");
Map<String, String[]> parameterMap = pageBean.getParameterMap();
if(parameterMap!=null&¶meterMap.size()>0) {
Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
String key = entry.getKey();
String[] values = entry.getValue();
if(!"page".equals(key)) {
for (String value : values) {
sb.append(" <input type='hidden' name='"+key+"' value='"+value+"'>");
}
}
}
}
sb.append("</form>");
//分页条
sb.append("<ul class='pagination justify-content-center'>");
sb.append(" <li class='page-item "+(pageBean.getPage()== 1?"disabled":"")+"'><a class='page-link' href='javascript:gotoPage(1)'>首页</a></li>");
sb.append(" <li class='page-item "+(pageBean.getPage()== 1?"disabled":"")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.previousPage()+")'><</a></li>");
sb.append(" <li class='page-item active'><a class='page-link' href='#'>"+pageBean.getPage()+"</a></li>");
sb.append(" <li class='page-item "+(pageBean.getPage()== pageBean.maxPage()?"disabled":"")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>></a></li>");
sb.append(" <li class='page-item "+(pageBean.getPage()== pageBean.maxPage()?"disabled":"")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.maxPage()+")'>尾页</a></li>");
sb.append(" <li class='page-item go-input'><b>到第</b><input class='page-link' type='text' id='skipPage' name='' /><b>页</b></li>");
sb.append(" <li class='page-item go'><a class='page-link' href='javascript:skipPage()'>确定</a></li>");
sb.append(" <li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>");
sb.append("</ul>");
//分页js代码
sb.append("<script type='text/javascript'>");
sb.append(" function gotoPage(page) {");
sb.append(" document.getElementById('pageBeanForm').page.value = page;");
sb.append(" document.getElementById('pageBeanForm').submit();");
sb.append("}");
sb.append(" function skipPage() {");
sb.append(" var page = document.getElementById('skipPage').value;");
sb.append(" if (!page || isNaN(page) || parseInt(page) < 1|| parseInt(page) > "+pageBean.maxPage()+") {");
sb.append(" alert('请输入1~"+pageBean.maxPage()+"的数字');");
sb.append(" return;");
sb.append(" }");
sb.append(" gotoPage(page);");
sb.append(" }");
sb.append("</script>");
return sb.toString();
}
}
BaseDao
package com.ruojuan.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.ruojuan.entity.Book;
/**
* T代表的实体类 可以是BOok
* @author liuruojuan
*
* 时间:2022年6月21日下午6:44:17
*/
public class BaseDao<T> {
// public List<Book> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
// /*
// * 1.拿到数据库连接
// * 2.拿到preparestatement
// * 3.执行SQL语句
// */
// Connection con = DBAccess.getConnection();//重复代码1
// PreparedStatement pst = con.prepareStatement(sql);//重复代码2
// ResultSet rs = pst.executeQuery();//重复代码3
while(rs.next()) {
list.add(new Book(rs.getInt("bid"),rs.getString("bname"),rs.getFloat("price")));
}
查询不同的表到,必然处理不同的结果集
接口调用方来实现
//
// return callBack.foreach(rs);
// }
public List<Book> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
// sql="select * from t_mvc_book where bname like '%圣墟%'";
// List<Book> list =new ArrayList<Book>();
// 从上面而得到select count(1) as n from (select * from t_mvc_book where bname like '%圣墟%') t
// String countsql = "select count(1) as n from ("+sql+")t";
// 目的是为了得到总记录数-》得到总页数
// select * from t_mvc_book where bname like '%圣墟%' LIMIT 10,10
/*
* 1.拿到数据库连接
* 2.拿到preparestatement
* 3.执行SQL语句
*/
Connection con = null;//重复代码1
PreparedStatement pst = null;//重复代码2
ResultSet rs = null;//重复代码3
if(pageBean!=null&&pageBean.isPagination()) {
//总记录数
String countSQL = getCountSQL(sql);
con = DBAccess.getConnection();//重复代码1
pst = con.prepareStatement(countSQL);//重复代码2
rs = pst.executeQuery();//重复代码3
if(rs.next()) {
//当前实体类就包含总记录数
pageBean.setTotal(rs.getString("n"));
}
//分页
String pageSQL = getPageSQL(sql,pageBean);
con = DBAccess.getConnection();//重复代码1
pst = con.prepareStatement(pageSQL);//重复代码2
rs = pst.executeQuery();//重复代码3
}
else {
con = DBAccess.getConnection();//重复代码1
pst = con.prepareStatement(sql);//重复代码2
rs = pst.executeQuery();//重复代码3
}
// while(rs.next()) {
// list.add(new Book(rs.getInt("bid"),rs.getString("bname"),rs.getFloat("price")));
// }
// 查询不同的表到,必然处理不同的结果集
// 接口调用方来实现
return callBack.foreach(rs);
}
/**
* 拼装第N页的数据SQL
* @param sql
* @param pageBean
* @return
*/
private String getPageSQL(String sql, PageBean pageBean) {
return sql+" limit " + pageBean.getStartIndex()+","+pageBean.getRows();
}
/**
* 拼装符合条件总记录输的
* @param sql
* @return
*/
private String getCountSQL(String sql) {
// sql="select * from t_mvc_book where bname like '%圣墟%'";
// List<Book> list =new ArrayList<Book>();
// 从上面而得到select count(1) as n from (select * from t_mvc_book where bname like '%圣墟%') t
// String countsql = "select count(1) as n from ("+sql+")t";
// 目的是为了得到总记录数-》得到总页数
// select * from t_mvc_book where bname like '%圣墟%' LIMIT 10,10
return "select count(1) as n from ("+sql+")t";
}
public int executeUpdate(String sql,T t,String[] attrs ) throws Exception{
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
//将t的某一个属性对应的值加到pst对象中
for (int i = 0; i < attrs.length; i++) {
Field f = t.getClass().getDeclaredField(attrs[i]);
f.setAccessible(true);
pst.setObject(i+1, f.get(t));
}
// pst.setObject(1, book.getBid());
// pst.setObject(2, book.getBname());
// pst.setObject(3, book.getPrice());
return pst.executeUpdate();
}
}
package com.ruojuan.util;
import java.sql.ResultSet;
import java.util.List;
import com.ruojuan.entity.Book;
/**
* 回调函数接口类的作用?
* 谁调用谁处理
* @author liuruojuan
*
* 时间:2022年6月21日下午6:47:02
*/
public interface CallBack<T> {
List<Book> foreach(ResultSet rs);
}
package com.ruojuan.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 提供了一组获得或关闭数据库对象的方法
*
*/
public class DBAccess {
private static String driver;
private static String url;
private static String user;
private static String password;
static {// 静态块执行一次,加载 驱动一次
try {
InputStream is = DBAccess.class
.getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("pwd");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 获得数据连接对象
*
* @return
*/
public static Connection getConnection() {
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void close(ResultSet rs) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Statement stmt) {
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
close(conn);
}
public static boolean isOracle() {
return "oracle.jdbc.driver.OracleDriver".equals(driver);
}
public static boolean isSQLServer() {
return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
}
public static boolean isMysql() {
return "com.mysql.cj.jdbc.Driver".equals(driver);
}
public static void main(String[] args) {
Connection conn = DBAccess.getConnection();
System.out.println(conn);
DBAccess.close(conn);
System.out.println("isOracle:" + isOracle());
System.out.println("isSQLServer:" + isSQLServer());
System.out.println("isMysql:" + isMysql());
System.out.println("数据库连接(关闭)成功");
}
}
中文乱码处理:
package com.ruojuan.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中文乱码
*
*/
@WebFilter("*.action")
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// 榛樿瀛楃闆�
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 涓枃澶勭悊蹇呴』鏀惧埌 chain.doFilter(request, response)鏂规硶鍓嶉潰
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// 淇濆瓨鎵�鏈夊弬鏁板悕=鍙傛暟鍊�(鏁扮粍)鐨凪ap闆嗗悎
Set set = map.keySet();// 鍙栧嚭鎵�鏈夊弬鏁板悕
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// 鍙栧嚭鍙傛暟鍊糩娉細鍙傛暟鍊间负涓�涓暟缁刔
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 璇诲彇web.xml鏂囦欢涓厤缃殑瀛楃闆�
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
pageBean实体:
package com.ruojuan.util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* 改造pagebean
* 需要新增变量保存上一次查询条件
* 需要新增变量保存上一次请求地址
* 需要添加方法: 获取最大的页码
* 需要添加方法: 获取下一页的页码
* 需要添加方法: 获取上一页的页码
* 需要新增方法:初始化pagebean
*/
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
private String url;//需要新增变量保存上一次请求地址
//需要新增变量保存上一次查询条件
private Map<String, String[]> parameterMap = new HashMap<String, String[]>();
//需要添加方法: 获取最大的页码
public int maxPage() {
return this.total%this.rows ==0?this.total/this.rows:this.total/this.rows+1;
}
//需要添加方法: 获取上一页的页码
public int previousPage() {
return this.page>1?this.page-1:this.page;
}
//需要添加方法: 获取下一页的页码
public int nextPage() {
return this.page<this.maxPage()?this.page+1:this.page;
}
//需要新增方法:初始化pagebean
public void setRequest(HttpServletRequest request) {
this.setPage(request.getParameter("page"));
this.setRows(request.getParameter("rows"));
this.setPagination(request.getParameter("pagination"));
this.setUrl(request.getRequestURL().toString());
this.setParameterMap(request.getParameterMap());
}
public void setPagination(String pagination) {
if(StringUtils.isNotBlank(pagination)) {
this.setPagination(!"false".equals(pagination));
}
}
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.setRows(rows);
}
}
public void setPage(String page) {
if(StringUtils.isNotBlank(page)) {
//set自动生成的方法
this.setPage(Integer.valueOf(page));
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
this.parameterMap = parameterMap;
}
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
+ ", url=" + url + ", parameterMap=" + parameterMap + "]";
}
}
package com.ruojuan.util;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
tld文件:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>JSTL 1.1 core library</description>
<display-name>JSTL core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>r</short-name>
<uri>http://jsp.veryedu.ruojuan</uri>
<validator>
<description>
Provides core validation features for JSTL tags.
</description>
<validator-class>
org.apache.taglibs.standard.tlv.JstlCoreTLV
</validator-class>
</validator>
<tag>
<!--代表标签库标签的名字 -->
<name>if</name>
<!--代表该标签库的助手类 -->
<tag-class>com.ruojuan.tag.IfTag</tag-class>
<!--代表是一个jsp标签 -->
<body-content>JSP</body-content>
<attribute>
<!--该自定义jsp标签的属性名称 -->
<name>test</name>
<!--该属性是否必填 -->
<required>true</required>
<!--该属性值是否支持该表带是 -->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>page</name>
<tag-class>com.ruojuan.tag.PageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>pageBean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3.框架的配置文件添加、以及web.xml的配置-以后开源框架的使用从这一步开始
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>mvc_crud</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.ruojuan.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>configLocation</param-name>
<param-value>/luoluo.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
4.完成Book实体类及bookDao的编写
实体类:
package com.ruojuan.entity;
public class Book {
private int bid;
private String bname;
private float price;
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Book() {
super();
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
}
Dao方法
package com.ruojuan.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import com.ruojuan.entity.Book;
import com.ruojuan.util.BaseDao;
import com.ruojuan.util.DBAccess;
import com.ruojuan.util.PageBean;
import com.ruojuan.util.StringUtils;
/**
* dao方法
* @author liuruojuan
*
* 时间:2022年6月28日下午6:13:00
*/
public class BookDao extends BaseDao<Book>{
//查询
public List<Book> list(Book book,PageBean pageBean) throws Exception{
String sql = "select * from t_mvc_book where 1=1";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql+=" and bname like '%"+bname+"%'";
}
int bid = book.getBid();
//前台jsp传递到后台,只要传了就有值
if(bid!=0) {
sql+=" and bid ="+bid;
}
return super.executeQuery(sql, pageBean, rs -> {
List<Book> list = new ArrayList<>();
try {
while(rs.next()) {
list.add(new Book(rs.getInt("bid"),rs.getString("bname"),rs.getFloat("price")));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
});
}
// //增加
// public int edit(Book book) throws Exception{
// Connection con = DBAccess.getConnection();
// String sql = "insert into t_mvc_book values (?,?,?)";
// PreparedStatement pst = con.prepareStatement(sql);
// pst.setObject(1, book.getBid());
// pst.setObject(2, book.getBname());
// pst.setObject(3, book.getPrice());
// return pst.executeUpdate();
//
// }
//增
public int add(Book book) throws Exception{
String sql = "insert into t_mvc_book values (?,?,?)";
return super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
}
// //删
// public int del(Book book) throws Exception{
// Connection con = DBAccess.getConnection();
// String sql = "delete from t_mvc_book where bid=?";
// PreparedStatement pst = con.prepareStatement(sql);
// pst.setObject(1, book.getBid());
// return pst.executeUpdate();
//
// }
//删
public int del(Book book) throws Exception{
String sql = "delete from t_mvc_book where bid=?";
return super.executeUpdate(sql, book, new String[] {"bid"});
}
// //改
// public int edit(Book book) throws Exception{
// Connection con = DBAccess.getConnection();
// String sql = "update t_mvc_book set bname=?,price=? where bid=?";
// PreparedStatement pst = con.prepareStatement(sql);
// pst.setObject(1, book.getBname());
// pst.setObject(2, book.getPrice());
// pst.setObject(3, book.getBid());
// return pst.executeUpdate();
//
// }
//改
public int edit(Book book) throws Exception{
String sql = "update t_mvc_book set bname=?,price=? where bid=?";
return super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
}
}
5.完成通用的增删改方法
public int executeUpdate(String sql,T t,String[] attrs ) throws Exception{
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
//将t的某一个属性对应的值加到pst对象中
for (int i = 0; i < attrs.length; i++) {
Field f = t.getClass().getDeclaredField(attrs[i]);
f.setAccessible(true);
pst.setObject(i+1, f.get(t));
}
return pst.executeUpdate();
6.完成BookAction
package com.ruojuan.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ruojuan.dao.BookDao;
import com.ruojuan.entity.Book;
import com.ruojuan.framework.ActionSupport;
import com.ruojuan.framework.ModelDriven;
import com.ruojuan.util.PageBean;
public class BookAction extends ActionSupport implements ModelDriven<Book>{
private Book book = new Book();
private BookDao bookDao = new BookDao();
@Override
public Book getModel() {
return book;
}
//增
public String add(HttpServletRequest request, HttpServletResponse response) {
try {
bookDao.add(book);
} catch (Exception e) {
e.printStackTrace();
}
//toList代表跳到查询页面
return "toList";
}
//删
public String del(HttpServletRequest request, HttpServletResponse response) {
try {
bookDao.del(book);
} catch (Exception e) {
e.printStackTrace();
}
//toList代表跳到查询页面
return "toList";
}
//改
public String edit(HttpServletRequest request, HttpServletResponse response) {
try {
bookDao.edit(book);
} catch (Exception e) {
e.printStackTrace();
}
//toList代表跳到查询页面
return "toList";
}
//查
public String list(HttpServletRequest request, HttpServletResponse response) {
try {
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
List<Book> list = bookDao.list(book,pageBean);
request.setAttribute("list", list);
request.setAttribute("pageBean", pageBean);
} catch (Exception e) {
e.printStackTrace();
}
//执行查询展示
return "list";
}
//跳转到新增/修改界面
public String preEdit(HttpServletRequest request, HttpServletResponse response) {
try {
int bid = book.getBid();
if(bid!=0) {
//传递bid到后台,有且只能查出一条数据,那也就意味着list集合中只要一条
List<Book> list = bookDao.list(book, null);
request.setAttribute("b", list.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
//toList代表跳到查询页面
return "toEdit";
}
}
7.完成mvc.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>mvc_crud</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.ruojuan.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>configLocation</param-name>
<param-value>/luoluo.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
8.完成前台代码的编写
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.ruojuan" prefix="r"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="css/bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="js/bootstrap.js"></script>
<!-- <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
-->
<title>书籍列表</title>
<style type="text/css">
.page-item input {
padding: 0;
width: 40px;
height: 100%;
text-align: center;
margin: 0 6px;
}
.page-item input, .page-item b {
line-height: 38px;
float: left;
font-weight: 400;
}
.page-item.go-input {
margin: 0 10px;
}
</style>
</head>
<!-- ${pageContext.request.contextPath } -->
<body>
<%-- <c:if test="${empty list }">
<jsp:forward page="book/search"></jsp:forward>
</c:if> --%>
<form class="form-inline"
action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
<div class="form-group mb-2">
<input type="text" class="form-control-plaintext" name="bname"
placeholder="请输入书籍名称">
</div>
<button type="submit" class="btn btn-primary mb-2">查询</button>
<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book.action?methodName=preEdit">增加</a>
</form>
<table class="table table-striped ">
<thead>
<tr>
<th scope="col">书籍ID</th>
<th scope="col">书籍名</th>
<th scope="col">价格</th>
<th scope="col">操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list }" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
<td>
<a href="${pageContext.request.contextPath }/book.action?methodName=preEdit&bid=${b.bid }">修改</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=del&bid=${b.bid }">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<r:page pageBean="${pageBean }"></r:page>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action = "${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post" >
bid:<input type="text" name="bid" value="${b.bid }"><br>
bname:<input type="text" name="bname" value="${b.bname }"><br>
price:<input type="text" name="price" value="${b.price }"><br>
<input type="submit">
</form>
</body>
</html>