1、导入相关的pom依赖(struts、自定义标签库的依赖)
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- 5.3、jstl、standard --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- 5.4、tomcat-jsp-api --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jsp-api</artifactId> <version>8.0.47</version> </dependency>
2、分页的tag类导入、z.tld、完成web.xml的配置
PageTag
package com.tag; import java.util.Map; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import com.util.PageBean; public class PageTag extends BodyTagSupport { private static final long serialVersionUID = 8003507841172246203L; private PageBean pageBean; public PageTag() { super(); } public PageBean getPageBean() { return pageBean; } public void setPageBean(PageBean pageBean) { this.pageBean = pageBean; } @Override public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); out.println(this.toHtml()); return SKIP_BODY; } catch (Exception e) { throw new RuntimeException(e); } } private String toHtml() { StringBuffer bf = new StringBuffer(); if (null == pageBean || !pageBean.isPagination()) { return bf.toString(); } // 1. 生成表单 bf.append("<form id='pageBeanForm' action='" + pageBean.getUrl() + "' method='post'>"); bf.append("<input type='hidden' name='page' value=''>"); for (Map.Entry<String, String[]> entry : pageBean.getParameterMap().entrySet()) { String name = entry.getKey(); String[] values = entry.getValue(); if ("page".equals(name)) { continue; } for (String value : values) { bf.append("<input type='hidden' name='" + name + "' value='" + value + "'>"); } } bf.append("</form>"); // 2. 生成按钮 bf.append("<div style='text-align: right;font-size: 12px;'>每页" + pageBean.getRows() + "条,共" + pageBean.getTotal() + "条,当前第" + pageBean.getPage() + "页,共" + pageBean.getMaxPage() + "页 <a href='javascript:doGotoPage(1)'>首 页</a> <a href='javascript:doGotoPage(" + pageBean.getPreviousPage() + ")'>上一页</a> <a href='javascript:doGotoPage(" + pageBean.getNextPage() + ")'>下一页</a> <a href='javascript:doGotoPage(" + pageBean.getMaxPage() + ")'>尾 页</a> <input id='pageNumber' type='text' style='text-align: center;width: 30px;'> <a href='javascript:doSkipPage();'>GO</a></div>"); // 3. 动态生成js bf.append("<script type='text/javascript'>"); bf.append("function doGotoPage(page){"); bf.append(" var form = document.getElementById('pageBeanForm');"); bf.append(" form.page.value = page;"); bf.append(" form.submit();"); bf.append("}"); bf.append("function doSkipPage(page){"); bf.append(" var page = document.getElementById('pageNumber').value;"); bf.append(" if(!page||isNaN(page)||parseInt(page)<1||parseInt(page)>"+pageBean.getMaxPage()+"){"); bf.append(" alert('页码必须为1~"+pageBean.getMaxPage()+"之间数字');"); bf.append(" document.getElementById('pageNumber').value = '';"); bf.append(" return;"); bf.append(" }"); bf.append(" doGotoPage(parseInt(page));"); bf.append("}"); bf.append("</script>"); bf.append(""); bf.append(""); bf.append(""); bf.append(""); bf.append(""); return bf.toString(); } }
z.tld
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <!-- 标签库描述符 --> <taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor"> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>Simple Tags</short-name> <uri>/zking</uri> <tag> <name>page</name> <tag-class>com.tag.PageTag</tag-class> <body-content>empty</body-content> <attribute> <name>pageBean</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
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" version="3.1"> <display-name>Archetype Created Web Application</display-name> <filter> <filter-name>encodingFiter</filter-name> <filter-class>com.util.EncodingFiter</filter-class> </filter> <filter-mapping> <filter-name>encodingFiter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.factory.StrutsActionProxy</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>
3、dao层去访问数据
创建与数据库相对应的实体类
Clazz
package com.entity;
public class Clazz {
private int cid;
private String cname;
private String cteacher;
private String pic;
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCteacher() {
return cteacher;
}
public void setCteacher(String cteacher) {
this.cteacher = cteacher;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
@Override
public String toString() {
return "Clazz [cid=" + cid + ", cname=" + cname + ", cteacher=" + cteacher + ", pic=" + pic + "]";
}
}
ClazzDao
package com.dao; import java.sql.SQLException; import java.util.List; import com.entity.Clazz; import com.util.BaseDao; import com.util.PageBean; import com.util.StringUtils; public class ClazzDao extends BaseDao<Clazz>{ /** * 查詢 * @param clazz * @param pageBean * @return * @throws Exception */ public List<Clazz> list(Clazz clazz,PageBean pageBean) throws Exception{ String sql="select * from t_struts_class where true "; String cname=clazz.getCname(); int cid=clazz.getCid(); if(cid!=0) { sql+=" and cid="+cid; } if(StringUtils.isNotBlank(cname)) { sql+=" and cname like '%"+cname+"%'"; } return super.executeQuery(sql, Clazz.class, pageBean); } /** * 新增 * @param clazz * @return * @throws NoSuchFieldException * @throws Exception */ public int add(Clazz clazz) throws NoSuchFieldException, Exception { String sql="insert into t_struts_class values(?,?,?,?)"; return super.executeUpdate(sql, new String [] {"cid","cname","cteacher","pic"}, clazz); } /** * 删除 * @param clazz * @return * @throws NoSuchFieldException * @throws Exception */ public int del(Clazz clazz) throws NoSuchFieldException, Exception { String sql="delete from t_struts_class where cid=? "; return super.executeUpdate(sql, new String [] {"cid"}, clazz); } /** * 修改 * @param clazz * @return * @throws NoSuchFieldException * @throws Exception */ public int edit(Clazz clazz) throws NoSuchFieldException, Exception { String sql=" update t_struts_class set cname= ? , chteacher=? ,pic=? where cid=? "; return super.executeUpdate(sql, new String [] {"cname","cteacher","pic","cid"}, clazz); } }
4、web层去调用dao层给前台返回数据
ClazzAction
package com.web; import java.util.List; import com.dao.ClazzDao; import com.entity.Clazz; import com.opensymphony.xwork2.ModelDriven; import com.util.PageBean; public class ClazzAction extends BaseAction implements ModelDriven<Clazz>{ private Clazz clz=new Clazz(); private ClazzDao clazzDao=new ClazzDao(); public String list() { PageBean pageBean=new PageBean(); pageBean.setRequest(request); try { List<Clazz> list=this.clazzDao.list(clz, pageBean); request.setAttribute("clzList", list); request.setAttribute("pageBean", pageBean); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "list"; } /** * 跳转编辑页面(新增修改页面) */ public String preSave() { if(clz.getCid()!=0) { try { this.result=this.clazzDao.list(clz, null).get(0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "preSave"; } public String add() { try { this.code=this.clazzDao.add(clz); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "toList"; } public String edie() { try { this.clazzDao.edit(clz); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "toList"; } public String del() { try { this.clazzDao.del(clz); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "toList"; } @Override public Clazz getModel() { // TODO Auto-generated method stub return clz; } }
5、在struts_sy.xml进行配置
<action name="/clz_*" class="com.web.ClazzAction" method="{1}"> <result name="list">/clzList.jsp</result> <result name="preSave">/clzEdit.jsp</result> <result name="toList" type=" redirectAction">/clz_List</result> </action>
6、写jsp页面
clzList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page isELIgnored="false"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@taglib prefix="z" uri="/zking"%> <!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> <h2>小说目录</h2> <br> <form action="${pageContext.request.contextPath}/sy/clazz_list.action" method="post"> 班级名称:<input type="text" name="cname"> <input type="submit" value="确定"> <input type="hidden" name="rows" value="15"> </form> <a href="${pageContext.request.contextPath}/sy/clazz_preSave.action">增加</a> <table border="1" width="100%"> <tr> <td>编号</td> <td>班级名称</td> <td>教员</td> <td>班级图片</td> <td>操作</td> </tr> <c:forEach items="${clazzList }" var="c"> <tr> <td>${c.cid }</td> <td>${c.cname }</td> <td>${c.cteacher }</td> <td>${c.pic }</td> <td><a href="${pageContext.request.contextPath}/sy/clazz_preSave.action?cid=${c.cid}">修改</a> <a href="${pageContext.request.contextPath}/sy/clazz_del.action?cid=${c.cid}">删除</a> <a href="${pageContext.request.contextPath}/sy/clazz_preUpload.action?cid=${c.cid}">图片上传</a> </td> </tr> </c:forEach> </table> <d:page pageBean="${pageBean }"></d:page> </body> </html>
ClzEdit.jsp
<%@ 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>班级编辑界面</title> </head> <body> <form action="${pageContext.request.contextPath}${result.cname == null ? '/sy/clazz_add.action' : '/sy/clazz_edit.action' }" method="post"> <%-- <input type="hidden" name="methodName" value="${book.bname == null ? 'add' : 'edit' }"> --%> cid:<input type="text" name="cid" value="${result.cid }"><br> cname:<input type="text" name="cname" value="${result.cname }"><br> cteacher:<input type="text" name="cteacher" value="${result.cteacher }"><br> <input type="submit"> </form> </body> </html>
页面效果