陈旧的开发模式

美工(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>

效果如下:

 

 

 

posted on 2019-07-04 23:33  旧城微冷  阅读(1180)  评论(0编辑  收藏  举报