天天看点

【720科技SpringMVC】---20180511 GitBook的使用(5)

内容关键词:GitBook快速开发步骤、方法使用小技巧

知识来源:720科技

快速开发步骤:

业务开发

只需按以下五个步骤就能完成一个模块的基本功能开发,也可以使用铭飞提供的在线代码生成器功能快速生成以下业务代码。下面将通过扩展通用模型basic,快速开发一个博客模块,模块名定义为mblog。

博文的表结构:

CREATE TABLE `mblog_article` (
`article_basic_id` int NOT NULL COMMENT 'basic表主键',
`article_content` text NULL COMMENT '博文内容',
PRIMARY KEY (`article_basic_id`) ,
CONSTRAINT `fk_article_basic_id` FOREIGN KEY (`article_basic_id`) REFERENCES `basic` (`BASIC_ID`) ON DELETE CASCADE ON UPDATE NO ACTION
)
COMMENT = '博文表,通过扩展basic实现';
           

第一步:实体

package net.mingsoft.mblog.entity;
import com.mingsoft.basic.entity.BasicEntity;
import java.util.Date;
import org.springframework.data.elasticsearch.annotations.Document;

 /**
 * 博客文章实体
 * @author 铭飞团队
 * @version 
 * 版本号:100<br/>
 * 创建日期:2015-6-20 16:05:42<br/>
 * 历史修订:<br/>
 */
@Document(indexName = "blogarticle")
public class ArticleEntity extends BasicEntity {
    private static final long serialVersionUID = ;
    /**
     * 博客文章自增长ID
     */
    private Integer articleBasicId; 

    /**
     * 文章内容
     */
    private String articleContent; 
    public ArticleEntity(){}
    public ArticleEntity(Integer articleBasicId) {
    this.articleBasicId = articleBasicId;
    }

    public ArticleEntity(String articleContent) {
        this.articleContent = articleContent;
    }
    /**
     * 设置博客文章自增长ID
     */
    public void setArticleBasicId(Integer articleBasicId) {
        this.articleBasicId = articleBasicId;
    }

    /**
     * 获取博客文章自增长ID
     */
    public Integer getArticleBasicId() {
        return this.articleBasicId;
    }

    /**
     * 设置文章内容
     */
    public void setArticleContent(String articleContent) {
        this.articleContent = articleContent;
    }

    /**
     * 获取文章内容
     */
    public String getArticleContent() {
        return this.articleContent;
    }
}
           

第二步:持久化

IArticleDao.java

package net.mingsoft.mblog.dao;

import com.mingsoft.base.dao.IBaseDao;
import com.mingsoft.util.*;
import java.util.*;
import org.springframework.stereotype.Component;
import net.mingsoft.mblog.entity.ArticleEntity;

/**
 * 博客文章持久层
 * @author 铭飞团队
 * @version 
 * 版本号:100<br/>
 * 创建日期:2016-6-20 16:05:42<br/>
 * 历史修订:<br/>
 */
@Component("blogArticleDao")
public interface IArticleDao extends IBaseDao {
}
           

IArticleDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="net.mingsoft.mblog.dao.IArticleDao">

    <resultMap id="resultMap" type="net.mingsoft.mblog.entity.ArticleEntity">
        <id column="article_basic_id" property="articleBasicId" /><!--博客文章自增长ID -->
        <result column="article_content" property="articleContent" /><!--文章内容 -->
        <result column="basic_title" property="basicTitle" /><!--文章内容 -->
    </resultMap>

    <!--保存-->    
    <insert id="saveEntity" useGeneratedKeys="true" keyProperty="articleBasicId"
        parameterType="net.mingsoft.mblog.entity.ArticleEntity" >
        insert into mblog_article
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="articleContent != null and articleContent != ''">article_content,</if>
            <if test="basicId != null">article_basic_id,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="articleContent != null and articleContent != ''">#{articleContent},</if>
            <if test="basicId != null">#{basicId},</if>
        </trim>
    </insert>

    <!--更新-->    
    <update id="updateEntity" parameterType="net.mingsoft.mblog.entity.ArticleEntity">
        update mblog_article
        <set>
            <if test="articleContent != null and articleContent != ''">article_content=#{articleContent},</if>    
        </set>
        where article_basic_id = #{basicId}
    </update>

    <!--根据id获取-->    
    <select id="getEntity" resultMap="resultMap" parameterType="int">
        select * from mblog_article where article_basic_id=#{articleBasicId}
    </select>

    <!--根据实体获取-->
    <select id="getByEntity" resultMap="resultMap" parameterType="net.mingsoft.mblog.entity.ArticleEntity">
        select * from mblog_article 
        <where>
            <if test="articleContent != null and articleContent != ''"> and article_content=#{articleContent} </if>                
        </where>
        limit 0,1
    </select>    

    <!--删除-->    
    <delete id="deleteEntity" parameterType="int">
        delete from mblog_article  where article_basic_id=#{articleBasicId}
    </delete>    

    <!--批量删除-->    
    <delete id="delete" >
        delete from mblog_article
        <where>
             article_basic_id  in <foreach collection="ids" item="item" index="index" 
            open="(" separator="," close=")">#{item}</foreach>
        </where>
    </delete>
    <!--查询全部-->    
    <select id="queryAll" resultMap="resultMap">
        select * from mblog_article order by article_basic_id desc
    </select>
    <!--条件查询-->    
    <select id="query" resultMap="resultMap" parameterType="net.mingsoft.mblog.entity.ArticleEntity">
        select * from mblog_article
        left join basic
        on basic.basic_id = mblog_article.article_basic_id
        <where>
                <if test="basicPeopleId &gt; 0 "> and basic_peopleid=#{basicPeopleId} </if>    
                <if test="articleContent != null and articleContent != ''"> and article_content=#{articleContent} </if>    

        </where>        
        order by article_basic_id desc
    </select>

</mapper>
           

第三步:业务

IArticleBiz.java

package net.mingsoft.mblog.biz;

import com.mingsoft.basic.biz.IBasicBiz;
import com.mingsoft.basic.entity.BasicEntity;
import com.mingsoft.util.*;
import java.util.*;
import net.mingsoft.mblog.entity.ArticleEntity;

/**
* 博客文章业务接口
* @author 铭飞团队
* @version
* 版本号:100<br/>
* 创建日期:2015-6-20 16:05:42<br/>
* 历史修订:<br/>
*/
public interface IArticleBiz extends IBasicBiz {
}
           

ArticleBizImpl.java

package net.mingsoft.mblog.biz.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mingsoft.base.biz.impl.BaseBizImpl;
import com.mingsoft.base.dao.IBaseDao;
import com.mingsoft.basic.biz.impl.BasicBizImpl;
import com.mingsoft.basic.entity.BasicEntity;
import com.mingsoft.util.*;
import java.util.*;
import net.mingsoft.mblog.entity.ArticleEntity;
import net.mingsoft.mblog.biz.IArticleBiz;
import net.mingsoft.mblog.dao.IArticleDao;

/**
 *博客文章管理持久化层
* @author 铭飞团队
* @version
* 版本号:100<br/>
* 创建日期:2015-6-20 16:05:42<br/>
* 历史修订:<br/>
 */
 @Service("blogArticleImpl")
public class ArticleBizImpl extends BasicBizImpl implements IArticleBiz {
    @Resource(name="blogArticleDao")
    private IArticleDao articleDao;

    @Override
    protected IBaseDao getDao() {
        // TODO Auto-generated method stub
        return articleDao;
    } 
}
           

第四步:控制

ArticleAction.java

package net.mingsoft.mblog.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.ui.ModelMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.mingsoft.mblog.biz.IArticleBiz;
import net.mingsoft.mblog.entity.ArticleEntity;
import net.mingsoft.mblog.search.IArticleSearch;
import net.mingsoft.mblog.search.mapping.ArticleMapping;
import net.mingsoft.base.elasticsearch.bean.BaseMapping;
import net.mingsoft.base.elasticsearch.bean.SearchBean;
import net.mingsoft.base.util.JSONObject;
import com.mingsoft.util.PageUtil;
import com.mingsoft.util.StringUtil;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.ElasticsearchUtil;
import net.mingsoft.basic.bean.ListBean;
import com.mingsoft.base.filter.DateValueFilter;
import com.mingsoft.base.filter.DoubleValueFilter;
import com.mingsoft.basic.entity.BasicEntity;
import net.mingsoft.basic.bean.EUListBean;

/**
*后台博客文章控制层
* @author 铭飞团队
* @version
* 版本号:100<br/>
* 创建日期:2015-6-20 16:05:42<br/>
* 历史修订:<br/>
 */
@Controller("blogArticleAction")
@RequestMapping("/${managerPath}/mblog/article")
public class ArticleAction extends com.mingsoft.basic.action.BaseAction{
    /**
     * 注入博客文章业务层
     */    
    @Resource(name="blogArticleImpl")
    private IArticleBiz articleBiz;
    /**
     * 返回主界面index
     */
    @RequestMapping("/index")
    public String index(HttpServletResponse response,HttpServletRequest request){
        return view ("/mblog/article/index");
    }
    /**
     * 查询博客文章列表
     * @param article 暂无描述实体
     * <i>article参数包含字段信息参考:</i><br/>
     * articleBasicId 博客文章自增长ID<br/>
     * articleContent 文章内容<br/>
     * <dt><span class="strong">返回</span></dt><br/>
     * <dd>[<br/>
     * { <br/>
     * articleBasicId: 博客文章自增长ID<br/>
     * articleContent: 文章内容<br/>
     * }<br/>
     * ]</dd><br/>     
     */
    @RequestMapping("/list")
    @ResponseBody
    public void list(@ModelAttribute ArticleEntity article,HttpServletResponse response, HttpServletRequest request,ModelMap model) {
        BasicUtil.startPage();
        List articleList = articleBiz.query(article);
        this.outJson(response, net.mingsoft.base.util.JSONArray.toJSONString(new EUListBean(articleList,(int)BasicUtil.endPage(articleList).getTotal()),new DoubleValueFilter(),new DateValueFilter()));
    }

    /**
     * 返回编辑界面article_form
     */
    @RequestMapping("/form")
    public String form(@ModelAttribute ArticleEntity article,HttpServletResponse response,HttpServletRequest request,ModelMap model){
        if(article.getArticleBasicId() != null){
            BasicEntity articleEntity = (BasicEntity) articleBiz.getEntity(article.getArticleBasicId());            
            model.addAttribute("articleEntity",articleEntity);
        }

        return view ("/mblog/article/form");
    }

    /**
     * 获取博客文章
     * @param article 博客文章实体
     * <i>article参数包含字段信息参考:</i><br/>
     * articleBasicId 博客文章自增长ID<br/>
     * articleContent 文章内容<br/>
     * <dt><span class="strong">返回</span></dt><br/>
     * <dd>{ <br/>
     * articleBasicId: 博客文章自增长ID<br/>
     * articleContent: 文章内容<br/>
     * }</dd><br/>
     */
    @RequestMapping("/get")
    @ResponseBody
    public void get(@ModelAttribute ArticleEntity article,HttpServletResponse response, HttpServletRequest request,ModelMap model){
        if(article.getArticleBasicId()<=) {
            this.outJson(response, null, false, getResString("err.error", this.getResString("article.basic.id")));
            return;
        }
        ArticleEntity _article = (ArticleEntity)articleBiz.getEntity(article.getArticleBasicId());
        this.outJson(response, _article);
    }

    /**
     * 保存博客文章实体
     * @param article 博客文章实体
     * <i>article参数包含字段信息参考:</i><br/>
     * articleBasicId 博客文章自增长ID<br/>
     * articleContent 文章内容<br/>
     * <dt><span class="strong">返回</span></dt><br/>
     * <dd>{ <br/>
     * articleBasicId: 博客文章自增长ID<br/>
     * articleContent: 文章内容<br/>
     * }</dd><br/>
     */
    @PostMapping("/save")
    @ResponseBody
    public void save(@ModelAttribute ArticleEntity article, HttpServletResponse response, HttpServletRequest request) {
        //验证文章内容的值是否合法            
        if(StringUtil.isBlank(article.getArticleContent())){
            this.outJson(response, null,false,getResString("err.empty", this.getResString("article.content")));
            return;            
        }
        articleBiz.saveBasic(article);//如果是普通模版 直接调用saveEntity(article)

        this.outJson(response, JSONObject.toJSONString(article));
    }

    /**
     * @param article 博客文章实体
     * <i>article参数包含字段信息参考:</i><br/>
     * articleBasicId:多个articleBasicId直接用逗号隔开,例如articleBasicId=1,2,3,4
     * 批量删除暂无描述
     *            <dt><span class="strong">返回</span></dt><br/>
     *            <dd>{code:"错误编码",<br/>
     *            result:"true|false",<br/>
     *            resultMsg:"错误信息"<br/>
     *            }</dd>
     */
    @RequestMapping("/delete")
    @ResponseBody
    public void delete(@RequestBody List<ArticleEntity> articles,HttpServletResponse response, HttpServletRequest request) {
        int[] ids = new int[articles.size()];
        for(int i = ;i<articles.size();i++){
            ids[i] = articles.get(i).getArticleBasicId();
        }
        articleBiz.deleteBasic(ids);    
        this.outJson(response, true);
    }

    /** 
     * 更新博客文章
     * @param article 博客文章实体
     * <i>article参数包含字段信息参考:</i><br/>
     * articleBasicId 博客文章自增长ID<br/>
     * articleContent 文章内容<br/>
     * <dt><span class="strong">返回</span></dt><br/>
     * <dd>{ <br/>
     * articleBasicId: 博客文章自增长ID<br/>
     * articleContent: 文章内容<br/>
     * }</dd><br/>
     */
    @PostMapping("/update")
    @ResponseBody     
    public void update(@ModelAttribute ArticleEntity article, HttpServletResponse response,
            HttpServletRequest request) {
        //验证文章内容的值是否合法            
        if(StringUtil.isBlank(article.getArticleContent())){
            this.outJson(response, null,false,getResString("err.empty", this.getResString("article.content")));
            return;            
        }
        articleBiz.updateBasic(article);//如果是普通模版 直接调用updateEntity(article)
        this.outJson(response, JSONObject.toJSONString(article));
    }

}
           

第五步:视图

index.ftl

<@ms.html5>
    <@ms.nav title="暂无描述管理"></@ms.nav>
    <@ms.searchForm name="searchForm" isvalidation=true>
            <@ms.searchFormButton>
                 <@ms.queryButton onclick="search()"/> 
            </@ms.searchFormButton>            
    </@ms.searchForm>
    <@ms.panel>
        <div id="toolbar">
            <@ms.panelNav>
                <@ms.buttonGroup>
                    <@ms.addButton id="addArticleBtn"/>
                    <@ms.delButton id="delArticleBtn"/>
                </@ms.buttonGroup>
            </@ms.panelNav>
        </div>
        <table id="articleList" 
            data-show-refresh="true"
            data-show-columns="true"
            data-show-export="true"
            data-method="post" 
            data-pagination="true"
            data-page-size="10"
            data-side-pagination="server">
        </table>
    </@ms.panel>

    <@ms.modal  modalName="delArticle" title="授权数据删除" >
        <@ms.modalBody>删除此授权
            <@ms.modalButton>
                <!--模态框按钮组-->
                <@ms.button  value="确认删除?"  id="deleteArticleBtn"  />
            </@ms.modalButton>
        </@ms.modalBody>
    </@ms.modal>
</@ms.html5>

<script>
    $(function(){
        $("#articleList").bootstrapTable({
            url:"${managerPath}/mblog/article/list.do",
            contentType : "application/x-www-form-urlencoded",
            queryParamsType : "undefined",
            toolbar: "#toolbar",
            columns: [{ checkbox: true},
                        {
                            field: 'articleBasicId',
                            title: '博客文章自增长ID',
                            width:'10',
                            align: 'center',
                            formatter:function(value,row,index) {
                                var url = "${managerPath}/mblog/article/form.do?articleBasicId="+row.articleBasicId;
                                return "<a href=" +url+ " target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target='_self'>" + value + "</a>";
                            }
                        },{
                            field: 'basicTitle',
                            title: '文章标题',
                            width:'65'

                        },{
                            field: 'articleContent',
                            title: '文章内容',
                            width:'65,535',
                            formatter:function(value,row,index) {
                                var url = "${managerPath}/mblog/article/form.do?articleContent="+row.articleContent;
                                return "<a href=" +url+ " target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target='_self'>" + value + "</a>";
                            }
                        }]
        })
    })
    //增加按钮
    $("#addArticleBtn").click(function(){
        location.href ="${managerPath}/mblog/article/form.do"; 
    })
    //删除按钮
    $("#delArticleBtn").click(function(){
        //获取checkbox选中的数据
        var rows = $("#articleList").bootstrapTable("getSelections");
        //没有选中checkbox
        if(rows.length <= 0){
            <@ms.notify msg="请选择需要删除的记录" type="warning"/>
        }else{
            $(".delArticle").modal();
        }
    })

    $("#deleteArticleBtn").click(function(){
        var rows = $("#articleList").bootstrapTable("getSelections");
        $(this).text("正在删除...");
        $(this).attr("disabled","true");
        $.ajax({
            type: "post",
            url: "${managerPath}/mblog/article/delete.do",
            data: JSON.stringify(rows),
            dataType: "json",
            contentType: "application/json",
            success:function(msg) {
                if(msg.result == true) {
                    <@ms.notify msg= "删除成功" type= "success" />
                }else {
                    <@ms.notify msg= "删除失败" type= "fail" />
                }
                location.reload();
            }
        })
    });
    //查询功能
    function search(){
        var search = $("form[name='searchForm']").serializeJSON();
        var params = $('#articleList').bootstrapTable('getOptions');
        params.queryParams = function(params) {  
            $.extend(params,search);
            return params;  
           }  
            $("#articleList").bootstrapTable('refresh', {query:$("form[name='searchForm']").serializeJSON()});
    }
</script>
           

form.ftl

<@ms.html5>
     <@ms.nav title="暂无描述编辑" back=true>
        <@ms.saveButton  onclick="save()"/>
    </@ms.nav>
    <@ms.panel>
        <@ms.form name="articleForm" isvalidation=true>
            <@ms.hidden name="basicId" value="${articleEntity.articleBasicId?default('0')}"/>
            <@ms.text name="basicTitle" colSm="2" width="400" label="文章标题"    title="文章标题" size="5"  placeholder="请输入文章标题"  value="${articleEntity.basicTitle?default('')}"  validation={"maxlength":"300","required":"true", "data-bv-notempty-message":"文章标题不能为空","data-bv-stringlength-message":"标题在300个字符以内!"}/>
        <@ms.text name="basicSort"  colSm="2" width="200" label="自定义顺序" title="自定义顺序" size="5"  placeholder="请输入文章顺序" value="${articleEntity.basicSort?c?default(0)}" validation={"data-bv-between":"true","data-bv-between-message":"自定义顺序必须大于0","data-bv-between-min":"0", "data-bv-between-max":"99999999","data-bv-notempty-message":"自定义顺序不能为空"}/>
        <@ms.textarea colSm="2" name="basicDescription" label="描述" wrap="Soft" rows="4"  size=""  value="${articleEntity.basicDescription?default('')}" placeholder="请输入对该文章的简短描述,以便用户查看文章简略"/>
            <@ms.textarea colSm="2" name="articleContent" label="文章内容"  wrap="Soft" rows="4"  size=""   value="${articleEntity.articleContent?default('')}"  />        
        </@ms.form>
    </@ms.panel>
</@ms.html5>
<script>
    var url = "${managerPath}/mblog/article/save.do";
    if($("input[name = 'basicId']").val() > 0){
        url = "${managerPath}/mblog/article/update.do";
        $(".btn-success").text("更新");
    }
    //编辑按钮onclick
    function save() {
        $("#articleForm").data("bootstrapValidator").validate();
            var isValid = $("#articleForm").data("bootstrapValidator").isValid();
            if(!isValid) {
                <@ms.notify msg= "数据提交失败,请检查数据格式!" type= "warning" />
                return;
        }
        var btnWord =$(".btn-success").text();
        $(".btn-success").text(btnWord+"中...");
        $(".btn-success").prop("disabled",true);
        $.ajax({
            type:"post",
            dataType:"json",
            data:$("form[name = 'articleForm']").serialize(),
            url:url,
            success: function(status) {
                if(status.result == true) { 
                    <@ms.notify msg="保存或更新成功" type= "success" />
                    location.href = "${managerPath}/mblog/article/index.do";
                }
                else{
                    <@ms.notify msg= "保存或更新失败!" type= "fail" />
                    location.href= "${managerPath}/mblog/article/index.do";
                }
            }
        })
    }    
</script>
           

底层代码重写

主要分视图代码重写、Java业务代码重写

  • 视图代码重写只需要在当前开发项目中创建与底层视图文件路径、文件名一致的文件即可,例如:重写登录界面,只需要在当前项目创建/WEB-INF/manager/login.ftl文件,当项目发布的时候当前的login.ftl会覆盖底层提供的login.ftl;
  • 后台业务代码的重写不像视图那样简单,需要在当前项目创建对应的类,如果类名出现相同,必须使用Spring注解定义bean名称,例如:@Controller("xxxx") @Service("xxxxxx")

方式使用小技巧

获取和填充session

我们在使用后台时,经常或碰到使用session中的数据,比如当前的管理员、当前的用户、当前的模块.....

这些功能我们都提供了相应的方法。但是使用时,需要继承相应模块。比如使用用户时,需要继承:net.mingsoft.people.action.BaseAction

  • 用户的填充和获取
    • 填充:this.setPeopleBySession(request, people); people是用户实体。
    • 获取:this.getPeopleBySession(); 返回的是当前用户实体。只能在用户已经登录的情况下获取。
  • 管理员的获取
    • this.getManagerBySession(request); 返回的是管理员实体。只能在管理员登录后台后使用。
  • 模块的获取
    • this.getCategoryModelCode(request); 返回管理员当前的模块。
  • 方法还有很多,可以参照铭飞后台API文档;

保存方法的妙用

  • 获取主键自增长编号
    • 我们在保存一条数据之后,有可能需要当前保存的实体自动增长的ID。这个时候就需要再使用保存的实体,再到数据库中查询一次。
    • 我们考虑到了这里的复用性,所以我们在实体保存之后,会在当前实体中保存他数据库中保存的ID。所以说,我们在返回的实体中,是已经包含了自增长主键的实体。
  • 保存自己的时候,同时保存父类。
    • 有时,我们在保存当前实体时,需要先保存父类实体。一般的情况下,我们要调用两次方法。第一次保存父类,然后获取父类的ID,用来组织子类的数据。
    • 我们考虑到了这里的通用性,所以我们可以在子类中调用父类的保存方法,已达到同时保存两张表的数据的同时,将父类的主键ID也传入子类的数据结构中。具体的实现方式可以参照快速开发步骤中的保存方法。