struts实现crud
利用struts完成增删改查
思路分析
1、导入相关的pom依赖(struts、自定义标签库的依赖)
2、分页的tag类导入、z.tld、完成web.xml的配置
3、dao层去访问数据
4、web层去调用dao层给前台返回数据
5、在struts_sy.xml进行配置
6、写jsp
数据库
重要代码
web.xml 配置
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>pre_struts</display-name>
<!-- 防止中文乱码过滤器 -->
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.dj.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>
Dao 层
BookDao
package com.dj.crud.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.dj.crud.util.JsonBaseDao;
import com.dj.crud.util.JsonUtils;
import com.dj.crud.util.PageBean;
import com.dj.crud.util.StringUtils;
public class BookDao extends JsonBaseDao{
/**
* 查询图书 通用方法
* @param paMap
* @param pageBean
* @return
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
public List<Map<String, Object>> list(Map<String, String[]> paMap, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select a.*,b.tname from book_book a,book_type b where a.tid=b.tid ";
String str = JsonUtils.getParamVal(paMap, "str");
String bid = JsonUtils.getParamVal(paMap, "bid");
if(StringUtils.isNotBlank(bid)) {//查询单个书籍
sql += " and a.bid = "+bid+" ";
}
if(StringUtils.isNotBlank(str)) {
sql += " and a.bname like '%"+str+"%' or a.bauthor like '%"+str+"%' or a.bdesc like '%"+str+"%' ";
}
return super.executeQuery(sql, pageBean);
}
/**
* 增加图书
* @param paMap
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
*/
public int add(Map<String, String[]> paMap) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException {
String sql = "insert into book_book(bname,tid,bauthor,bprice,bpublish,bimg) values(?,?,?,?,?,?)";
return super.executeUpdate(sql, new String[] {"bname","tid","bauthor","bprice","bpublish","bimg"}, paMap);
}
/**
* 修改图书
* @param paMap
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
*/
public int edit(Map<String, String[]> paMap) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException {
String sql = "update book_book set bname=?,tid=?,bauthor=?,bprice=?,bpublish=?,bimg=? where bid=?";
return super.executeUpdate(sql, new String[] {"bname","tid","bauthor","bprice","bpublish","bimg","bid"}, paMap);
}
/**
* 删除图书
* @param paMap
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
*/
public int del(Map<String, String[]> paMap) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException {
String sql = "delete from book_book where bid=?";
return super.executeUpdate(sql, new String[] {"bid"}, paMap);
}
}
web 层
BookAction
package com.dj.crud.web;
import java.util.List;
import java.util.Map;
import com.dj.crud.dao.BookDao;
import com.dj.crud.util.PageBean;
import com.dj.crud.util.StringUtils;
public class BookAction extends BaseAction {
private BookDao bookDao = new BookDao();
/**
* 查询所有图书 模糊查 分页
*
* @param req
* @param resp
* @return
*/
public String list() {
try {
PageBean pageBean = new PageBean();// 需要分页
pageBean.setRequest(request);// 初始化
pageBean.setRows(6);// 设置每页几条数据
List<Map<String, Object>> list = this.bookDao.list(request.getParameterMap(), pageBean);
// 传值
request.setAttribute("bookList", list);// 集合
request.setAttribute("pageBean", pageBean);// 分页
} catch (Exception e) {
e.printStackTrace();
}
return "list";
}
/**
* 跳转增加、修改页面的通用方法
*
* @return
*/
public String preSave() {
String bid = request.getParameter("bid");
try {
if(StringUtils.isNotBlank(bid)) {
Map<String, Object> map = this.bookDao.list(request.getParameterMap(), null).get(0);
request.setAttribute("book", map);
}
} catch (Exception e) {
e.printStackTrace();
}
return "preSave";
}
/**
* 增加图书
* @return
*/
public String add() {
try {
result = this.bookDao.add(request.getParameterMap());
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
/**
* 修改图书
* @return
*/
public String edit() {
try {
result = this.bookDao.edit(request.getParameterMap());
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
/**
* 删除图书
* @return
*/
public String del() {
try {
result = this.bookDao.del(request.getParameterMap());
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
}
BaseAction
定义BaseAction,存放结果码常量,请求、响应、上下文、公用的传值 。
代码如下:
package com.dj.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();
}
}
struts_sy.xml 配置
struts_sy.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>
<!-- action 分类 -->
<package name="sy" extends="base" namespace="/sy">
<action name="/demo_*" class="com.dj.web.HelloAction" method="{1}">
<result name="rs">/rs.jsp</result>
</action>
<action name="/stack_*" class="com.dj.test.DemoAction" method="{1}">
<result name="rs">/rs.jsp</result>
</action>
<action name="/book_*" class="com.dj.crud.web.BookAction" method="{1}">
<result name="list">/list.jsp</result>
<result name="preSave">/edit.jsp</result>
<result name="toList" type="redirectAction">/book_list</result>
</action>
</package>
</struts>
jsp 界面
list.jsp (数据展示界面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ taglib uri="/dj" prefix="d"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<div align="center">
<!-- 模糊查询 -->
<form action="${pageContext.request.contextPath }/sy/book_list.action" method="post">
<input type="text" name="str" >
<input type="submit" value="查 询">
</form><br><br>
<a href="${pageContext.request.contextPath }/sy/book_preSave.action"> 新 增 书 籍 </a><br><br>
<%-- <!-- 获取数据 -->
<c:if test="${empty bookList }">
<jsp:forward page="${pageContext.request.contextPath }/sy/book_list.action"></jsp:forward>
</c:if> --%>
<!-- 书籍信息展示 -->
<table border="1" width="100%">
<tr align="center">
<td>书 本 名 称</td>
<td>书 籍 展 示</td>
<td>书 籍 类 别</td>
<td>所 出 作 者</td>
<td>书 籍 价 格</td>
<td>出 版 社</td>
<td>上 市 销 量</td>
<td>操 作</td>
</tr>
<c:forEach items="${bookList }" var="b">
<tr align="center">
<td>${b.bname }</td>
<td>${b.bimg }</td>
<td>${b.tname }</td>
<td>${b.bauthor }</td>
<td>${b.bprice }</td>
<td>${b.bpublish }</td>
<td>${b.bvolume }</td>
<td>
<a href="${pageContext.request.contextPath }/sy/book_preSave.action?bid=${b.bid}">修 改</a>
<a href="${pageContext.request.contextPath }/sy/book_del.action?bid=${b.bid}">删 除</a>
<a href="${pageContext.request.contextPath }/sy/book_preUpload.action?bid=${b.bid}">上 传 图 片</a>
</td>
</tr>
</c:forEach>
<%-- <s:iterator var="b" value="result">
<tr align="center">
<td><s:property value="#b.bname"/></td>
<td><s:property value="#b.bimg"/></td>
<td><s:property value="#b.tname"/></td>
<td><s:property value="#b.bauthor"/></td>
<td><s:property value="#b.bprice"/></td>
<td><s:property value="#b.bpublish"/></td>
<td><s:property value="#b.bdesc"/></td>
<td><s:property value="#b.bvolume"/></td>
<td>
</td>
</tr>
</s:iterator> --%>
</table>
<!-- 分页 -->
<d:page pageBean="${pageBean }"></d:page>
</div>
</body>
</html>
edit.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>新增 or 修改 页面</title>
</head>
<body>
<br><br>
<!-- 新增页面与修改页面 公用 -->
<div align="center">
<form action="${pageContext.request.contextPath }${book.bname } == null ? '/sy/book_add.action' : '/sy/book_edit.action'" method="post">
书 本 名 称:<input type="text" name="bname" value="${book.bname }"><br><br>
书 籍 类 别:<select name="tid">
<option value="1">请 选 择 书 籍 类 型 :</option>
<option value="1">出 版 小 说</option>
<option value="2">人 文 社 科</option>
<option value="3">文 学 艺 术</option>
<option value="4">生 活 时 尚</option>
<option value="5">辅 助 教 材</option>
<option value="6">漫 画 杂 志</option>
<option value="7">外 文 小 说</option>
<option value="8">亲 子 书 籍</option>
<option value="9">健 康 养 生</option>
<option value="10">心 理 与 励 志</option>
<option value="11">商 业 与 经 济</option>
<option value="12">互 联 网 科 技</option>
</select><br><br>
作 者:<input type="text" name="bauthor" value="${book.bauthor }"><br><br>
价 格:<input type="text" name="bprice" value="${book.bprice }"><br><br>
出 版 社:<input type="text" name="bpublish" value="${book.bpublish }"><br><br>
<input type="submit" value="提 交">
<input type="reset" value="重 置"><br>
</form>
</div>
</body>
</html>
效果展示
主界面效果
数据展示:
分页查询:
修改效果
单个数据展示:
数据进行修改:
修改后:
增加效果
增加数据:
加入后:
删除效果
删除刚刚新增的数据,删除后:
Struts标签
s:iterator
S:action
S:url
S:form
s:textfield
S:select
S:radio
S:param
s:textarea