目录:
entity
clazz
Dao
calzzDao
tag
pageTag
web
clazzAction
util
BaseAction
BaseDao
PageBean
配置文件
web.xml
z.tld
struts.xml
pom.xml
jsp页面
clzList.jsp
clzEdit.jsp
entity
package com.liuxia.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;
}
}
ClazzDao
package com.liuxia.crud.dao;
import java.sql.SQLException;
import java.util.List;
import com.liuxia.crud.entity.Clazz;
import com.liuxia.crud.util.BaseDao;
import com.liuxia.crud.util.PageBean;
import com.liuxia.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 {
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 {
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 {
String sql= "update t_struts_class set cname=?,cteacher=?,pic=? where cid=?";
return super.executeUpdate(sql,new String[] {"cname","cteacher","pic","cid"}, clazz);
}
}
pageTag
package com.liuxia.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;
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.getParamMap();
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;
}
}
ClazzAction
package com.liuxia.crud.web;
import java.sql.SQLException;
import java.util.List;
import com.liuxia.crud.dao.ClazzDao;
import com.liuxia.crud.entity.Clazz;
import com.liuxia.crud.util.BaseAction;
import com.liuxia.crud.util.PageBean;
import com.opensymphony.xwork2.ModelDriven;
public class ClazzAction extends BaseAction implements ModelDriven<Clazz>{
private Clazz clz=new Clazz();
private ClazzDao clazzDao=new ClazzDao();
/**
* 查所有
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String list() throws InstantiationException, IllegalAccessException, SQLException {
PageBean pageBean=new PageBean();
pageBean.setRequest(request);
List<Clazz> list = this.clazzDao.list(clz, pageBean);
request.setAttribute("clzList",list);
request.setAttribute("pageBean",pageBean);
return "list";
}
/**
* 跳转新增修改页面的公用方法
*
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String preSave() {
if(clz.getCid()!=0) {
try {
this.result = this.clazzDao.list(clz,null).get(0);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
return "preSave";
}
/**
* 新增方法
* @return
*/
public String add() {
try {
this.code = this.clazzDao.add(clz);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
public String edit() {
try {
this.clazzDao.edit(clz);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
public String del() {
try {
this.clazzDao.del(clz);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
@Override
public Clazz getModel() {
return clz;
}
}
BaseAction
package com.liuxia.crud.util;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
/**
* 每一个开发的子控制器要用的属性都定义在通用的action中。
* @author Administrator
*
*/
public class BaseAction implements ServletRequestAware, ServletResponseAware{
/**
* 为了传值使用
*/
protected HttpServletResponse response;
protected HttpServletRequest request;
protected HttpSession session;
protected ServletContext application;
/**
* 为了配置跳转页面所用
*/
protected final static String SUCCESS = "success";
protected final static String FAIL = "fail";
protected final static String LIST = "list";
protected final static String ADD = "add";
protected final static String EDIT = "edit";
protected final static String DETAIL = "detail";
/**
* 具体传值字段 后端向jsp页面传值所用字段
*/
protected Object result;
protected Object msg;
protected int code;
public Object getResult() {
return result;
}
public Object getMsg() {
return msg;
}
public int getCode() {
return code;
}
@Override
public void setServletResponse(HttpServletResponse arg0) {
this.response = arg0;
}
@Override
public void setServletRequest(HttpServletRequest arg0) {
this.request = arg0;
this.session = arg0.getSession();
this.application = arg0.getServletContext();
}
}
BaseDao
package com.liuxia.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.liuxia.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
*/
public int executeUpdate(String sql, String[] attrs, T t) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
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();
}
}
PageBean
package com.liuxia.crud.util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 3;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
private String url;
private Map<String, String[]> paramMap = new HashMap<>();
// 定义初始化方法,存入上一次请求的值
public void setRequest(HttpServletRequest req) {
this.setPage(req.getParameter("page"));
this.setRows(req.getParameter("rows"));
this.setPagination(req.getParameter("pagination"));
// getRequestURL获取到浏览器请求的全路径
this.setUrl(req.getRequestURL().toString());
// getParameterMap可以获取到一次url请求所携带的所有参数
this.setParamMap(req.getParameterMap());
}
public void setPagination(String pagination) {
if (StringUtils.isNotBlank(pagination)) {
this.setPagination(!"false".equals(pagination));
}
}
public void setRows(String rows) {
if (StringUtils.isNotBlank(rows))
this.setRows(Integer.valueOf(rows));
}
public void setPage(String page) {
if (StringUtils.isNotBlank(page)) {
this.setPage(Integer.valueOf(page));
}
}
public PageBean() {
super();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParamMap() {
return paramMap;
}
public void setParamMap(Map<String, String[]> paramMap) {
this.paramMap = paramMap;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
/**
* 获取到总页数
* @return
*/
public int getMaxPage() {
return this.total % this.rows == 0 ?
this.total / this.rows :
(this.total / this.rows) + 1;
}
/**
* 获取下一页页码
* @return
*/
public int getNextPage() {
return this.page < this.getMaxPage() ? this.page+1 : this.page;
}
/**
* 获取上一页页码
* @return
*/
public int getPreviousPage() {
return this.page > 1 ? this.page-1 : this.page;
}
}
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.liuxia.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>
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>dj 1.1 core library</description>
<display-name>dj core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>d</short-name>
<uri>/liuxia</uri>
<tag>
<name>page</name>
<tag-class>com.liuxia.crud.tag.PageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>pageBean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
struts.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.liuxia.web.HelloAction" method="{1}">
<result name="success">/success.jsp</result>
</action>
<action name="/demo_*" class="com.liuxia.ognl.Demo7" method="{1}">
<result name="success">/success.jsp</result>
</action>
<action name="/clz_*" class="com.liuxia.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>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.liuxia.web</groupId>
<artifactId>StrutsDemp</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>StrutsDemp Maven Webapp</name>
<url>http://maven.apache.org</url>
<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>StrutsDemp</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>
jsp页面
clzList.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="/liuxia" 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>班级编辑界面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}${result.cname == null ? '/sy/clz_add.action' : '/sy/clz_edit.action' }" method="post">
ID:<input type="text" name="cid" value="${result.cid }"><br>
名称:<input type="text" name="cname" value="${result.cname }"><br>
教员:<input type="text" name="cteacher" value="${result.cteacher }"><br>
<input type="submit" value="ok">
</form>
</body>
</html>
: