Strutsz之crud
利用struts完成增删改查
思路:
1、导入相关的pom依赖(struts、自定义标签库的依赖)
<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.maven</groupId>
<artifactId>Struts</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Struts 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>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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
</dependencies>
<build>
<finalName>Struts</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类导入、z.tld、完成web.xml的配置
我们需要导入的包
实体类的BaseDao
package com.xyx.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;
public class BaseDao<T> {
/**
*
* @param sql 查询语句
* @param clz
* @param pageBean 分页
* @return
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SQLException
*/
public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
List<T> list =new ArrayList<>();
Connection con=DBAccess.getConnection();
PreparedStatement pst=null;
ResultSet rs=null;
try {
if (pageBean != null && pageBean.isPagination()) {
String countSql=getCountSql(sql);
pst=con.prepareStatement(countSql);
rs=pst.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getLong(1)+"");
}
String pageSql= getPageSql(sql,pageBean);
pst=con.prepareStatement(pageSql);
rs=pst.executeQuery();
} else {
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
}
while (rs.next()) {
// list.add(new Book(rs.getInt("bid"),
// rs.getString("bname"),
// rs.getFloat("price")));
/**
T t = (T) clz.newInstance();
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
field.set(t, rs.getObject(field.getName()));
}
list.add(t);
}
} finally {
DBAccess.close(con, pst, rs);
}
return list;
}
/**
* 通用的增删改方法
* @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();
}
private String getPageSql(String sql, PageBean pageBean) {
// TODO Auto-generated method stub
return sql + " limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
private String getCountSql(String sql) {
// TODO Auto-generated method stub
return "select count(1) from ("+sql+") t ";
}
}
EncodingFiter
package com.xyx.crud.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中文乱码处理
*
*/
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// 默认字符集
public EncodingFiter() {
super();
}
public void destroy() {
}
@SuppressWarnings("rawtypes")
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 中文处理必须放到 chain.doFilter(request, response)方法前面
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
Set set = map.keySet();// 取出所有参数名
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
PageBean
package com.xyx.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 = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
private String url;//存储上一次请求
private Map<String, String[]> paramMap = new HashMap<>();//键值对应
//设置初始值 需要存放jsp的参数键值对
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)) {
//默认分页 填false不分页
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;
}
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;
}
/**
* 获取到上一页的代码
*/
public int getPreviousPage() {
return this.page > 1 ? this.page-1 : this.page;
}
}
StringUtils
package com.xyx.crud.util;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
3、dao层去访问数据
package com.xyx.crud.dao;
import java.sql.SQLException;
import java.util.List;
import com.xyx.crud.entity.Clazz;
import com.xyx.crud.util.BaseDao;
import com.xyx.crud.util.PageBean;
import com.xyx.crud.util.StringUtils;
public class ClazzDao extends BaseDao<Clazz> {
/**
* 查询
* @param clz
* @param pageBean
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<Clazz> list(Clazz clz,PageBean pageBean) throws Exception{
String sql="select * from t_struts_clazz where true";
String cname=clz.getCname();//模糊查
int cid=clz.getCid();//点击修改的时候查单个
if(cid!=0) {//在前台传了ID过来了
sql+=" and cid = "+cid;
}
if(StringUtils.isNotBlank(cname)) {
sql+=" and cname like '%"+cname+"%'";
}
return super.executeQuery(sql, Clazz.class, pageBean);
}
/**
* 新增
* @param clz
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws NoSuchFieldException
*/
public int add(Clazz clz) throws Exception {
String sql="insert into t_struts_clazz(cid,cname,cteacher,pic) values (?,?,?,?)";
return super.executeUpdate(sql, new String[] {"cid","cname","cteacher","pic"}, clz);
}
public int edit(Clazz clz) throws Exception {
String sql="update t_struts_clazz set cname=?,cteacher=?,pic=? where cid=?";
return super.executeUpdate(sql, new String[] {"cname","cteacher","pic","cid"}, clz);
}
public int del(Clazz clz) throws Exception {
String sql="delete from t_struts_clazz where cid=?";
return super.executeUpdate(sql, new String[] {"cid"}, clz);
}
}
z.tld
<tag>
<name>page</name>
<tag-class>com.xyx.crud.tag.PageTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>pageBean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
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.xyx.crud.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts</filter-name>
<!-- 相当于MVC中央控制器 -->
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
</web-app>
4、web层去调用dao层给前台返回数据
写一个通用的类 BaseAction
package com.xyx.crud.web;
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();
}
}
继承BaseAction ClazzAction
package com.xyx.crud.web;
import java.util.List;
import com.opensymphony.xwork2.ModelDriven;
import com.xyx.crud.dao.ClazzDao;
import com.xyx.crud.entity.Clazz;
import com.xyx.crud.util.PageBean;
public class ClazzAction extends BaseAction implements ModelDriven<Clazz>{
private ClazzDao clzDao=new ClazzDao();
private Clazz clz=new Clazz();//接受前台传过来的参数
public String list() {
PageBean pageBean =new PageBean();
pageBean.setRequest(request);//pageBean 初始化
try {
List<Clazz> list = this.clzDao.list(clz, pageBean);
//this.result=this.clzDao.list(clz, pageBean);
request.setAttribute("clzList", list);//查询
request.setAttribute("pageBean", pageBean);//分页
} catch (Exception e) {
e.printStackTrace();
}
return "list";
}
/**
* 跳转新增页面的公用修改方法
* @return
*/
public String preSave() {
if(clz.getCid()!=0) {
Clazz c;
try {
c = this.clzDao.list(clz, null).get(0);//查询数据
request.setAttribute("clz", c);//把数据传到页面上去
} catch (Exception e) {
e.printStackTrace();
}
}
return "preSave";
}
/**
* 新增
* @return
*/
public String add() {
try {
result=this.clzDao.add(clz);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 修改
* @return
*/
public String edit() {
try {
this.clzDao.edit(clz);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 删除
* @return
*/
public String del() {
try {
this.clzDao.del(clz);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
@Override
public Clazz getModel() {
return clz;
}
}
5、在struts_sy.xml进行配置
struts_sy.xml
<action name="/clz_*" class="com.xyx.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>
6、写jsp
clzList
<body>
<h2>小说目录</h2>
<br>
<form action="${pageContext.request.contextPath}/sy/clz_list.action"
method="post">
<!-- <input type="hidden" name="rows" value="20"> -->
<!-- <input type="hidden" name=pagination value="false"> -->
班级名:<input type="text" name="cname"> <input type="submit"
value="确定">
</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="c">
<tr>
<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}">修改</a>
<a href="${pageContext.request.contextPath}/sy/clz_del.action?cid=${c.cid}">删除</a>
<a href="${pageContext.request.contextPath}/sy/clz_preUpload.action?cid=${c.cid}">上传图片</a>
</td>
</tr>
</c:forEach>
</table>
<z:page pageBean="${pageBean }"></z:page>
</body>
clzEdit
<body>
<form action="${pageContext.request.contextPath}${clz.cname ==null? '/sy/clz_add.action':'/sy/clz_edit.action'}" method="post">
cid:<input type="text" name="cid" value="${clz.cid }"></br>
cname:<input type="text" name="cname" value="${clz.cname }"></br>
cteacher:<input type="text" name="cteacher" value="${clz.cteacher }"></br>
pic:<input type="text" name="pic" value="${clz.pic }"></br>
<input type="submit">
</form>
</body>
接下来就是我们的页面展示啦!!!
先增加
接下来我们在写一下 修改 修改花花 改为花花1
我们在来删除这个花花
模糊查询