Struts2增删改查
思路:
导入相关的pom依赖(struts、自定义标签库的依赖)
分页的tag类导入、z.tld、完成web.xml的配置
dao层去访问数据
web层去调用dao层给前台返回数据
在struts_sy.xml进行配置
写jsp
导入相关的pom依赖
<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>
提供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">
<tlib-version>1.1</tlib-version>
<short-name>s</short-name>
<uri>/p</uri>
<tag>
<name>page</name>
<tag-class>com.pyc.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.pyc.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts</filter-name>
<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>
uitl在之前的mvc中
baseaction:
主要是存放结果码常量,请求、响应、上下文、公用的传值
package com.pyc.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();
}
}
entity实体类:
Clazz.java
package com.pyc.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;
}
@Override
public String toString() {
return "Clazz [cid=" + cid + ", cname=" + cname + ", cteacher=" + cteacher + ", pic=" + pic + "]";
}
public Clazz(int cid, String cname, String cteacher, String pic) {
super();
this.cid = cid;
this.cname = cname;
this.cteacher = cteacher;
this.pic = pic;
}
public Clazz() {
super();
}
}
tag分页
PageTag.java
package com.pyc.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.pyc.util.PageBean;
public class PageTag extends BodyTagSupport {
/**
*
*/
private static final long serialVersionUID = -5562962387565807161L;
/**
*
*/
private PageBean pageBean;
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.print(toHTML());
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
private String toHTML() {
StringBuilder sb = new StringBuilder();
// 拼接下一次分页请求搜提交的分页表单
sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
sb.append("<input type='hidden' name='page'> ");
Map<String, String[]> paMap = pageBean.getPaMap();
if(paMap != null && paMap.size()>0) {
Set<Entry<String, String[]>> entrySet = paMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
for(String value :entry.getValue() ) {
if(!"page".equals(entry.getKey())) {
sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+value+"'>");
}
}
}
}
sb.append("</form>");
// 拼接分页条
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)'>首页</a> ");
sb.append(" <a href='javascript:gotoPage("+pageBean.getPreviousPage()+")'>上一页</a> ");
sb.append(" <a href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页</a> ");
sb.append(" <a href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a> ");
sb.append(" <input type='text' id='skipPage' style='text-align: center; font-size: 12px; width: 50px;'> ");
sb.append(" <a href='javascript:skipPage()'>Go</a>");
sb.append(" </div>");
// 拼接分页的javascript 代码
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;
}
}
dao方法
ClzDao
package com.pyc.dao;
import java.sql.SQLException;
import java.util.List;
import com.pyc.entity.Clazz;
import com.pyc.util.BaseDao;
import com.pyc.util.PageBean;
import com.pyc.util.StringUtils;
/**
* 操作數據庫
* @author 96345
*
*/
public class ClzDao extends BaseDao<Clazz>{
/**
* 班級列表查詢(帶分頁)
* @param clz
* @param pageBean
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
public List<Clazz> list(Clazz clz,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql="select * from t_struts_class where true ";
String cname=clz.getCname();
int cid=clz.getCid();
if(StringUtils.isNotBlank(cname)) {
sql+=" and cname like '%"+cname+"%'";
}
if(cid !=0) {
sql+=" and cid="+cid;
}
return super.executeQuery(sql, Clazz.class, pageBean);
}
/**
* 班級信息的增加
* @param clz
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int add(Clazz clz) throws IllegalArgumentException, IllegalAccessException, SQLException {
String sql="insert into t_struts_class values(?,?,?,?)";
return super.executeUpdate(sql, new String[]{"cid","cname","cteacher","pic"}, clz);
}
/**
* 編輯信息的刪除
* @param clz
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
public int del(Clazz clz) throws IllegalArgumentException, IllegalAccessException, SQLException {
String sql="delete from t_struts_class where cid=?";
return super.executeUpdate(sql, new String[]{"cid"}, clz);
}
/**
* 班級信息的修改
* @param clz
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
public int edit(Clazz clz) throws 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"}, clz);
}
}
web层
ClassAction:
package com.pyc.web;
import com.opensymphony.xwork2.ModelDriven;
import com.pyc.dao.ClzDao;
import com.pyc.entity.Clazz;
import com.pyc.util.BaseAction;
import com.pyc.util.PageBean;
public class ClazzAction extends BaseAction implements ModelDriven<Clazz>{
private ClzDao clazzDao = new ClzDao();
private Clazz clz = new Clazz();
/**
* 查询
* @return
*/
public String list() {
PageBean pageBean = new PageBean();
pageBean.setRequest(request);//request 是从继承的BaseAction中获得
try {
this.result = clazzDao.list(clz, pageBean);
request.setAttribute("pageBean", pageBean);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "list";
}
/**
* 跳转编辑页面(与新增同一页面)
* 跳编辑页面时需要传递cid到后台进行查询并且将查询到的数据进行回显
* @return
*/
public String preSave() {
int cid = clz.getCid();
if(cid != 0) {
try {
this.result = clazzDao.list(clz, null).get(0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "preSave";
}
/**
* 增加
* @return
*/
public String add() {
try {
this.code = this.clazzDao.add(clz);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 删除
* @return
*/
public String del() {
try {
this.code = this.clazzDao.del(clz);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 修改
* @return
*/
public String edit() {
try {
this.code = this.clazzDao.edit(clz);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
@Override
public Clazz getModel() {
// TODO Auto-generated method stub
return clz;
}
}
jsp页面
clzList.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="/p" prefix="s"%>
<!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="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>
<td>操作</td>
</tr>
<c:forEach items="${result }" 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}">修改</a>
<a href="${pageContext.request.contextPath}/sy/clz_del.action?cid=${c.cid }">删除</a>
</td>
</tr>
</c:forEach>
</table>
<sd:page pageBean="${pageBean}"></sd: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.get(0).cname == null ? '/sy/clz_add.action' : '/sy/clz_edit.action'}" method="post">
cid : <input type="text" value="${result.get(0).cid}" name="cid"><br>
cname : <input type="text" value="${result.get(0).cname}" name="cname"><br>
cteacher : <input type="text" value="${result.get(0).cteacher}" name="cteacher"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
测试
不能直接进入jsp页面
加入上面自己填写的路径:http://localhost:8080/pro_maven/sy/clz_list.action
注意type
chain:Action链式处理的结果类型,也就是将结果转发到这个action中。
redirect:实际上dispatcher和redirect的区别就是在于转发和重定向的区别。
redirectAction:用于直接redirectaction。
http://localhost:8080/pro_maven/sy/clz_list.action
增加
显示结果:
删除编号1
显示结果:
修改编号11
显示结果:
。。。成功了