bestpay学习 - - 一个轻量级的完全开源项目

NUTZ  一个轻量级的完全开源项目

* 讲义:bestpay

* 讲义创建:2018年6月13日10:49:22

设计背景

随着脚本语言所刮起的开发热潮,Java在Web开发领域逐渐露出疲态,而Java被“脚本小子”诟病最多的便是低下的开发效率。从本质上来说,Java语言本身为程序员提供的帮助只有两点,一是语言的语法,二是内置的类库。

现在从事Web开发,大多是采用第三方的类库(或者说是框架),比如流行的SSH。 所谓Java在Web开发的低效,不妨这样说比较贴切一些:采用第三方类库进行开发比较低效。为此,开发者zozoh开发了这一旨在提高Web开发人员的生产力的Nutz框架。

Nutz可以做什么?

  • Dao:针对JDBC的薄封装,事务模板,无缓存
  • Ioc:JSON 风格的配置文件,声明时切片支持
  • Mvc:注解风格的配置,内置多文件上传功能
  • Json:解析和渲染
  • Castors:Java对象类型转换
  • Lang: 更简洁的Java函数以及更丰富的反射支持
  • Aop: 轻便快速的切面编程支持
  • Plugin:轻便的插件机制
  • Resource:资源扫描

Nutz为谁而设计?

  • 如果你觉得Hibernate控制比较繁琐,iBatis编写SQL又比较麻烦,Nutz.Dao专为你设计。
  • 如果你觉得在多个服务器部署或者修改Spring配置文件很麻烦,Nutz.Ioc专为你设计
  • 如果你觉得直接写XML配置文件很麻烦,可视化编辑器又没控制感,Nutz.Mvc专为你设计
  • 如果你觉得JSON转换很麻烦(要写超过一行以上的代码),Nutz.Json专为你设计
  • 如果你觉得Java语法不如Ruby便捷, Nutz.Castor以及Nutz.Lang专为你设计
  • 如果你以前根本没接触过SSH ,只使用JDBC编程, 整个Nutz专门为你设计

同传统的SSH相比,它所具备的特点:

  • 轻:当前最新版,整个jar文件共950k
  • 薄: 针对JDBC的薄封装,无缓存
  • 全:提供了 Dao (ORM, SQL 管理),Ioc, Aop, Mvc, Json解析等必要功能
  • 活:各个部分可以独立使用,比如在Spring里采用Nutz.Dao ,又比如在Nutz.Ioc里使用 - Hibernate等
  • 整:它所有功能均不依赖第三方jar文件。

简单!!如果一个Web应用,你在WEB-INF/lib下只需要放置一个nutz.jar就够了

活跃的社区,回复非常及时

快速搭建一个管理后台

1. 首先去nutz的github 下载一份源码(这里选择管理后台源码)

  • 点击https://nutz.cn/yvr/t/tdb5l3e7pajv1ptl1f0nveg1bk去选择一份自己心仪的demo

这里选择企业级管理平台: https://github.com/Wizzercn/NutzWk,效果图如下

  • 项目介绍

搭建成功后的效果图

搭建的工作量

  • 基于企业级demo,创建一个新的模块,命名长新云(ChangXinYun)
    代码具备如下功能:
    • list列表功能,具备分页,筛选记录,导出
    • 新增(或CRUD)
    • 导入excel




ChangXinYunController.java 代码:

        package cn.wizzer.app.web.modules.controllers.platform.cms;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.OutputStream;
        import java.sql.ResultSet;
        import java.sql.SQLException;
        import java.text.DecimalFormat;
        import java.util.Date;
        import java.util.HashMap;
        import java.util.LinkedList;
        import java.util.List;
        import java.util.Map;

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

        import org.apache.poi.hssf.usermodel.HSSFFont;
        import org.apache.poi.hssf.usermodel.HSSFWorkbook;
        import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException;
        import org.apache.poi.ss.usermodel.Cell;
        import org.apache.poi.ss.usermodel.CellStyle;
        import org.apache.poi.ss.usermodel.Row;
        import org.apache.poi.ss.usermodel.Sheet;
        import org.apache.poi.xssf.usermodel.XSSFWorkbook;
        import org.apache.shiro.authz.annotation.RequiresAuthentication;
        import org.nutz.dao.Dao;
        import org.nutz.dao.Sqls;
        import org.nutz.dao.entity.Record;
        import org.nutz.dao.sql.Sql;
        import org.nutz.dao.sql.SqlCallback;
        import org.nutz.ioc.loader.annotation.Inject;
        import org.nutz.ioc.loader.annotation.IocBean;
        import org.nutz.lang.Strings;
        import org.nutz.lang.random.R;
        import org.nutz.lang.util.NutMap;
        import org.nutz.log.Log;
        import org.nutz.log.Logs;
        import org.nutz.mvc.adaptor.WhaleAdaptor;
        import org.nutz.mvc.annotation.AdaptBy;
        import org.nutz.mvc.annotation.At;
        import org.nutz.mvc.annotation.Ok;
        import org.nutz.mvc.annotation.POST;
        import org.nutz.mvc.annotation.Param;
        import org.nutz.mvc.impl.AdaptorErrorContext;
        import org.nutz.mvc.upload.TempFile;
        import org.nutz.mvc.upload.UploadAdaptor;

        import com.alibaba.druid.util.StringUtils;
        import com.mysql.jdbc.Connection;

        import cn.wizzer.app.cms.modules.models.ChangXinYunModel;
        import cn.wizzer.app.cms.modules.services.ChangXinYunService;
        import cn.wizzer.app.sys.modules.services.SysMenuService;
        import cn.wizzer.app.web.commons.base.Globals;
        import cn.wizzer.app.web.commons.slog.annotation.SLog;
        import cn.wizzer.app.web.modules.controllers.httputils.HttpClient4;
        import cn.wizzer.framework.base.Result;
        import cn.wizzer.framework.page.datatable.DataTableColumn;
        import cn.wizzer.framework.page.datatable.DataTableOrder;
        import cn.wizzer.framework.util.DateUtil;
        import okhttp3.Request;

        /**
         * Created by William 2018年6月5日09:55:33
         */
        @IocBean
        @At("/platform/changxinyun")
        public class ChangXinYunController {
            @SuppressWarnings("unused")
            private static final Log log = Logs.get();

            @Inject
            private SysMenuService menuService;

            @Inject
            private ChangXinYunService changXinYunService;

            @Inject
            private Dao dao;
            //dao.create(ChangXinYunModel.class, true);

            @At({"", "/index/","/index/?"})
            @Ok("beetl:/changxinyun/index.html")
            @RequiresAuthentication
            public void index(@Param("startDealWithTimeMills") String startDealWithTimeMills,@Param("startDealWithTimeMills") String fromUrl ,HttpServletRequest req) {

                if (!StringUtils.isEmpty(fromUrl))
                    req.setAttribute("startDealWithTimeMills", startDealWithTimeMills);
                else 
                    req.setAttribute("startDealWithTimeMills", "");
            }

            @At
            @Ok("json:full")
            @RequiresAuthentication
            public Object data(@Param("startDealWithTimeMills") String startDealWithTimeMills,@Param("searchKey") String searchKey,@Param("name") String name,@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List order, @Param("::columns") List columns,
                    HttpServletRequest req) {
            String whereName = "";
            if (!Strings.isBlank(searchKey)){
                whereName = " and ( t.pid LIKE '%"+searchKey+"%' or t.name like '%"+searchKey+"%' or t.phone like '%"+searchKey+"%') ";
            }

            if (!Strings.isBlank(startDealWithTimeMills)){
                whereName = " and  requestAt > '"+startDealWithTimeMills+"' ";
            }

            String sqlCount ="SELECT t.* from YZF_ChangXinYun t where 1=1 "+whereName+" order by orderBy desc";// WHERE type='0'"+whereName+"ORDER BY isTop DESC"; 
            Sql sql = Sqls.create(sqlCount);

            NutMap re = changXinYunService.data(length, start, draw,sql,sql);

            @SuppressWarnings("rawtypes")
            LinkedList dataList = (LinkedList) re.get("data");

            for (int i=0;i params = new HashMap<>();
                if (key == null ||value == null) return Result.error("key or value 不能全部为空");

                String name = null,pid = null,phone = null;
                for (int i=0;i list = new LinkedList();
                        while (rs.next())
                            list.add(rs.getString("orderBy"));
                        return list;
                    }
                });
                dao.execute(sql);
                List list = sql.getList(String.class);
                return (list == null || list.isEmpty()) ? 1 :(int)Double.parseDouble(list.get(0)) + 1;
                }

            /**
             * 插入数据对象到数据库中
             * @param order
             * @param name
             * @param pid
             * @param phone
             * @return
             * @deprecated
             */
            private ChangXinYunModel doGetChangXinYunModel(int order,String name,String pid,String phone) {
                ChangXinYunModel cxyModel = new ChangXinYunModel();
                    cxyModel.setOrderBy(order);
                    cxyModel.setName(name);
                    cxyModel.setPid(pid);
                    cxyModel.setPhone(phone);
                    StringBuilder sb =  new StringBuilder();
                    sb.append("https://api.--xxxx.com/xxxxxxx/query?");
                    sb.append("name="+name+"&");
                    sb.append("pid="+pid+"&");
                    sb.append("phone="+phone+"&");
                    sb.append("type="+1+"&");
                    String token = "xxxxxxxxxxxxxx";
                    sb.append("token="+token);
                    String result = HttpClient4.doGet(sb.toString());
                    cxyModel.setToken(token);
                    cxyModel.setMethodName("GET");
                    cxyModel.setOpAt(Integer.parseInt(System.currentTimeMillis()/1000+""));
                    cxyModel.setPath(sb.toString());
                    cxyModel.setRequestAt(""+System.currentTimeMillis());
                    cxyModel.setResult(result);
                    cxyModel.setDelFlag(false);
                    cxyModel.setBank_card("");
                    cxyModel.setComment("三要素认证");
                    cxyModel.setHead("");
                    cxyModel.setOtherInfo("");
                    cxyModel.setPhone(phone);
                    cxyModel.setPid(pid);
                    dao.insert(cxyModel);
                return cxyModel;
            }

            @SuppressWarnings("deprecation")
                private String getValue(Cell cell) {
                if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)
                    return String.valueOf(cell.getBooleanCellValue()); // 返回布尔类型的值 
                else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                     DecimalFormat df = new DecimalFormat("0");
                     String val = df.format(cell.getNumericCellValue());        
                    return val; // 返回数值类型的值 
                }
                else 
                    return String.valueOf(cell.getStringCellValue());  // 返回字符串类型的值 
            }

            @SuppressWarnings("resource")
            private void readExcel(InputStream in,boolean is2010) throws Exception {
                InputStream is = in;
                org.apache.poi.ss.usermodel.Workbook workBook = null;
                if (is2010)
                    workBook = new XSSFWorkbook(is); //2010
                else 
                    workBook = new HSSFWorkbook(is); //2003-2007

                if (workBook.getNumberOfSheets() < 1) throw new RuntimeException("excel没有表格存在");

                // 循环工作表Sheet
                for (int numSheet = 0; numSheet < workBook.getNumberOfSheets(); numSheet++) {
                    Sheet sheet = workBook.getSheetAt(numSheet);
                    if (sheet == null) {
                        continue;
                    }

                    //校验表头  序号 姓名 身份证 手机号
                    if (sheet.getLastRowNum() < 1) continue;
                    Row headRow = sheet.getRow(0);

                    if (headRow.getCell(0) == null || StringUtils.isEmpty(getValue(headRow.getCell(0))) || !getValue(headRow.getCell(0)).trim().equals("序号")) throw new RuntimeException("表头第一列必须为[序号]");
                    if (headRow.getCell(1) == null || StringUtils.isEmpty(getValue(headRow.getCell(1))) || !getValue(headRow.getCell(1)).trim().equals("姓名")) throw new RuntimeException("表头第一列必须为[姓名]");
                    if (headRow.getCell(2) == null || StringUtils.isEmpty(getValue(headRow.getCell(2))) || !getValue(headRow.getCell(2)).trim().equals("身份证")) throw new RuntimeException("表头第一列必须为[身份证]");
                    if (headRow.getCell(3) == null || StringUtils.isEmpty(getValue(headRow.getCell(3))) || !getValue(headRow.getCell(3)).trim().equals("手机号")) throw new RuntimeException("表头第一列必须为[手机号]");

                    //校验表格数据必须大于1条
                    if (sheet.getLastRowNum() < 2) throw new RuntimeException(sheet.getSheetName() + ",没有需要导入的数据");

                    // 循环行Row
                    for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                        Row row = sheet.getRow(rowNum);
                        if (row == null) {
                            continue;
                        }

                        if (rowNum == 100) Thread.sleep(1000);

                        if (row.getCell(1) == null || StringUtils.isEmpty(getValue(row.getCell(1)))) continue;
                        if (row.getCell(2) == null || StringUtils.isEmpty(getValue(row.getCell(2)))) continue;
                        if (row.getCell(3) == null || StringUtils.isEmpty(getValue(row.getCell(3)))) continue;
                        //init Model
                        doPostChangXinYunModel(getValue(row.getCell(1)), getValue(row.getCell(2)), getValue(row.getCell(3)),null);
                    }
                }
            }

            private HttpServletRequest getTeamInfo(HttpServletRequest req ,String sql) {
                req.setAttribute("teams", changXinYunService.list(Sqls.create(sql)));
                return req;
            }

            @SuppressWarnings({ "unchecked", "deprecation" })
            @At("/export")
            @Ok("void") // 加了之后不走RouteFilter,否则响应输出流出错
            @SLog(tag = "导出长新云", msg = "ID:${args[2].getAttribute('id')}")
            public void export(HttpServletRequest req, HttpServletResponse resp) {
                String searchKey = (String) req.getParameter("searchKey");

                OutputStream out = null;
                    HSSFWorkbook workbook=null;

                    try {
                        out = resp.getOutputStream();

                        // poi
                        resp.addHeader("content-type", "applicationnd.ms-excel;charset=utf-8");
                        resp.addHeader("content-disposition", "attachment; filename=ChangXinYun"+DateUtil.format(new Date(), "yyyyMMddHHmmss")+".xls"); 
                        //          Workbook workBook = Excel.createWorkbook(Excel.Excel_Type.EXCEL_97_2003);
                        //HSSFWorkbook workbook = new HSSFWorkbook();
                         workbook = new HSSFWorkbook();

                        Sheet sheet = workbook.createSheet("长新云数据");

                        String whereName = "";
                    if (!Strings.isBlank(searchKey)){
                        whereName = " and ( t.pid LIKE '%"+searchKey+"%' or t.name like '%"+searchKey+"%' or t.phone like '%"+searchKey+"%') ";
                    }

                    String sql ="SELECT t.* from YZF_ChangXinYun t where 1=1 "+whereName+" order by orderBy ";// WHERE type='0'"+whereName+"ORDER BY isTop DESC";

                        req = getTeamInfo(req,sql + " asc");
                        Row row = sheet.createRow(0);

                        HSSFFont font  = workbook.createFont();
                        font.setFontName("微软雅黑");
                        font.setFontHeightInPoints((short) 11);//设置字体大小
                        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示

                        CellStyle headStyle = workbook.createCellStyle();
                        headStyle.setAlignment(CellStyle.ALIGN_CENTER);
                        headStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
                        headStyle.setBorderRight(CellStyle.BORDER_THIN);
                        headStyle.setFont(font);
                        //SELECT t.*,l.matchName as matchname from game_team t left join game_matchmain l on t.leagueId=l.id 
                        Cell head0 = row.createCell(0);
                        head0.setCellValue("序号");
                        head0.setCellStyle(headStyle);
                        Cell head1 = row.createCell(1);
                        head1.setCellValue("姓名");
                        head1.setCellStyle(headStyle);
                        Cell head2 = row.createCell(2);
                        head2.setCellValue("身份证");
                        head2.setCellStyle(headStyle);
                        Cell head3 = row.createCell(3);
                        head3.setCellValue("手机号");
                        head3.setCellStyle(headStyle);
                        Cell head4 = row.createCell(4);
                        head4.setCellValue("查询类型");
                        head4.setCellStyle(headStyle);
                        Cell head5 = row.createCell(5);
                        head5.setCellValue("结果");
                        head5.setCellStyle(headStyle);

                        List records = (List) req.getAttribute("teams");
                        for (int i = 0; i < records.size(); i++) {
                            Row r = sheet.createRow(i + 1);
                            r.createCell(0).setCellValue(records.get(i).getString("orderby"));
                            r.createCell(1).setCellValue(records.get(i).getString("name"));
                            r.createCell(2).setCellValue(records.get(i).getString("pid"));
                            r.createCell(3).setCellValue(records.get(i).getString("phone"));
                            r.createCell(4).setCellValue("实名认证");
                            r.createCell(5).setCellValue(records.get(i).getString("result"));
                        }

                sheet.autoSizeColumn((short)0); //调整第一列宽度
                sheet.autoSizeColumn((short)1); //调整第二列宽度
                sheet.autoSizeColumn((short)2); //调整第三列宽度
                sheet.autoSizeColumn((short)3); //调整第四列宽度
                sheet.autoSizeColumn((short)4); //调整第五列宽度
                sheet.autoSizeColumn((short)5); //调整第六列宽度

                        workbook.write(out);    // 输出
                        out.flush();
                    } catch (Exception e) {
                        System.out.println("**************队伍信息导出为EXCEL发生错误");
                        e.printStackTrace();
                    } finally {
                        try {
                            workbook.close();
                            out.close();
                        } catch (IOException e) 
                        {
                            e.printStackTrace();
                        }
                    }
            }

        }




首页index.html 代码

    <% layout("/layouts/platform.html"){ %>
    
    
序号 姓名 身份证 手机号 查询类型 结果

高级筛选

<%}%>



- 效果图 -






学习参考地址

名称 路径 备注
nutz首页 http://nutzam.com/index.html nutz首页,Nutz 1.r.65(怪物猎人)发布
github地址 https://github.com/nutzam 开发配套的源码地址,可以再github搜索”nutz
apidoc http://www.nutzam.com/core/dao/basic_operations.html# nutz帮助文档地址
分布式 https://www.oschina.net/news/94388/nutzwk-5-0-1-released NutzWk 5.0.1 发布,Java 微服务分布式开发框架
其他源码地址 https://github.com/wendal/nutz-book-project Nutz 活跃开发作者:wendal,github地址








你可能感兴趣的:(翼支付,javaweb)