Struts的增删改查

it2022-05-06  10

1、导入相关的pom依赖(struts、自定义标签库的依赖)

目录 将以下代码插入 pom.xm

<!-- 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>

pom.xml

<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.13</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> </dependencies> <build> <finalName>web_strust</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>

2、分页的tag类导入、d.tld、完成web.xml的配置

PageTag

package com.caoguangli.crud.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.caoguangli.crud.util.PageBean; public class PageTag extends BodyTagSupport { private static final long serialVersionUID = 5327538022285881545L; 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(toHTML()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return super.doStartTag(); } private String toHTML() { StringBuilder sb = new StringBuilder(); // 拼接下一次发送请求所要提交的隐藏的form表单 sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>"); sb.append("<input type='hidden' name='page'>"); Map<String, String[]> paMap = pageBean.getPaMap(); if(paMap != null && paMap.size() > 0 ) { Set<Entry<String,String[]>> entrySet = paMap.entrySet(); for (Entry<String, String[]> entry : entrySet) { // /**上一次请求可能携带页面 name=page 的参数,但是该参数在前面已经单独赋值 * 为什么要单独赋值呢? * 因为上一次请求可能是第二页,意味着前后请求page对应的值是不一样的,需要单独赋值 */ if(!"page".equals(entry.getKey())) { /** * <input type='hidden' name='hobby' value='1'> * <input type='hidden' name='hobby' value='2'> * [1,2] */ for (String val : entry.getValue()) { sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'> "); } } } } sb.append("</form>"); // 拼接分页条 sb.append("<div style='text-align: right; font-size: 12px;'>"); sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页  <a "); sb.append(" href='javascript:gotoPage(1)'>首页</a>  <a"); sb.append(" href='javascript:gotoPage("+pageBean.getPreviousPage()+")'>上一页</a>  <a"); sb.append(" href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页</a>  <a"); sb.append(" href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a>  <input type='text'"); sb.append(" id='skipPage'"); sb.append(" style='text-align: center; font-size: 12px; width: 50px;'>  <a"); sb.append(" href='javascript:skipPage()'>Go</a>"); sb.append("</div>"); // 拼接分页所需要的jsp代码 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.getMaxPage()+"){"); sb.append(" alert('请输入1~N的数字');"); sb.append(" return;"); sb.append(" }"); sb.append(" gotoPage(page);"); sb.append(" }"); sb.append("</script>"); return sb.toString(); } }

d.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>caoguangli 1.1 core library</description> <display-name>caoguangli core</display-name> <tlib-version>1.1</tlib-version> <short-name>c</short-name> <uri>/caoguangli</uri> <!-- page --> <tag> <!-- 标签库中的标签 (类似c:set c:out的定义) --> <name>page</name> <!-- 是标签运行具体代码,也就是助手类,下面填写的助手类的全路径名 --> <tag-class>com.caoguangli.crud.tag.PageTag</tag-class> <body-content>JSP</body-content> <attribute> <!-- 该标签的属性 --> <name>pageBean</name> <!-- 该属性是否必填 --> <required>true</required> <!-- 是否支持表达式 --> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>

web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.caoguangli.crud.util.EncodingFiter</filter-class> </filter> <filter-mapping> <filter-name>encodingFiter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>

3、dao层去访问数据

先建一个实体类 clazz

package com.caoguangli.crud.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; } public Clazz(int cid, String cname, String cteacher, String pic) { super(); this.cid = cid; this.cname = cname; this.cteacher = cteacher; this.pic = pic = "暂无图片"; } public Clazz() { super(); } @Override public String toString() { return "Class [cid=" + cid + ", cname=" + cname + ", cteacher=" + cteacher + ", pic=" + pic + "]"; } }

然后写ClazzDao

package com.caoguangli.crud.dao; import java.sql.SQLException; import java.util.List; import com.caoguangli.crud.entity.Clazz; import com.caoguangli.crud.util.BaseDao; import com.caoguangli.crud.util.PageBean; import com.caoguangli.crud.util.StringUtils; public class ClazzDao extends BaseDao<Clazz> { /** * 查询方法 * @param clazz * @param pageBean * @return * @throws InstantiationException * @throws IllegalAccessException * @throws SQLException */ public List<Clazz> list(Clazz clazz, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{ 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 SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ public int add(Clazz clazz) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException { 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 SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ public int del(Clazz clazz) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException { String sql = "delete from t_struts_class where cid=?"; return super.executeUpdate(sql, new String[] {"cid"}, clazz); } /** * 修改方法 * @param clazz * @return * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ public int edit(Clazz clazz) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException { String sql = "update t_struts_class set cname=?,cteacher=?,pic=? where cid=?"; return super.executeUpdate(sql, new String[] {"cname","cteacher","pic","cid"}, clazz); } }

4、web层去调用dao层给前台返回数据

ClazzAction

package com.caoguangli.crud.web; import java.sql.SQLException; import java.util.List; import com.caoguangli.crud.dao.ClazzDao; import com.caoguangli.crud.entity.Clazz; import com.caoguangli.crud.util.BaseAction; import com.caoguangli.crud.util.PageBean; import com.opensymphony.xwork2.ModelDriven; public class ClazzAction extends BaseAction implements ModelDriven<Clazz> { private Clazz clazz = new Clazz(); private ClazzDao clazzDao = new ClazzDao(); /** * 查询方法 * @return * @throws InstantiationException * @throws IllegalAccessException * @throws SQLException */ public String list() throws InstantiationException, IllegalAccessException, SQLException { PageBean pageBean = new PageBean(); pageBean.setRequest(request); List<Clazz> list = this.clazzDao.list(clazz, pageBean); request.setAttribute("clazzList", list); request.setAttribute("pageBean", pageBean); return "list"; } /** * 跳转编辑页面(新增修改页面) * @return */ public String preSave() { if(clazz.getCid() != 0) { try { this.result = this.clazzDao.list(clazz, null).get(0); } catch (InstantiationException | IllegalAccessException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "preSave"; } public String add() { try { this.clazzDao.add(clazz); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "toList"; } public String edit() { try { this.clazzDao.edit(clazz); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "toList"; } public String del() { try { this.clazzDao.del(clazz); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "toList"; } @Override public Clazz getModel() { // TODO Auto-generated method stub return clazz; } }

5、在struts_sy.xml进行配置

struts_sy.xml

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="sy" extends="base" namespace="/sy"> <action name="/hello_*" class="com.caoguangli.one.web.HelloAction" method="{1}"> <result name="success">/success.jsp</result> </action> <action name="/demo_*" class="com.caoguangli.test.Demo7" method="{1}"> <result name="success">/success.jsp</result> </action> <action name="/clazz_*" class="com.caoguangli.crud.web.ClazzAction" method="{1}"> <result name="list">/clazzList.jsp</result> <result name="preSave">/clazzEdit.jsp</result> <result name="toList" type="redirectAction">/clazz_list</result> </action> </package> </struts>

6、写jsp

clazzList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="/caoguangli" prefix="d" %> <!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> <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>

clazzEdit.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>

页面效果:


最新回复(0)