Struts2 -- add, delete, modify and query

Posted by GateGuardian on Sat, 02 Nov 2019 08:29:39 +0100

Using struts to complete adding, deleting, modifying and checking
Ideas:
1. Import related pom dependencies (struts, custom tag library dependency)
2. Import the paginated tag class, z.tld, and complete the configuration of web.xml
3. dao layer to access data
4. The web layer calls the dao layer to return data to the foreground.
5. Configure in struts_sy.xml
6. Write jsp page

 

 

pom dependence

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

 

Pagination tag class import, z.tld (because today's main topic is about the addition, deletion, and modification of Struts, which is not detailed for pagination)

PageTag:

package com.psy.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.psy.crud.util.PageBean;

public class PageTag extends BodyTagSupport {

	private static final long serialVersionUID = 1L;
	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() {
		StringBuffer sb = new StringBuffer();
		/*
		 * Splicing form forms that submit data to the background
		 * 	Note: the page parameter in the spliced form is changed, so you do not need to keep the last requested value
		 */
		sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
		sb.append("<input type='hidden' name='page'>");
		Map<String, String[]> parameterMap = pageBean.getParameterMap();
		if(parameterMap != null && parameterMap.size() > 0) {
			Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
			for (Entry<String, String[]> entry : entrySet) {
				if(!"page".equals(entry.getKey())) {
					String[] values = entry.getValue();
					for (String val : values) {
						sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>");
					}
				}
			}
		}
		sb.append("</form>");
		
		/*
		 * Displayed page bar
		 */
		sb.append("<div style='text-align: right; font-size: 12px;'>");
		sb.append("each page"+pageBean.getRows()+"A total of"+pageBean.getTotal()+"Clause No."+pageBean.getPage()+"Page, total"+pageBean.getMaxPage()+"page  <a href='javascript:gotoPage(1)'>home page</a>  <a");
		sb.append(" href='javascript:gotoPage("+pageBean.previousPage()+")'>Previous page</a>  <a");
		sb.append(" href='javascript:gotoPage("+pageBean.nextPage()+")'>next page</a>  <a");
		sb.append(" href='javascript:gotoPage("+pageBean.getMaxPage()+")'>Tail page</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>");
		
		/*
		 * Add js code for paging bar to interact with background
		 */
		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('Please input 1~N Figures');");
		sb.append("				return;");
		sb.append("			}");
		sb.append("			gotoPage(page);");
		sb.append("		}");
		sb.append("</script>");
		return sb.toString();
	}
}

  z.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>zking 1.1 core library</description>
  <display-name>zking core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>/zking</uri>

 <tag>
    <name>page</name>
    <tag-class>com.psy.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:

<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.psy.crud.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

dao layer:

package com.psy.crud.dao;

import java.util.List;

import com.psy.crud.entity.Clazz;
import com.psy.crud.util.BaseDao;
import com.psy.crud.util.PageBean;
import com.psy.crud.util.StringUtils;

public class ClzDao extends BaseDao<Clazz> {

	/**
	 * Query paging method, common method for querying single data
	 * @param clz
	 * @param pageBean
	 * @return
	 */
	public List<Clazz> list(Clazz clz,PageBean pageBean){
		String sql="select * from t_struts_class where true";
		String cname=clz.getCname();
		int cid=clz.getCid();
		if(cid!=0) {
			sql +=" and cid="+cid;
		}
		if(StringUtils.isNotBlank(cname)) {
			sql +=" and cname like '%"+cname+"%'";
		}
		
		return super.executeQuery(sql, Clazz.class, pageBean);
		
	}
	
	
	/**
	 * New method
	 * @param clz
	 * @return
	 */
	public int add(Clazz clz) {
		String sql="insert into t_struts_class values(?,?,?,?)";
		return super.executeUpdate(sql, new String[] {"cid","cname","cteacher","pic"}, clz);
		
	}
	
	/**
	 * modify
	 * @param clz
	 * @return
	 */
	public int edit(Clazz clz) {
		String sql="update t_struts_class set cname=?,cteacher=?,pic=? where cid=?";
		return super.executeUpdate(sql, new String[] {"cname","cteacher","pic","cid"}, clz);
		
	}
	
	/**
	 * delete
	 * @param clz
	 * @return
	 */
	public int del(Clazz clz) {
		String sql="delete from t_struts_class where cid=?";
		return super.executeUpdate(sql, new String[] {"cid"}, clz);
		
	}
	
	
	
	
	
}

web layer:

package com.psy.crud.web;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.psy.crud.dao.ClzDao;
import com.psy.crud.entity.Clazz;
import com.psy.crud.util.PageBean;

public class ClazzAction extends BaseAction implements ModelDriven<Clazz> {

	private ClzDao clzDao = new ClzDao();
	private Clazz clz = new Clazz();

	public String list() {
		PageBean pageBean = new PageBean();
		pageBean.setRequest(request);
		List<Clazz> list = this.clzDao.list(clz, pageBean);
		// this.result=this.clzDao.list(clz, pageBean);
		request.setAttribute("clzList", list);
		request.setAttribute("pageBean", pageBean);

		return "list";

	}

	/**
	 * The common method of jump to add and modify page
	 * 
	 * @return
	 */
	public String preSave() {

		if(clz.getCid() !=0) {
			Clazz c = this.clzDao.list(clz, null).get(0);
			request.setAttribute("clz", c);
		}
		return "preSave";

	}

	/**|
	 * Newly added
	 * @return
	 */
	public String add() {

		result= this.clzDao.add(clz);
		return "toList";

	}

	/**
	 * modify
	 * @return
	 */
	public String edit() {

		this.clzDao.edit(clz);
		return "toList";

	}

	/**
	 * delete
	 * @return
	 */
	public String del() {

		this.clzDao.del(clz);
		return "toList";

	}

	@Override
	public Clazz getModel() {
		// TODO Auto-generated method stub
		return clz;
	}

}

  struts_sy.xml:

<action name="/clz_*" class="com.psy.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>

  

jsp page

Clzlist.jsp (information display page):

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@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>

	<form action="${pageContext.request.contextPath }/sy/clz_list.action"
		method="post">
		Class name:<input type="text" name="cname"> Teacher:<input type="text"
			name="bname"> <input type="submit">

	</form>
	<a href="${pageContext.request.contextPath }/sy/clz_preSave.action">Newly added</a>
	<table border="1" width="100%">

		<tr>
			<td>number</td>
			<td>Class name</td>
			<td>Teacher</td>
			<td>picture</td>
			<td>operation</td>
		</tr>
		<c:forEach items="${clzList }" 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/clz_preSave.action?cid=${c.cid }">modify</a>  
				    <a href="${pageContext.request.contextPath }/sy/clz_del.action?cid=${c.cid }">delete</a>  
				    <a href="${pageContext.request.contextPath }/sy/clz_preUpload.action?cid=${c.cid }">Upload pictures</a>  
				</td>
			</tr>
		</c:forEach>
	</table>

    <z:page pageBean="${pageBean }"></z:page>

</body>
</html>

clzEdit.jsp (add and modify page):

<%@ 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 }${clz.cname == null ? '/sy/clz_add.action' : '/sy/clz_edit.action'}" method="post">
		number:<input type="text" name="cid" value="${clz.cid }"> <br>
		Class name:<input type="text" name="cname" value="${clz.cname }"> <br>
		Teacher:<input type="text" name="cteacher" value="${clz.cteacher }"> <br>
		<input type="submit">
	</form>
</body>
</html>

Topics: PHP JSP Java SQL xml