今天分享的是struts2框架中增删改查的用法:
一:利用Struts2框架
1.1在pom.xml中导入相关依赖
4.0.0
com.ht
T224_struts
war
0.0.1-SNAPSHOT
T224_struts Maven Webapp
http://maven.apache.org
junit
junit
4.12
test
javax.servlet
javax.servlet-api
4.0.1
provided
org.apache.struts
struts2-core
2.5.13
javax.servlet.jsp
jsp-api
2.2.1-b03
provided
mysql
mysql-connector-java
5.1.44
jstl
jstl
1.2
taglibs
standard
1.1.2
org.apache.tomcat
tomcat-jsp-api
8.0.47
T224_struts
org.apache.maven.plugins
maven-compiler-plugin
3.7.0
1.8
1.8
UTF-8
二:导入分页相关的通用pageBean类,z.tld,并且配置web.xml
2.1 导入pageBean类
packagecom.crud.tag;importjava.io.IOException;importjava.util.Map;importjava.util.Map.Entry;importjava.util.Set;importjavax.servlet.jsp.JspException;importjavax.servlet.jsp.JspWriter;importjavax.servlet.jsp.tagext.BodyTagSupport;importcom.crud.util.PageBean;/*** 分页通用类
*@authorAdministrator*/
public class PageTag extendsBodyTagSupport {private static final long serialVersionUID = 1L;privatePageBean pageBean;publicPageBean getPageBean() {returnpageBean;
}public voidsetPageBean(PageBean pageBean) {this.pageBean =pageBean;
}
@Overridepublic int doStartTag() throwsJspException {
JspWriter out=pageContext.getOut();try{
out.print(toHTML());
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return super.doStartTag();
}privateString toHTML() {
StringBuffer sb= newStringBuffer();/** 拼接向后台提交数据的form表单
* 注意:拼接的form表单中的page参数是变化的,所以不需要保留上一次请求的值*/sb.append("
");sb.append("");
Map parameterMap =pageBean.getParameterMap();if(parameterMap != null && parameterMap.size() > 0) {
Set> entrySet =parameterMap.entrySet();for (Entryentry : entrySet) {if(!"page".equals(entry.getKey())) {
String[] values=entry.getValue();for(String val : values) {
sb.append("");
}
}
}
}
sb.append("
");/** 展示的分页条*/sb.append("sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页 首页
sb.append(" href='javascript:gotoPage("+pageBean.previousPage()+")'>上一页
sb.append(" href='javascript:gotoPage("+pageBean.nextPage()+")'>下一页
sb.append(" href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页
sb.append(" id='skipPage'");
sb.append(" style='text-align: center; font-size: 12px; width: 50px;'>
sb.append(" href='javascript:skipPage()'>Go
");sb.append("
}
}
2.2 z.tld文件
zking 1.1 core library
zking core
1.1
z
/zking
page
com.crud.tag.PageTag
JSP
pageBean
true
true
2.3 配置web.xml
Archetype Created Web Application
encodingFiter
com.crud.util.EncodingFiter
encodingFiter
/*
struts
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
struts
*.action
三:在Mysql中设计数据库
3.1 在项目中配置与mysql数据库连接
数据库用户名和密码是不一样的看你们自己怎么设置的
四:编写Dao层去访问数据库
packagecom.crud.dao;importjava.sql.SQLException;importjava.util.List;importcom.crud.entity.Class;importcom.crud.util.BaseDao;importcom.crud.util.EntityBaseDao;importcom.crud.util.PageBean;importcom.crud.util.StringUtils;/*** 班级dao方法类
*@authorAdministrator*/
public class ClassDao extends EntityBaseDao{/*** 查询分页方法,查询数据公用方法
*@paramc
*@parampaBean
*@return*@throwsInstantiationException
*@throwsIllegalAccessException
*@throwsSQLException*/
public List list(Class c,PageBean paBean) throwsInstantiationException, IllegalAccessException, SQLException{
String sql="select * from struts_class where true ";
String classname=c.getClassname();int cid=c.getCid();if (cid!=0) {
sql+=" and cid = "+cid;
}if(StringUtils.isNotBlank(classname)) {
sql+=" and classname like '%"+classname+"%'";
}return super.executeQuery(sql,paBean,Class.class);
}/*** 新增方法
*@paramc
*@return*@throwsNoSuchFieldException
*@throwsSecurityException
*@throwsIllegalArgumentException
*@throwsIllegalAccessException
*@throwsSQLException*/
public int add(Class c) throwsNoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="insert into struts_class values(?,?,?)";return super.executeUpdate(sql, new String[] {"classname","cname","upload"},c);
}/*** 删除方法
*@paramc
*@return*@throwsNoSuchFieldException
*@throwsSecurityException
*@throwsIllegalArgumentException
*@throwsIllegalAccessException
*@throwsSQLException*/
public int del(Class c) throwsNoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="delete from struts_class where cid=?";return super.executeUpdate(sql, new String[] {"cid"},c);
}/*** 修改方法
*@paramc
*@return*@throwsNoSuchFieldException
*@throwsSecurityException
*@throwsIllegalArgumentException
*@throwsIllegalAccessException
*@throwsSQLException*/
public int edit(Class c) throwsNoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="update struts_class set classname=?,cname=?,upload=? where cid=?";return super.executeUpdate(sql, new String[] {"cid","classname","cname","upload"},c);
}
}
五:编写web层去调用dao层的方法返回数据给前台
ClassAction 类
packagecom.crud.web;importjava.sql.SQLException;importjava.util.List;importcom.crud.dao.ClassDao;importcom.crud.entity.Class;importcom.crud.util.PageBean;importcom.opensymphony.xwork2.ActionSupport;importcom.opensymphony.xwork2.ModelDriven;/*** 班级web层
*@authorAdministrator*/
public class ClassAction extends BaseAction implements ModelDriven{private ClassDao cldao=newClassDao();private Class cls=newClass();publicString list() {
PageBean pageBean=newPageBean();
pageBean.setRequest(request);try{
List list = this.cldao.list(cls, pageBean);
request.setAttribute("mylist", list);
request.setAttribute("pageBean", pageBean);
}catch (InstantiationException | IllegalAccessException |SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return "list";
}/*** 跳转新增修改页面的公用方法
*@return*@throwsSQLException
*@throwsIllegalAccessException
*@throwsInstantiationException*/
public String preSave() throwsInstantiationException, IllegalAccessException, SQLException {if (cls.getCid()!=0) {
Class cl= this.cldao.list(cls, null).get(0);
request.setAttribute("cls",cl);
}return "preSave";
}/*** 新增
*@return
*/
publicString add() {try{
result= this.cldao.add(cls);
}catch(Exception e) {//TODO: handle exception
e.printStackTrace();
}return "toList";
}/*** 删除
*@return
*/
publicString del() {try{this.cldao.del(cls);
}catch (NoSuchFieldException | SecurityException | IllegalArgumentException |IllegalAccessException|SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return "toList";
}/*** 修改
*@return
*/
publicString edit() {try{this.cldao.edit(cls);
}catch (NoSuchFieldException | SecurityException | IllegalArgumentException |IllegalAccessException|SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return "toList";
}
@OverridepublicClass getModel() {//TODO Auto-generated method stub
return null;
}
}
这里实现了一个BaseAction 类
packagecom.crud.web;importjavax.servlet.ServletContext;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importorg.apache.struts2.interceptor.ServletRequestAware;importorg.apache.struts2.interceptor.ServletResponseAware;/*** 每一个开发的子控制器要用的属性都定义在通用的action中。
*@authorAdministrator
**/
public class BaseAction implementsServletRequestAware, ServletResponseAware{/*** 为了传值使用*/
protectedHttpServletResponse response;protectedHttpServletRequest request;protectedHttpSession session;protectedServletContext 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页面传值所用字段*/
protectedObject result;protectedObject msg;protected intcode;publicObject getResult() {returnresult;
}publicObject getMsg() {returnmsg;
}public intgetCode() {returncode;
}
@Overridepublic voidsetServletResponse(HttpServletResponse arg0) {this.response =arg0;
}
@Overridepublic voidsetServletRequest(HttpServletRequest arg0) {this.request =arg0;this.session =arg0.getSession();this.application =arg0.getServletContext();
}
}
六:配置struts_sy.xml文件
/clsList.jsp
/clsupdate.jsp
/cls_list
七:连接前端显示数据并且调用实现效果
ClsList.jsp(显示数据并且调用Crud)
Insert title here班级
班级名:编号 | 班级名 | 学生名 | 图片 | 操作 |
${c.cid } | ${c.classname } | ${c.cname} | ${c.upload } |
Clsupdate.jsp(新增与修改公用界面)
Insert title herecid:classname:
cname:
upload:
最后:展示效果
谢谢观看!今天的分享到此结束!