easyui前后端分离

陈旧的开发模式

美工(ui工程师:出一个项目模型)

前端工程师做html页面

java工程师:将原有的html转成jsp,动态展示数据

前后端强依赖,后端必须要等前端的html做好才能套jsp。如果html发生变更,就更痛了,开发效率低


前后端分离

核心思想是前端html页面通过ajax调用后端的restuful api接口并使用json数据进行交互。

前后端约定接口&数据&参数

在开发前约定数据交互的格式。

前后端并行开发(无强依赖,可前后端并行开发,如果需求变更,只要接口&参数不变,就不用两边都修改代码,开发效率高)

美工:只管展示tree_data1.json

 

案例(easyui)

在同包的位置下创建一个js文件确定数据交互的格式,如下:

{"total":28,"rows":[
    {"uid":"FI-SW-01","uname":"Koi","upwd":10.00,"status":"P","listprice":36.50,"attr1":"Large","itemid":"EST-1"},
    {"uid":"K9-DL-01","uname":"Dalmation","upwd":12.00,"status":"P","listprice":18.50,"attr1":"Spotted Adult Female","itemid":"EST-10"},
    {"uid":"RP-SN-01","uname":"Rattlesnake","upwd":12.00,"status":"P","listprice":38.50,"attr1":"Venomless","itemid":"EST-11"},
    {"uid":"RP-SN-01","uname":"Rattlesnake","upwd":12.00,"status":"P","listprice":26.50,"attr1":"Rattleless","itemid":"EST-12"},
    {"uid":"RP-LI-02","uname":"Iguana","upwd":12.00,"status":"P","listprice":35.50,"attr1":"Green Adult","itemid":"EST-13"},
    {"uid":"FL-DSH-01","uname":"Manx","upwd":12.00,"status":"P","listprice":158.50,"attr1":"Tailless","itemid":"EST-14"},
    {"uid":"FL-DSH-01","uname":"Manx","upwd":12.00,"status":"P","listprice":83.50,"attr1":"With tail","itemid":"EST-15"},
    {"uid":"FL-DLH-02","uname":"Persian","upwd":12.00,"status":"P","listprice":23.50,"attr1":"Adult Female","itemid":"EST-16"},
    {"uid":"FL-DLH-02","uname":"Persian","upwd":12.00,"status":"P","listprice":89.50,"attr1":"Adult Male","itemid":"EST-17"},
    {"uid":"AV-CB-01","uname":"Amazon Parrot","upwd":92.00,"status":"P","listprice":63.50,"attr1":"Adult Male","itemid":"EST-18"}
]}

前端代码

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>

<link rel="stylesheet" type="text/css"
    href="${pageContext.request.contextPath}/static/js/public/easyui5/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
    href="${pageContext.request.contextPath}/static/js/public/easyui5/themes/icon.css">
<script type="text/javascript"
    src="${pageContext.request.contextPath}/static/js/public/easyui5/jquery.min.js"></script>
<script type="text/javascript"
    src="${pageContext.request.contextPath}/static/js/public/easyui5/jquery.easyui.min.js"></script>
<script type="text/javascript"
    src="${pageContext.request.contextPath}/static/js/userManage.js"></script>
</head>
<body>
<!-- 展示的数据 -->
<table id="dg"></table>
<!-- 弹窗 -->
<div id="dd" class="easyui-dialog" title="My Dialog" style="width:400px;height:200px;"   
        data-options="iconCls:'icon-save',resizable:true,modal:true,closed:true,buttons:'#bb'">   
    Dialog Content.  
    <!-- 提交的from表单 -->
<form id="ff" method="post">  
    <input type="hidden" name="SerialNo"> 
    <!-- 
        easyui自带一些简单的正则表达式,
        也可以在easyui中自定义validType:xxx  这个xxx就代表一种正则
            $(function(validType){
                
            })    
    -->
    <div>   
        <label for="name">uid:</label>   
        <input class="easyui-validatebox" type="text" name="uid" data-options="required:true" />   
    </div>   
    <div>   
        <label for="name">uname:</label>   
        <input class="easyui-validatebox" type="text" name="uname" data-options="required:true" />   
    </div> 
    <div>   
        <label for="name">upwd:</label>   
        <input class="easyui-validatebox" type="text" name="upwd" data-options="required:true" />   
    </div> 
</form> 

<div id="bb">
<a href="#" class="easyui-linkbutton " onclick="ok()">保存</a>
<a href="#" class="easyui-linkbutton" >关闭</a>
</div>

</body>
</html>

js代码:

$(function(){
    $('#dg').datagrid({    
        url:$("#ctx").val()+'/userAction.action?methodName=list',  
        fitColumns:true,
        fit:true,
        pagination:true,
        columns:[[    
            {field:'uid',title:'用户ID',width:100},    
            {field:'uname',title:'名称',width:100},    
            {field:'upwd',title:'密码',width:100,align:'right'}    
        ]],
        toolbar: [{
            
            iconCls: 'icon-edit',
            handler: function(){
                var row=$('#dg').datagrid('getSelected');
                $("#zz").attr("data","edit");
                if(row){
                    $('#ff').form('load',row);
                    $('#dd').dialog('open');
                }
            }
        },'-',{
            iconCls: 'icon-add',
            handler: function(){
                var row=$('#dg').datagrid('getSelected');
                //修改方法名
                $("#zz").attr("data","add");
                //清空数据
                $('#ff').form('clear');
                //打开提示框
                $('#dd').dialog('open');        
            }
        },'-',{
            //删除方法
            iconCls: 'icon-remove',
            handler: function(){
                //获取选中的数据
                var row=$('#dg').datagrid('getSelected');
                $.ajax({
                    //请求地址与参数传递
                     url:$("#ctx").val()+'/userAction.action?methodName=remove&SerialNo='+row.SerialNo,
                     success: function(param){    
                            //重新载入页面
                            $('#dg').datagrid('reload');
                        
                        }    
                })
            }
        }]
    
    }); 
    
})

/**
 * 搜索的方法
 * @returns
 */
function qq(){
    //获取文本框的值
    var query=$("#qq").val();
    $("#dg").datagrid({
        url:$("#ctx").val()+'/userAction.action?methodName=query&uname='+query
    });
}

/**
 * 新增和修改方法
 * @returns
 */
function ok(){
    //获取方法名
    var a=$("#zz").attr("data");
    $('#ff').form('submit', {       
        url:'../userAction.action?methodName='+a,    
        success: function(param){    
            $('#dd').dialog('close');
            $('#dg').datagrid('reload');
            $('#ff').form('clear'),
            $('#dd').dialog('close')
        }    
    }); 
}

 

后端

dao方法:

package com.dao;

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

import com.util.JsonBaseDao;
import com.util.JsonUtils;
import com.util.PageBean;
import com.util.StringUtils;

public class UserDao extends JsonBaseDao {
    /**
     * 修改方法
     * @param paMap
     * @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_easyui_user_version2 set uid=?,uname=?,upwd=? where serialno=?";    
        return super.executeUpdate(sql, new String[] {"uid","uname","upwd","SerialNo"}, paMap);
        
    }
    
    /**
     * 新增方法
     * @param paMap
     * @return
     * @throws Exception
     */
    public int add(Map<String, String[]> paMap)throws Exception  {
        String sql="insert into t_easyui_user_version2 (uid,uname,upwd) values (?,?,?)";
        return super.executeUpdate(sql, new String[] {"uid","uname","upwd"}, paMap);
        
    }
    
    /**
     * 删除方法
     * @param paMap
     * @return
     * @throws Exception
     */
    public int remove(Map<String, String[]> paMap)throws Exception {
        String sql="delete from t_easyui_user_version2 where SerialNo=?";
        return super.executeUpdate(sql, new String[] {"SerialNo"}, paMap);
        
    }

    
    /**
     * 查询的方法
     * @param paMap
     * @param pageBean
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public List<Map<String, Object>> query(Map<String, String[]> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
        String sql="select * from t_easyui_user_version2 where true";
        String uname = JsonUtils.getParamVal(paMap, "uname");
        if (StringUtils.isNotBlank(uname)) {
            sql = sql + " and uname  like '%" + uname + "%'";
        }
        return super.executeQuery(sql, pageBean);
        
    }
}

web层:

package com.web;

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

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

import com.dao.UserDao;
import com.entity.TreeNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.util.PageBean;
import com.util.ResponseUtil;
import com.zking.framework.ActionSupport;

public class UserAction extends ActionSupport {

    private UserDao userDao = new UserDao();

    /**
     * datagrid所需数据后端程序员开发完毕
     * @param req
     * @param resp
     * @return
     */
    public String list(HttpServletRequest req,HttpServletResponse resp){
        try {
            PageBean pageBean=new PageBean();
            pageBean.setRequest(req);
            List<Map<String, Object>> list = this.userDao.query(req.getParameterMap(), pageBean);
            ObjectMapper om=new ObjectMapper();
            //数据格式转换
            Map<String, Object> map=new HashMap<>();
            map.put("total", pageBean.getTotal());
            map.put("rows", list);
            ResponseUtil.write(resp, om.writeValueAsString(map));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        
        return null;
    }
    /**
     * 查询的请求方法
     * @param req
     * @param resp
     * @return
     */
    public String query(HttpServletRequest req,HttpServletResponse resp) {
        try {
            PageBean pageBean=new PageBean();
            pageBean.setRequest(req);
            List<Map<String, Object>> list = this.userDao.query(req.getParameterMap(), pageBean);
            ObjectMapper om=new ObjectMapper();
            Map<String, Object> map=new HashMap<>();
            map.put("total", pageBean.getTotal());
            map.put("rows", list);
            ResponseUtil.write(resp, om.writeValueAsString(map));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return "index";
        
    }
    
    
    /**
     * form组件提交所需数据后端程序员处理完毕
     * @param req
     * @param resp
     * @return
     */
    public String edit(HttpServletRequest req,HttpServletResponse resp){
        try {
            int edit = this.userDao.edit(req.getParameterMap());
            ObjectMapper om=new ObjectMapper();
            ResponseUtil.write(resp, om.writeValueAsString(edit));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        return null;
    }
    
    
    /**
     * 新增的请求方法
     * @param req
     * @param resp
     * @return
     */
     
     
    public String add(HttpServletRequest req,HttpServletResponse resp){
        try {
            int add = this.userDao.add(req.getParameterMap());

            System.out.println("ok");
            ObjectMapper om=new ObjectMapper();
            ResponseUtil.write(resp, om.writeValueAsString(add));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        return null;
    }
    
    /**
     * 删除的请求方法
     * @param req
     * @param resp
     * @return
     */
    public String remove(HttpServletRequest req,HttpServletResponse resp) {
        try {
            int remove=this.userDao.remove(req.getParameterMap());
            ObjectMapper om=new ObjectMapper();
            ResponseUtil.write(resp, om.writeValueAsString(remove));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
        
    }
}

xml文件配置:

<config>
    <action path="/menuAction" type="com.web.MenuAction">
    </action>

    <action path="/userAction" type="com.web.UserAction">
        <forward name="index" path="/index.jsp" redirect="false"></forward>
        <forward name="login" path="/login.jsp" redirect="false"></forward>

    </action>
</config>

效果如下:

 

 

 

转载于:https://www.cnblogs.com/huxiaocong/p/11135587.html

Sure, I can help you with that. Here's an example of how you can upload a PHPExcel file to a MySQL database using a front-end framework like EasyUI in a separate front-end and back-end setup. First, let's start with the front-end code using EasyUI to handle the file upload: ```html <!DOCTYPE html> <html> <head> <title>Excel Upload</title> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/easyui@1.9.25/themes/default/easyui.css"> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/easyui@1.9.25/jquery.easyui.min.js"></script> </head> <body> <h2>Excel Upload</h2> <form id="excelForm" method="post" enctype="multipart/form-data"> <input id="excelFile" name="excelFile" type="file"> <button id="uploadBtn" class="easyui-linkbutton" type="submit">Upload</button> </form> <script type="text/javascript"> $(function(){ $('#excelForm').form({ url: 'upload.php', onSubmit: function(){ return $(this).form('validate'); }, success: function(result){ $.messager.show({ title: 'Success', msg: result, timeout: 5000 }); } }); }); </script> </body> </html> ``` Next, let's create the `upload.php` file on the server side to handle the file upload and database insertion: ```php <?php // Include PHPExcel library require_once 'PHPExcel/PHPExcel.php'; // Database connection details $host = 'localhost'; $username = 'your_username'; $password = 'your_password'; $database = 'your_database'; // File upload directory $targetDir = 'uploads/'; // Create target directory if it doesn't exist if (!is_dir($targetDir)) { mkdir($targetDir, 0777, true); } // Handle file upload $targetFile = $targetDir . basename($_FILES["excelFile"]["name"]); move_uploaded_file($_FILES["excelFile"]["tmp_name"], $targetFile); // Read the uploaded file using PHPExcel $objPHPExcel = PHPExcel_IOFactory::load($targetFile); $worksheet = $objPHPExcel->getActiveSheet(); // Database connection $conn = new mysqli($host, $username, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Loop through each row in the worksheet foreach ($worksheet->getRowIterator() as $row) { $rowData = []; $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); // Loop through each cell in the row foreach ($cellIterator as $cell) { $rowData[] = $cell->getValue(); } // Insert row data into the database $sql = "INSERT INTO your_table_name (column1, column2, column3) VALUES (?, ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("sss", $rowData[0], $rowData[1], $rowData[2]); $stmt->execute(); } // Close database connection $conn->close(); // Delete the uploaded file unlink($targetFile); echo "Upload successful!"; ?> ``` Make sure to create a directory named "uploads" in the same directory as the `upload.php` file to store the uploaded files. Replace `'your_username'`, `'your_password'`, `'your_database'`, and `'your_table_name'` with your actual database credentials and table name. This is a basic example to get you started. You may need to modify it based on your specific requirements and validations. Additionally, make sure to sanitize and validate user input to prevent any security vulnerabilities. I hope this helps you with uploading PHPExcel files to a MySQL database using a front-end framework like EasyUI in a separate front-end and back-end setup. Let me know if you have any further questions!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值