struts的增删改查
Posted bf6rc9qu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts的增删改查相关的知识,希望对你有一定的参考价值。
1、导入相关的pom依赖(struts、自定义标签库的依赖)
<!-- 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.java
package com.huang.crud.tag; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import com.huang.crud.util.PageBean; public class PageTag extends BodyTagSupport private static final long serialVersionUID = -8476740758233598045L; private PageBean pageBean; @Override public int doStartTag() throws JspException JspWriter out = pageContext.getOut(); try out.write(tohtml()); catch (IOException e) e.printStackTrace(); return super.doStartTag(); public String toHTML() // pageBean=new PageBean(); StringBuffer sb=new StringBuffer(); //下一次请求提交到后台的表单html代码拼接 sb.append("<link rel=\\"stylesheet\\" type=\\"text/css\\" href=\\"css/bootstrap.min.css\\"/>"); sb.append("<script type=\\"text/javascript\\" src=\\"js/jquery-3.3.1.js\\"></script>"); sb.append("<script type=\\"text/javascript\\" src=\\"js/bootstrap.min.js\\"></script>"); sb.append("<form id=‘pageBeanForm‘ action=‘"+pageBean.getUrl()+"‘ method=‘post‘>"); Map<String, String[]> paramMap = pageBean.getParameterMap(); if(paramMap!=null&¶mMap.size()>0) for(Entry<String, String[]> entry:paramMap.entrySet()) if(!"page".equals(entry.getKey())) for(String val:entry.getValue()) sb.append("<input type=‘hidden‘ name=‘"+entry.getKey()+"‘> value=‘"+val+"‘"); sb.append("<input type=‘hidden‘ name=‘page‘>"); sb.append("</form>"); //分页条html代码拼接 sb.append("<div style=‘text-align: right; font-size: 12px;‘>"); sb.append(" 每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页 "); sb.append(" <a href=‘javascript:gotoPage(1)‘ class=‘btn btn-default‘>首页</a> <a"); sb.append(" href=‘javascript:gotoPage("+pageBean.getPreviousPage()+")‘ class=‘btn btn-default‘>上一页</a> <a"); sb.append(" href=‘javascript:gotoPage("+pageBean.getNextPage()+")‘ class=‘btn btn-default‘>下一页</a> <a"); sb.append(" href=‘javascript:gotoPage("+pageBean.getMaxPage()+")‘ class=‘btn btn-default‘>尾页</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()‘ class=‘btn btn-default‘>Go</a>"); sb.append(" </div>"); //分页所需要调用的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.getMaxPage()+")"); sb.append(" alert(‘请输入1~N的数字‘);"); sb.append(" return;"); sb.append(" "); sb.append(" gotoPage(page);"); sb.append(" "); sb.append("</script>"); return sb.toString(); public PageBean getPageBean() return pageBean; public void setPageBean(PageBean pageBean) this.pageBean = pageBean;
z.tid
<?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>dj 1.1 core library</description> <display-name>dj core</display-name> <tlib-version>1.1</tlib-version> <short-name>d</short-name> <uri>/huang</uri> <tag> <name>page</name> <tag-class>com.huang.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.huang.crud.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.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>
3、dao层去访问数据
ClazzDao.java
package com.huang.crud.dao; import java.sql.SQLException; import java.util.List; import com.huang.crud.entity.Clazz; import com.huang.crud.util.BaseDao; import com.huang.crud.util.PageBean; import com.huang.crud.util.StringUtils; public class ClazzDao extends BaseDao<Clazz> 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); public int add(Clazz clazz) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException, InstantiationException String sql= "insert into t_struts_class values(?,?,?,?)"; return super.executeUpdate(sql,new String[] "cid","cname","cteacher","pic", clazz); public int del(Clazz clazz) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException, InstantiationException String sql= "delete from t_struts_class where cid=?"; return super.executeUpdate(sql,new String[] "cid", clazz); public int edit(Clazz clazz) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException, InstantiationException String sql= "update t_struts_class set cname=?,cteacher=?,pic=? where cid=?"; return super.executeUpdate(sql,new String[] "cname","cteacher","pic","cid", clazz);
BaseDao.java
package com.huang.crud.util; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.huang.crud.entity.Clazz; public class BaseDao<T> /** * T=Student.class * * @param sql 决定查询哪张表的数据 * @param clz 查询出来的数据封装到哪个实体类中 * @param pageBean 决定是否分页 * @return * @throws * @throws InstantiationException * @throws SQLException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InstantiationException */ public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, IllegalArgumentException, IllegalAccessException, InstantiationException List<T> ls=new ArrayList<>(); Connection con=DBAccess.getConnection(); PreparedStatement ps = null; ResultSet rs = null; if(pageBean!=null && pageBean.isPagination()) //该分页了 String countSql=getCountSql(sql);//获取符合记录的行数的Sql语句 try ps=con.prepareStatement(countSql); catch (SQLException e) e.printStackTrace(); try rs=ps.executeQuery(); catch (SQLException e) e.printStackTrace(); if(rs.next()) pageBean.setTotal(rs.getLong(1)+"");//给pageBean的总页数赋值 String pageSql=getPageSql(sql,pageBean);//拼接上符合条件的分页查询sql语句 ps=con.prepareStatement(pageSql); rs=ps.executeQuery(); else ps = con.prepareStatement(sql); rs = ps.executeQuery(); try while (rs.next()) // ls.add(new Book(rs.getInt("bid"), // rs.getString("bname"), // rs.getFloat("price"))); /** * 1、创建了一个book对象 * 2、从ResultSet结果集中获取值放入Book对象属性中 * 2.1获取到book的属性对象 * 2.2给属性对象赋值 * 3、将已经有值的Book对象放进list集合中 * */ T t = (T) clz.newInstance(); Field[] fields = clz.getDeclaredFields(); for (Field field : fields) field.setAccessible(true); field.set(t, rs.getObject(field.getName())); ls.add(t); finally DBAccess.close(con,ps,rs); return ls; /** * 将原生sql拼接出符合条件的某一页的数据查询 * @param sql * @return */ private String getPageSql(String sql,PageBean pageBean) return sql + " limit "+pageBean.getStartIndex()+","+pageBean.getRows(); /** * 用原生sql拼接出查询符合条件的记录数 * @param sql * @return */ private String getCountSql(String sql) return "select count(1) from ("+sql+") t"; /** * 通用的增删改方法 * @param sql 增删改的sql语句 * @param attrs ?所代表的实体类的属性 * @param t 实体类的实例 * @return * @throws SQLException * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InstantiationException */ public int executeUpdate(String sql, String[] attrs, T t) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException Connection con = DBAccess.getConnection(); PreparedStatement pst = con.prepareStatement(sql); for (int i = 0; i < attrs.length; i++) Field field = t.getClass().getDeclaredField(attrs[i]); field.setAccessible(true); pst.setObject(i+1, field.get(t)); return pst.executeUpdate();
4、在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="/clz_*" class="com.huang.crud.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> </package> </struts>
5、写jsp
clzList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="/huang" 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/clz_list.action" method="post"> 书名:<input type="text" name="bname"> <input type="submit" value="确定"> <input type="hidden" name="rows" value="15"> </form> <a href="$pageContext.request.contextPath/sy/clz_preSave.action">增加</a> <table border="1" width="100%"> <tr> <td>编号</td> <td>班级名称</td> <td>班级图片</td> <td>操作</td> </tr> <c:forEach items="$clzList " var="b"> <tr> <td>$b.cid </td> <td>$b.cname </td> <td>$b.cteacher </td> <td>$b.pic </td> <td> <a href="$pageContext.request.contextPath/sy/clz_preSave.action?cid=$b.cid">修改</a> <a href="$pageContext.request.contextPath/sy/clz_del.action?cid=$b.cid">删除</a> <a href="$pageContext.request.contextPath/sy/clz_preUpload.action?cid=$b.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>Insert title here</title> </head> <body> <form action="$pageContext.request.contextPath $result.cname == null ? ‘/sy/clz_add.action‘ : ‘/sy/clz_edit.action‘" method="post"> cid:<input type="text" name="cid" value="$result.cid "/> cname:<input type="text" name="cname" value="$result.cname "/> cteacher:<input type="text" name="cteacher" value="$result.cteacher "/> <input type="submit"/> </form> </body> </html>
运行结果:
以上是关于struts的增删改查的主要内容,如果未能解决你的问题,请参考以下文章