Struts2结合layui完成的增删查改

  • Post author:
  • Post category:其他



前言:利用Struts2结合layui完成的增删查改可以节省代码量是界面更美观

以下我分了7步给大家讲解一下



1、导入相关的pom依赖,引入layui(struts、自定义标签库的依赖)


这些是我下载的jar包


注意:一定要导入自定义标签库的依赖,layui就自己去官网下载吧,这里就不介绍了

	<!--我们需要自定义标签库一定要引用这个jar包  -->
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jsp-api</artifactId>
			<version>8.0.47</version>
		</dependency>
<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.zrh</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>
   	
   	<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.44</version>
		</dependency>
   	
     <dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		
    
			<dependency> 
			   <groupId>javax.servlet.jsp</groupId> 
			   <artifactId>jsp-api</artifactId> 
			   <version>2.1</version> 
			   <scope>provided</scope>
			</dependency>
			
			<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
		
		
		<!--我们需要自定义标签库一定要引用这个jar包  -->
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jsp-api</artifactId>
			<version>8.0.47</version>
		</dependency>
			
		
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		    <version>2.4.4</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、完成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.zrh.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>
  	<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>



3、dao层去访问数据


注意:在这里继承的是JsonBaseDao不是BaseDao

package com.zrh.crud.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.zrh.crud.entity.clazz;
import com.zrh.crud.util.BaseDao;
import com.zrh.crud.util.JsonBaseDao;
import com.zrh.crud.util.JsonUtils;
import com.zrh.crud.util.PageBean;
import com.zrh.util.StringUtils;

public class clazzDao extends JsonBaseDao{
	/**
	 * 查询分页方法,查询单挑数据公用的方法
	 * @param clz
	 * @param pagebean
	 * @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 * from t_struts_class where true";
		String cname = JsonUtils.getParamVal(paMap, "cname");
		String cid = JsonUtils.getParamVal(paMap, "cid");
		if(StringUtils.isNotBlank(cid)) {
			sql += " and cid = "+cid+"";
		}
		if(StringUtils.isNotBlank(cname)) {
			sql += " and cname like '%"+cname+"%'";
		}
		return super.executeQuery(sql , pageBean);
	}
	
	/**
	 * 增加
	 * @param clz
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public int add(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql="insert into t_struts_class (cid,cname,cteacher) values(?,?,?)";
		return super.executeUpdate(sql, new String[] {"cid","cname","cteacher"}, paMap);
	}
	
	/**
	 * 修改
	 * @param clz
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public int edit(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql = "update  t_struts_class set cname=?,cteacher=? where cid=?";
		return super.executeUpdate(sql, new String[] {"cname","cteacher","cid"}, paMap);
	}
	
	/**
	 * 删除
	 * @param clz
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public int del(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql = "delete from t_struts_class where cid=?";
		return super.executeUpdate(sql, new String[] {"cid"}, paMap);
	}
	
	}



4、web层去调用dao层给前台返回数据

package com.zrh.crud.web;
/**
 * 和MVC有一点不一样不用继承
 * @author zrh
 *
 */

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.opensymphony.xwork2.ModelDriven;
import com.zrh.crud.dao.clazzDao;
import com.zrh.crud.entity.clazz;
import com.zrh.crud.util.PageBean;
import com.zrh.crud.util.ResponseUtil;

public class clazzAction extends BaseAction implements ModelDriven<clazz>{
	
	private clazzDao clzDao = new clazzDao();
	private clazz clz = new clazz();
	
	
	
	/**
	 * 查询书籍类别
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		try {
			PageBean pageBean=new PageBean();
			pageBean.setRequest(request);
			List<Map<String, Object>>  list = this.clzDao.list(request.getParameterMap(), pageBean);
			ObjectMapper om =new ObjectMapper();
			Map<String, Object> map=new HashMap<>();
			map.put("code", 0);
			map.put("count", pageBean.getTotal());
			map.put("data", list);
			ResponseUtil.write(response, om.writeValueAsString(map));
		} catch (InstantiationException e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	
	
	
	/**
	 * 增加
	 * @param req
	 * @param resp
	 * @return
	 */
	public String add() {
		try {
			int add = this.clzDao.add(request.getParameterMap());
			if(add>0) {
				System.out.println("成功");
			}else {
				System.out.println("失败");
			}
			ObjectMapper om = new ObjectMapper();
			ResponseUtil.write(response, om.writeValueAsString(add));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	
	/**
	 * 删除书本类别
	 * @throws Exception 
	 * @throws JsonProcessingException 
	 * 
	 */

	public String del() throws  Exception {
		try {
			int del = this.clzDao.del(request.getParameterMap());
			ObjectMapper om=new ObjectMapper();
			ResponseUtil.write(response, om.writeValueAsString(del));
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 修改书籍类别
	 * @param req
	 * @param resp
	 * @return
	 * @throws JsonProcessingException
	 * @throws Exception
	 */
	
	public String edit() throws  Exception {
		try {
			int edit=this.clzDao.edit(request.getParameterMap());
			ObjectMapper om=new ObjectMapper();
			ResponseUtil.write(response, om.writeValueAsString(edit));
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	

	@Override
	public clazz getModel() {
		// TODO Auto-generated method stub
		return null;
	}
}



这里继承了BaseAction我们需要的response request


每一个开发的子控制器要用的属性都定义在通用的action中,这样既方便又好用

package com.zrh.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();
	}
}



5、在struts_sy.xml进行配置

	<action name="/clz_*" class="com.zrh.crud.web.clazzAction" method="{1}">
			<result name="list">/clzList.jsp</result>
	</action>



6、写jsp


引入自己的路径

<link rel="stylesheet" href="static/js/layui/css/layui.css" >
<script src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script>
<script type="text/javascript" src="static/js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/class.js">
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%-- <%@ include file="/jsp/common/head.jsp" %> --%>    
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="static/js/layui/css/layui.css" >
<script src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script>
<script type="text/javascript" src="static/js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/class.js"></script>  
</head>


<body class="child-body">
<div class="child-nav">
    <span class="layui-breadcrumb">
         <a>班级管理</a>
         <a><cite>分类列表</cite></a>
    </span>
</div>
<blockquote class="layui-elem-quote">

<!--搜索维度  -->
 <div class="layui-form">
    <div class="layui-form-item">
        <label class="layui-form-label">班级名称</label>
        <div class="layui-input-inline">
            <input type="text" id='cname' name="cname" lay-verify="required" placeholder="请输入>班级名称" autocomplete="true" class="layui-input">
        </div>
        <button class="layui-btn layui-btn-normal layui-btn-radius" data-type="reload"><i class="layui-icon">&#xe615;</i>查询</button>
        <button class="layui-btn layui-btn-normal"   data-type="add">新建</button>
    </div>
</div>   
</blockquote>

<!--隐藏域传值  -->
<input type="hidden"  id="sj" value="${pageContext.request.contextPath}" >
<!--根据table id 来展示表格数据  -->
<table class="layui-hide" id="test" lay-filter="test"></table>


<!--行内样式按钮   -->
<script type="text/html" id="lineBtns">
  <a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon">&nbsp;</i>编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<!--弹出层  -->
	 <div class="site-text" style="margin: 5%; display: none" id="box1"  target="123">
	    <form class="layui-form layui-form-pane" onsubmit="return false" id="booktype">
	        <div class="layui-form-item">
	            <label class="layui-form-label"> 编号</label>
	            <div class="layui-input-block">
	                <input type="text" class="layui-input"  id="cid"  name=cid ><br>
	            </div>
	            <br>
	            <label class="layui-form-label"> 班级名</label>
	            <div class="layui-input-block">
	                <input type="text" class="layui-input"  id="cname1"  name=cname><br>
	            </div>
	            
	             <label class="layui-form-label"> 教师</label>
	            <div class="layui-input-block">
	                <input type="text" class="layui-input"  id="cteacher"  name="cteacher"><br>
	            </div>
	            
	        </div>
	    </form>
	</div> 
</body>
</html>



7.js界面


	//执行渲染
	layui.use(['table','layer','form'],function(){
		var data=document.getElementById("sj").value;
		var table =layui.table;
		var layer=layui.layer;
		var form = layui.form;
		console.log(data+'/sy/clz_list.action');
	     /*展示数据表格  */
		table.render({
			  elem:'#test'//表格id
			,url:data+'/sy/clz_list.action'//所对应调用的接口
			,method:'post'		//提交方式
		    ,cols:[[
		    	/*根据数据库的表格所对应的名称  */
		    	{field:'cid',title:'编号',width:100,align:'center'},    
		        {field:'cname',title:'班级名',width:100,align:'center'},    
		        {field:'cteacher',title:'老师',width:100,align:'center'},
//		        {field:'pic',title:'图片',width:100,align:'center'},
		        {field:'right',height:80, width:300, title: '操作', toolbar:'#lineBtns'}//操作栏 
		    ]]
		         ,page:'true'//分页
		         , id: 'testReload'
		});
		
	
	//上方菜单操作栏(查询、以及  增加  按钮  )
    var $ = layui.$, active = {
            //查询
            reload: function () {
                var cname = $('#cname');//书籍类别名称 根据 id来取值
                console.log(cname.val());
                // 执行重载
                table.reload('testReload', {
                    page: {
                        curr: 1
                        // 重新从第 1 页开始
                    },
                    where: {
                        key: 'cname',
                        cname: cname.val(),
                    }
                });
            }, add: function () { //添加
                layer.open({//弹出框
                    type: 1,
                    title: '添加班级',
                    maxmin: true,
                    shadeClose: true, //点击遮罩关闭层
                    area: ['80%', '80%'],
                    content: $('#box1'),
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {//确定执行函数
                    	console.log(layero);
                        //执行添加方法
                        $.getJSON(data+"/sy/clz_add.action", {
                        	 cid: $("#cid").val(),
                        	 cname: $("#cname1").val(),
                        	 cteacher: $("#cteacher").val(),///角色名
                        	/* booktypename: $("input[ name='booktypename1']").val(), *///角色名
                        }, function (data) {
                        	/*根据后台返回的参数来进行判断  */
                            if (data==1) {
                                layer.alert('添加成功', {icon: 1, title: '提示'}, function (i) {
                                    layer.close(i);
                                    layer.close(index);//关闭弹出层
                                    $("#booktype")[0].reset()//重置form
                                })
                                table.reload('testReload', {//重载表格
                                    page: {
                                        curr: 1
                                        // 重新从第 1 页开始
                                    }
                                })
                            } else if(data==2){
                                layer.msg('添加失败,请勿重复添加该班级')
                            }
                        })

                    }, cancel: function (index, layero) {//取消
                        $("#booktype")[0].reset()//重置form  根据id
                        layer.close(index)
                    }
                });
            }
    }
    $('.layui-form .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
	
	
	
	/*表格 行内操作(编辑  以及  删除 按钮操作)  */
	    table.on('tool(test)', function(obj){
         var data = obj.data; //获得当前行数据
         var urlex=document.getElementById("sj").value;
         var tr=obj.tr//活动当前行tr 的  DOM对象
         console.log(data);
         var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
         if(layEvent === 'del'){ //删除
             layer.confirm('确定删除吗?',{title:'删除'}, function(index){
                 //向服务端发送删除指令og
                 $.getJSON(urlex+'/sy/clz_del.action',{cid:data.cid}, function(ret){
                         layer.close(index);//关闭弹窗
                         table.reload('testReload', {//重载表格
                             page: {
                                 curr: 1
                                 // 重新从第 1 页开始
                             }
                         })
                 });
                 layer.close(index);
             });
         } else if(layEvent === 'edit'){ //编辑
             layer.open({
                 type: 1 //Page层类型
                 ,skin: 'layui-layer-molv'
                 ,area: ['380px', '270px']
                 ,title: ['编辑班级信息','font-size:18px']
                 ,btn: ['确定', '取消'] 
                 ,shadeClose: true
                 ,shade: 0 //遮罩透明度
                 ,maxmin: true //允许全屏最小化
                 ,content:$('#box1')  //弹窗id
                 ,success:function(layero,index){
	                 $('#cid').val(data.cid);
	                 $('#cname1').val(data.cname);
	                 $('#cteacher').val(data.cteacher);
                 },yes:function(index,layero){
                	/*  $.ajaxSettings.async = false; */
                	  $.getJSON(urlex+'/sy/clz_edit.action',{
                		  cid: $('#cid').val(),
                		  cname: $('#cname1').val(), 
                		  cteacher:$('#cteacher').val(),
                		  cid: data.cid,
                	  },function(data){
                	  //根据后台返回的参数,来进行判断
                		  if(data>0){
                			  layer.alert('编辑成功',{icon:1,title:'提示'},function(i){
                				  layer.close(i);
                                  layer.close(index);//关闭弹出层
                                  $("#booktype")[0].reset()//重置form
                			  })
                			  table.reload('testReload',{//重载表格
                				  page:{
                					  curr:1
                				  }
                			  })
                		  }
                	  });
                 }
               
             
             });
         }
      
	    });
	  
});

输出结果界面为:

在这里插入图片描述

增加界面:

在这里插入图片描述

修改界面:

在这里插入图片描述



版权声明:本文为Zhangrunhong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。