struts之增删改查
- Dao包
- ClazzDao
- entity包
- Clazz
- tag包
- PageTag
- util包
- BaseDao
- EncodingFiter
- PageBean
- StringUtils
- web包
- BaseAction
- ClazzAction
util包
1、BaseDao
package com.yj.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;
/**
* T = Book.class
* @author 雷神
*
* @param <T>
*/
public class BaseDao<T> {
/**
*
* @param sql:决定查询哪张表的数据
* @param clz:查询出来的数据封装到哪个实体类中
* @param pagebean:决定是否分页
* @return
* @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> list = new ArrayList<>();
Connection con = DBAccess.getConnection();
PreparedStatement pst = null;
ResultSet rs = null;
try {
if (pageBean != null && pageBean.isPagination()) {
//该分页了
String countSql = getcountSql(sql);//拼接sql语句用来查询一页的所有行
pst = con.prepareStatement(countSql);
rs = pst.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getLong(1)+"");
}
//拼接sql语句 用来查询第几页的结果集
String pageSql = getPageSql(sql,pageBean);
pst = con.prepareStatement(pageSql);
rs = pst.executeQuery();
} else {//不分页
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
}
while (rs.next()) {
//利用反射拿到值
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 {
//shift+alt+z
//关闭连接,执行对象以及结果集
DBAccess.close(con, pst, rs);
}
return list;
}
/**
* 用原生sql拼接出符合条件的某一页的数据查询sql
* @param sql
* @param pageBean
* @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 t : 实体类的实例
* @param sql :增删改的sql语句
* @param attrs ?所代表的实体类的属性
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int executeUpdate(T t,String sql,String[] attrs) 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();
}
}
2、EncodingFiter
package com.yj.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();
}
}
}
3、PageBean
package com.yj.crud.util;
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[]> parameterMap;// 上一次请求的所有参数
public PageBean() {
super();
}
/**
* 对分页bean进行初始化
*
* @param request
*/
public void setRequest(HttpServletRequest request) {
// 公共参数
this.setPage(request.getParameter("page"));
this.setRows(request.getParameter("rows"));
this.setPagination(request.getParameter("pagination"));
// 请求地址和请求参数
this.setUrl(request.getContextPath() + request.getServletPath());
this.setParameterMap(request.getParameterMap());
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
this.parameterMap = parameterMap;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void setPage(String page) {
if (null != page && !"".equals(page.trim())) {
this.page = Integer.parseInt(page);
}
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public void setRows(String rows) {
if (null != rows && !"".equals(rows.trim())) {
this.rows = Integer.parseInt(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 void setPagination(String pagination) {
if ("false".equals(pagination)) {
this.pagination = false;
}
}
/**
* 下一页
*
* @return
*/
public int getNextPage() {
int nextPage = page + 1;
if (nextPage > this.getMaxPage()) {
nextPage = this.getMaxPage();
}
return nextPage;
}
/**
* 上一页
*
* @return
*/
public int getPreviousPage() {
int previousPage = page - 1;
if (previousPage < 1) {
previousPage = 1;
}
return previousPage;
}
/**
* 最大页码
*
* @return
*/
public int getMaxPage() {
return total % rows == 0 ? total / rows : total / rows + 1;
}
/**
* 起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (page - 1) * rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
4、StringUtils
package com.yj.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);
}
}
tag包
PageTag
package com.yj.crud.tag;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.yj.crud.util.PageBean;
public class PageTag extends BodyTagSupport {
private static final long serialVersionUID = 8003507841172246203L;
private PageBean pageBean;
public PageTag() {
super();
}
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public int doStartTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
out.println(this.toHtml());
return SKIP_BODY;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private String toHtml() {
StringBuffer bf = new StringBuffer();
if (null == pageBean || !pageBean.isPagination()) {
return bf.toString();
}
// 1. 生成表单
bf.append("<form id='pageBeanForm' action='" + pageBean.getUrl() + "' method='post'>");
bf.append("<input type='hidden' name='page' value=''>");
for (Map.Entry<String, String[]> entry : pageBean.getParameterMap().entrySet()) {
String name = entry.getKey();
String[] values = entry.getValue();
if ("page".equals(name)) {
continue;
}
for (String value : values) {
bf.append("<input type='hidden' name='" + name + "' value='" + value + "'>");
}
}
bf.append("</form>");
// 2. 生成按钮
bf.append("<div style='text-align: right;font-size: 12px;'>每页" + pageBean.getRows() + "条,共"
+ pageBean.getTotal() + "条,当前第" + pageBean.getPage() + "页,共" + pageBean.getMaxPage()
+ "页 <a href='javascript:doGotoPage(1)'>首 页</a> <a href='javascript:doGotoPage("
+ pageBean.getPreviousPage() + ")'>上一页</a> <a href='javascript:doGotoPage("
+ pageBean.getNextPage() + ")'>下一页</a> <a href='javascript:doGotoPage("
+ pageBean.getMaxPage()
+ ")'>尾 页</a> <input id='pageNumber' type='text' style='text-align: center;width: 30px;'> <a href='javascript:doSkipPage();'>GO</a></div>");
// 3. 动态生成js
bf.append("<script type='text/javascript'>");
bf.append("function doGotoPage(page){");
bf.append(" var form = document.getElementById('pageBeanForm');");
bf.append(" form.page.value = page;");
bf.append(" form.submit();");
bf.append("}");
bf.append("function doSkipPage(page){");
bf.append(" var page = document.getElementById('pageNumber').value;");
bf.append(" if(!page||isNaN(page)||parseInt(page)<1||parseInt(page)>"+pageBean.getMaxPage()+"){");
bf.append(" alert('页码必须为1~"+pageBean.getMaxPage()+"之间数字');");
bf.append(" document.getElementById('pageNumber').value = '';");
bf.append(" return;");
bf.append(" }");
bf.append(" doGotoPage(parseInt(page));");
bf.append("}");
bf.append("</script>");
bf.append("");
bf.append("");
bf.append("");
bf.append("");
bf.append("");
return bf.toString();
}
}
entity包
package com.yj.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;
}
@Override
public String toString() {
return "Clazz [cid=" + cid + ", cname=" + cname + ", cteacher=" + cteacher + ", pic=" + pic + "]";
}
}
dao包
package com.yj.crud.dao;
import java.sql.SQLException;
import java.util.List;
import com.yj.crud.entity.Clazz;
import com.yj.crud.util.BaseDao;
import com.yj.crud.util.PageBean;
import com.yj.crud.util.StringUtils;
public class ClazzDao 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";
int cid = clz.getCid();
String cname = clz.getCname();
if(cid != 0 ) {
sql += " and cid = " +cid;
}
if(StringUtils.isNotBlank(cname)) {
sql += " and cname like '%"+cname+"%'";
}
return super.executeQuery(sql, Clazz.class, pageBean);
}
/**
* 新增
* @param clz
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws SQLException
*/
public int add(Clazz clz) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException {
String sql = "insert into t_struts_class values(?,?,?,?)";
return super.executeUpdate( clz,sql, new String[] {"cid","cname","cteacher","pic"});
}
/**
* 修改
* @param clz
* @return
* @throws IllegalArgumentException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws SQLException
*/
public int edit(Clazz clz) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql = "update t_struts_class set cname=?,cteacher=?,pic=? where cid=?";
return super.executeUpdate(clz,sql , new String[] {"cname","cteacher","pic","cid"});
}
/**
* 删除
* @param clz
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws SQLException
*/
public int del(Clazz clz) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException {
String sql = "delete from t_struts_class where cid = ?";
return super.executeUpdate(clz,sql, new String[] {"cid"});
}
}
web包
1、BaseAction
package com.yj.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();
}
}
2、ClazzAction
package com.yj.crud.web;
import java.sql.SQLException;
import java.util.List;
import com.opensymphony.xwork2.ModelDriven;
import com.yj.crud.dao.ClazzDao;
import com.yj.crud.entity.Clazz;
import com.yj.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);
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 (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
return "list";
}
/**
* 跳转新增修改页面的通用方法
* @return
*/
public String preSave() {
if(clz.getCid()!=0) {
try {
Clazz clazz = this.clzDao.list(clz, null).get(0);
request.setAttribute("clz", clazz);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
return "preSave";
}
/**
* 新增
* @return
*/
public String add() {
try {
result = this.clzDao.add(clz);
} catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
| SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 修改
* @return
*/
public String edit() {
try {
this.clzDao.edit(clz);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
/**
* 删除
* @return
*/
public String del() {
try {
this.clzDao.del(clz);
} catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
@Override
public Clazz getModel() {
return clz;
}
}