struts2--CRUD
struts的CRUD
1、导入相关的pom依赖(struts、自定义标签库的依赖)
<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> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jsp-api</artifactId> <version>8.0.47</version> </dependency>
2、分页的tag类导入、z.tld、完成web.xml的配置
2.1 PageTag
1 package com.yuan.crud.tag; 2 3 import java.io.IOException; 4 import java.util.Map; 5 import java.util.Map.Entry; 6 import java.util.Set; 7 8 import javax.servlet.jsp.JspException; 9 import javax.servlet.jsp.JspWriter; 10 import javax.servlet.jsp.tagext.BodyTagSupport; 11 12 import com.yuan.crud.util.PageBean; 13 14 public class PageTag extends BodyTagSupport { 15 16 /** 17 * 18 */ 19 private static final long serialVersionUID = 1L; 20 21 private PageBean pageBean; 22 23 public PageBean getPageBean() { 24 return pageBean; 25 } 26 27 public void setPageBean(PageBean pageBean) { 28 this.pageBean = pageBean; 29 } 30 31 @Override 32 public int doStartTag() throws JspException { 33 JspWriter out = pageContext.getOut(); 34 try { 35 out.print(toHTML()); 36 } catch (IOException e) { 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 } 40 return super.doStartTag(); 41 } 42 43 private String toHTML() { 44 StringBuilder sb= new StringBuilder(); 45 46 //拼接下一次发送请求所要提交的隐藏的form表单 47 sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>"); 48 sb.append("<input type='hidden' name='page'>"); 49 50 Map<String, String[]> paMap = pageBean.getPaMap(); 51 if(paMap != null && paMap.size()>0) { 52 Set<Entry<String, String[]>> entrySet = paMap.entrySet(); 53 for (Entry<String, String[]> entry : entrySet) { 54 //上一次请求可能携带页码name=page的参数,但是改参数在前面已经单独赋值, 55 //因为上一次请求是第一页的数据,下一次可能是第二页,一位这前后请求page对应的值是不一样的,需要单独赋值 56 57 if(!"page".equals(entry.getKey())) { 58 for(String val:entry.getValue()) { 59 sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>"); 60 61 } 62 } 63 } 64 } 65 66 sb.append("</form>"); 67 68 69 //拼接分页条 70 sb.append("<div style='text-align: right; font-size: 12px;'>"); 71 sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页 <a "); 72 sb.append(" href='javascript:gotoPage(1)'>首页</a> <a"); 73 sb.append(" href='javascript:gotoPage("+pageBean.getPreviousPage()+")'>上一页</a> <a"); 74 sb.append(" href='javascript:gotoPage("+pageBean.getNexPage()+")'>下一页</a> <a"); 75 sb.append(" href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a> <input type='text'"); 76 sb.append(" id='skipPage'"); 77 sb.append(" style='text-align: center; font-size: 12px; width: 50px;'> <a"); 78 sb.append(" href='javascript:skipPage()'>Go</a>"); 79 sb.append("</div>"); 80 //拼接分页所需要的js代码 81 sb.append("<script type='text/javascript'>"); 82 sb.append(" function gotoPage(page) {"); 83 sb.append(" document.getElementById('pageBeanForm').page.value = page;"); 84 sb.append(" document.getElementById('pageBeanForm').submit();"); 85 sb.append(" }"); 86 sb.append(" function skipPage() {"); 87 sb.append(" var page = document.getElementById('skipPage').value;"); 88 sb.append(" if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>"+pageBean.getMaxPage()+"){"); 89 sb.append(" alert('请输入1~N的数字');"); 90 sb.append(" return;"); 91 sb.append(" }"); 92 sb.append(" gotoPage(page);"); 93 sb.append(" }"); 94 sb.append(" </script>"); 95 96 return sb.toString(); 97 } 98 99 100 }
2.2 mytag.tld
1 <!DOCTYPE taglib 2 PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" 3 "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> 4 <!-- 标签库描述符 --> 5 <taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor"> 6 <!-- 代表标签库的版本号 --> 7 <tlib-version>1.0</tlib-version> 8 <!-- 代表jsp的版本 --> 9 <jsp-version>1.2</jsp-version> 10 <!-- 你的标签库的简称 --> 11 <short-name>test</short-name> 12 <!-- 你标签库的引用uri --> 13 <uri>/zking</uri> 14 15 <!-- 1自定义分页标签 --> 16 <tag> 17 <name>Page</name> 18 <tag-class>com.yuan.crud.tag.PageTag</tag-class> 19 <body-content>JSP</body-content> 20 <attribute> 21 <name>pageBean</name> 22 <required>true</required> 23 <rtexprvalue>true</rtexprvalue> 24 </attribute> 25 </tag> 26 27 28 29 30 </taglib>
2.3 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.yuan.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层去访问数据 Clazz实体类
3.1 ClazzDao
1 package com.yuan.crud.dao; 2 3 import java.sql.SQLException; 4 import java.util.List; 5 6 import com.yuan.crud.entity.Clazz; 7 import com.yuan.crud.util.BaseDao; 8 import com.yuan.crud.util.PageBean; 9 import com.yuan.crud.util.StringUtils; 10 11 public class ClazzDao extends BaseDao<Clazz> { 12 13 public List<Clazz> list(Clazz clazz,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{ 14 String sql="select * from t_struts_class where true "; 15 String cname= clazz.getCname(); 16 int cid=clazz.getCid(); 17 if(cid!=0) { 18 sql += " and cid="+cid; 19 } 20 if(StringUtils.isNotBlank(cname)) { 21 sql += " and cname like '%"+cname+"%'"; 22 } 23 return super.executeQuery(sql , Clazz.class, pageBean); 24 } 25 26 27 public int add(Clazz clazz) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException { 28 String sql ="insert into t_struts_class values(?,?,?,?)"; 29 return executeUpdate(sql, new String[] {"cid","cname","cteacher","pic"}, clazz); 30 } 31 32 public int del(Clazz clazz) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException { 33 String sql ="delete from t_struts_class where cid=?"; 34 return executeUpdate(sql, new String[] {"cid"}, clazz); 35 } 36 37 public int edit(Clazz clazz) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException { 38 String sql ="update t_struts_class set cname = ?,cteacher=?,pic=? where cid=?"; 39 return executeUpdate(sql, new String[] {"cname","cteacher","pic","cid"}, clazz); 40 } 41 42 43 44 45 }
3.2 Clazz
1 package com.yuan.crud.entity; 2 3 public class Clazz{ 4 5 6 private int cid; 7 private String cname; 8 private String cteacher; 9 private String pic; 10 public int getCid() { 11 return cid; 12 } 13 public void setCid(int cid) { 14 this.cid = cid; 15 } 16 public String getCname() { 17 return cname; 18 } 19 public void setCname(String cname) { 20 this.cname = cname; 21 } 22 public String getCteacher() { 23 return cteacher; 24 } 25 public void setCteacher(String cteacher) { 26 this.cteacher = cteacher; 27 } 28 public String getPic() { 29 return pic; 30 } 31 public void setPic(String pic) { 32 this.pic = pic; 33 } 34 @Override 35 public String toString() { 36 return "Clazz [cid=" + cid + ", cname=" + cname + ", cteacher=" + cteacher + ", pic=" + pic + "]"; 37 } 38 39 40 41 42 }
4、web层去调用dao层给前台返回数据
4.1 BaseAction
1 package com.yuan.crud.web; 2 3 import javax.servlet.ServletContext; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 import javax.servlet.http.HttpSession; 7 8 import org.apache.struts2.interceptor.ServletRequestAware; 9 import org.apache.struts2.interceptor.ServletResponseAware; 10 11 /** 12 * 每一个开发的子控制器要用的属性都定义在通用的action中。 13 * @author Administrator 14 * 15 */ 16 public class BaseAction implements ServletRequestAware, ServletResponseAware{ 17 /** 18 * 为了传值使用 19 */ 20 protected HttpServletResponse response; 21 protected HttpServletRequest request; 22 protected HttpSession session; 23 protected ServletContext application; 24 25 /** 26 * 为了配置跳转页面所用 27 */ 28 protected final static String SUCCESS = "success"; 29 protected final static String FAIL = "fail"; 30 protected final static String LIST = "list"; 31 protected final static String ADD = "add"; 32 protected final static String EDIT = "edit"; 33 protected final static String DETAIL = "detail"; 34 35 /** 36 * 具体传值字段 后端向jsp页面传值所用字段 37 */ 38 protected Object result; 39 protected Object msg; 40 protected int code; 41 42 public Object getResult() { 43 return result; 44 } 45 46 public Object getMsg() { 47 return msg; 48 } 49 50 public int getCode() { 51 return code; 52 } 53 54 @Override 55 public void setServletResponse(HttpServletResponse arg0) { 56 this.response = arg0; 57 58 } 59 60 @Override 61 public void setServletRequest(HttpServletRequest arg0) { 62 this.request = arg0; 63 this.session = arg0.getSession(); 64 this.application = arg0.getServletContext(); 65 } 66 67 68 }
4.2 ClazzAction
1 package com.yuan.crud.web; 2 3 import java.sql.SQLException; 4 import java.util.List; 5 6 import com.opensymphony.xwork2.ModelDriven; 7 import com.yuan.crud.dao.ClazzDao; 8 import com.yuan.crud.entity.Clazz; 9 import com.yuan.crud.util.PageBean; 10 11 public class ClazzAction extends BaseAction implements ModelDriven<Clazz>{ 12 13 private Clazz clz = new Clazz(); 14 private ClazzDao clzdao = new ClazzDao(); 15 16 /** 17 * 查询 18 * @return 19 */ 20 public String list() { 21 PageBean pageBean = new PageBean(); 22 pageBean.setRequest(request); 23 try { 24 List<Clazz> list = this.clzdao.list(clz, pageBean); 25 System.out.println(list); 26 request.setAttribute("clzList", list); 27 request.setAttribute("pageBean", pageBean); 28 } catch (InstantiationException | IllegalAccessException | SQLException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 } 32 return "list"; 33 } 34 35 /** 36 * 跳转编辑页面(新增修改页面) 37 * @return 38 */ 39 public String preSave() { 40 if(clz.getCid()!=0) { 41 try { 42 this.result = this.clzdao.list(clz, null).get(0); 43 } catch (InstantiationException | IllegalAccessException | SQLException e) { 44 // TODO Auto-generated catch block 45 e.printStackTrace(); 46 } 47 } 48 return "preSave"; 49 } 50 51 public String add() { 52 try { 53 this.code = this.clzdao.add(clz); 54 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException 55 | SQLException e) { 56 // TODO Auto-generated catch block 57 e.printStackTrace(); 58 } 59 return "toList"; 60 } 61 62 public String edit() { 63 try { 64 this.clzdao.edit(clz); 65 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException 66 | SQLException e) { 67 // TODO Auto-generated catch block 68 e.printStackTrace(); 69 } 70 return "toList"; 71 } 72 73 public String del() { 74 try { 75 this.clzdao.del(clz); 76 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException 77 | SQLException e) { 78 // TODO Auto-generated catch block 79 e.printStackTrace(); 80 } 81 return "toList"; 82 } 83 84 85 @Override 86 public Clazz getModel() { 87 88 return clz; 89 } 90 91 }
5、在struts_sy.xml进行配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" 4 "http://struts.apache.org/dtds/struts-2.5.dtd"> 5 <struts> 6 <package name="sy" extends="base" namespace="/sy"> 7
8
9
10 11 12 <action name="/clz_*" class="com.yuan.crud.web.ClazzAction" method="{1}"> 13 <result name="list">/clzList.jsp</result> 14 <result name="preSave">/clzEdit.jsp</result> 15 <result name="toList" type="redirectAction">clz_list</result> 16 </action> 17 </package> 18 </struts>
6、写jsp
6.1 clzList.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 <%@taglib prefix="z" uri="/****"%> 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6 <html> 7 <head> 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 9 <title>Insert title here</title> 10 </head> 11 <body> 12 <form action="${pageContext.request.contextPath }/sy/clz_list.action" method="post"> 13 14 班级名: <input type="text" name="cname" /><input type="submit" value="确定"/> 15 16 </form> 17 <a href="${pageContext.request.contextPath }/sy/clz_preSave.action">新增</a> 18 <table border="1" width="100%"> 19 <tr> 20 <td>编号</td> 21 <td>班级名</td> 22 <td>教员</td> 23 <td>图片</td> 24 <td>操作</td> 25 </tr> 26 27 <c:forEach items="${clzList }" var="c"> 28 <tr> 29 <td>${c.cid }</td> 30 <td>${c.cname }</td> 31 <td>${c.cteacher }</td> 32 <td>${c.pic }</td> 33 34
35
36 <td> 37 <a href="${pageContext.request.contextPath }/sy/clz_preSave.action?cid=${c.cid}">修改</a> 38 <a href="${pageContext.request.contextPath }/sy/clz_del.action?cid=${c.cid}">删除</a> 39 <a href="${pageContext.request.contextPath }/sy/clz_preUpload.action?cid=${c.cid}">图片上传</a> 40 </td> 41 </tr> 42 </c:forEach> 43 </table> 44 <z:Page pageBean="${pageBean }"></z:Page> 45 </body> 46 </html>
6.2 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>
7.页面显示
7.1首页
7.2 新增
7.3 修改
显示