学成在线笔记三:CMS管理页面开发

注意:

我是用的element-ui的版本位:2.10.1,若要使用本博客中的前端代码,建议修改为相同版本。

修改方式:修改根目录下的package.jsondependencies中的element-ui的版本号为:2.10.1 即可

自定义条件查询

需求分析

页面自定条件包含:

  • 站点ID:精确匹配
  • 模板ID:精确匹配
  • 页面别名:模糊匹配

服务端开发

CmsPageService

修改findList方法

public QueryResponseResult findList(int page, int size, QueryPageRequest queryPageRequest) {
        // 页面别名模糊查询
        ExampleMatcher pageAliaseMatcher = ExampleMatcher.matching().withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains());
        
        CmsPage params = new CmsPage();
        // 站点ID
        if (StringUtils.isNotBlank(queryPageRequest.getSiteId())) {
            params.setSiteId(queryPageRequest.getSiteId());
        }
    	// 页面别名
        params.setPageAliase(queryPageRequest.getPageAliase());

        // 构建查询条件
        Example<CmsPage> cmsPageExample = Example.of(params, pageAliaseMatcher);

        if (page <= 0) {
            page = 1;
        }
        // 页码从0开始
        page = page - 1;
        // 查询
        Page<CmsPage> pageResult = cmsPageRepository.findAll(cmsPageExample, PageRequest.of(page, size));
        QueryResult<CmsPage> cmsPageQueryResult = new QueryResult<>();
        cmsPageQueryResult.setList(pageResult.getContent());
        cmsPageQueryResult.setTotal(pageResult.getTotalElements());

        return new QueryResponseResult(CommonCode.SUCCESS, cmsPageQueryResult);
    }

CmsSiteControllerApi

由于前端页面需要按站点ID查询,所以前端需要展示站点的下拉选择,需要新增API

xc-service-api/cms中新增CmsSiteControllerApi

package com.xuecheng.api.cms;

import com.xuecheng.framework.model.response.QueryResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "CMS站点管理接口", description = "CMS页面站点管理接口,提供站点的增删改查")
public interface CmsSiteControllerApi {

    @ApiOperation("查询所有站点信息")
    QueryResponseResult findAll();

}

CmsSiteController

xc-service-manage-cms中新增Controller

package com.xuecheng.manage_cms.controller;

import com.xuecheng.api.cms.CmsSiteControllerApi;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.manage_cms.service.CmsSiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("cms/site")
public class CmsSiteController implements CmsSiteControllerApi {

    @Autowired
    private CmsSiteService cmsSiteService;

    @Override
    @GetMapping
    public QueryResponseResult findAll() {
        return cmsSiteService.findAll();
    }

}

CmsSiteService

package com.xuecheng.manage_cms.service;

import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_cms.dao.CmsSiteRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CmsSiteService {

    @Autowired
    private CmsSiteRepository cmsSiteRepository;

    public QueryResponseResult findAll() {
        List<CmsSite> cmsSiteList = cmsSiteRepository.findAll();
        QueryResult<CmsSite> queryResult = new QueryResult<>(cmsSiteList, cmsSiteList.size());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

}

CmsSiteRepository

package com.xuecheng.manage_cms.dao;

import com.xuecheng.framework.domain.cms.CmsSite;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface CmsSiteRepository extends MongoRepository<CmsSite, String> {
}

前端开发

页面修改

修改src/module/cms/page/page_list.vue中的内容,主要为:

  • 新增data绑定的数据
  • 新增查询站点列表的方法
  • 新增用于录入查询条件的输入框和下拉选择框
  1. template中的查询按钮之前添加如下代码

    	<!-- 站点ID下拉选择 -->
        <el-select v-model="params.siteId" placeholder="请选择站点">
          <el-option
            v-for="item in cmsSiteList"
            :key="item.siteId"
            :label="item.siteName"
            :value="params.siteId">
          </el-option>
        </el-select>
        <!-- 页面别名输入框 -->
        <span style="margin-left: 10px;">页面别名:</span>  
        <el-input v-model="params.pageAliase" placeholder="" style="width: 200px"></el-input>
    
  2. 修改script中的代码如下

    <script>
        import * as cmsApi from '../api/cms'
        export default {
          data() {
            return {
              tableData: [],
              cmsSiteList: [],
              total: 50,
              params: {
                  page: 1,
                  size: 20,
                  siteId: '',
                  pageAliase:''
              }
            }
          },
          methods: {
            // cmsPage分页查询
            changePage:function() {
                this.query()
            },
            // 分页查询CmsPage
            query:function() {
                // 分页查询CMS页面
                console.log("当前页码:" + this.params.page + ", 当前记录数:" + this.params.size);
                cmsApi.page_list(this.params.page, this.params.size, this.params).then(res => {
                    // 获取数据
                    this.total = res.queryResult.total
                    this.tableData = res.queryResult.list
                })
            },
            // 查询所有站点cmsSite
            cmsSiteQueryAll:function() {
                cmsApi.site_list_all().then(res => {
                  this.cmsSiteList = res.queryResult.list
                })
            }
          },
          mounted() {
              this.query()
              // 查询站点数据
              this.cmsSiteQueryAll()
          }
        }
      </script>
    

修改API

修改src/module/cms/api/cms.js

import http from './../../../base/api/public'
import querystring from 'querystring'
let sysConfig = require('@/../config/sysConfig')
let apiUrl = sysConfig.xcApiUrlPre;
/**
 * 分页查询CMS页面
 * 
 * @param {*} page 当前页
 * @param {*} size 每页记录数
 * @param {*} params 其他参数:页面别名、站点ID、页面ID等
 */
export const page_list = (page,size,params) => { 
    let queryParams = querystring.stringify(params)
    return http.requestQuickGet(apiUrl + '/cms/page/list/'+page+'/'+size + '?' + queryParams) 
}

/**
 * 查询所有站点信息
 */
export const site_list_all = () => { 
    return http.requestQuickGet(apiUrl + '/cms/site') 
}

测试

完成想要的效果。

异常处理

异常处理流程

系统对异常的处理使用统一的异常处理流程:

  1. 自定义异常类型。
  2. 自定义错误代码及错误信息。
  3. 对于可预知的异常由程序员在代码中主动抛出,由SpringMVC统一捕获。可预知异常是程序员在代码中手动抛出本系统定义的特定异常类型,由于是程序员抛出的异常,通常异常信息比较齐全,程序员在抛出时会指定错误代码及错误信息,获取异常信息也比较方便。
  4. 对于不可预知的异常(运行时异常)由SpringMVC统一捕获Exception类型的异常。不可预知异常通常是由于系统出现bug、或一些不要抗拒的错误(比如网络中断、服务器宕机等),异常类型为RuntimeException类型(运行时异常)。
  5. 可预知的异常及不可预知的运行时异常最终会采用统一的信息格式(错误代码+错误信息)来表示,最终也会随请求响应给客户端。

学成在线笔记三:CMS管理页面开发_第1张图片

  • 在controller、service、dao中程序员抛出自定义异常;springMVC框架抛出框架异常类型。
  • 统一由异常捕获类捕获异常,并进行处理。
  • 捕获到自定义异常则直接取出错误代码及错误信息,响应给用户。
  • 捕获到非自定义异常类型首先从Map中找该异常类型是否对应具体的错误代码,如果有则取出错误代码和错误信息并响应给用户,如果从Map中找不到异常类型所对应的错误代码则统一为99999错误代码并响应给用户。
  • 将错误代码及错误信息以Json格式响应给用户。

可预知异常处理

自定义异常类

package com.xuecheng.framework.exception;

import com.xuecheng.framework.model.response.ResultCode;
import lombok.Getter;

/**
 * 自定义异常类
 */
@Getter
public class CustomerException extends RuntimeException {

    private ResultCode resultCode;

    public CustomerException(ResultCode resultCode) {
        this.resultCode = resultCode;
    }

}

异常抛出工具类

package com.xuecheng.framework.exception;

import com.xuecheng.framework.model.response.ResultCode;

/**
 * 自定义异常抛出类
 */
public class ExceptionCast {

    public static void cast(ResultCode resultCode) {
        throw new CustomerException(resultCode);
    }

}

统一异常处理类

package com.xuecheng.framework.exception;

import com.xuecheng.framework.model.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理类
 */
@Slf4j
@ControllerAdvice
public class ExceptionCatch {


    /**
     * 自定义异常类型处理
     *
     * @param e CustomerException
     */
    @ResponseBody
    @ExceptionHandler(CustomerException.class)
    public ResponseResult customerException(CustomerException e) {
        log.error("发生异常, 异常信息:{}", e.getMessage());
        return new ResponseResult(e.getResultCode());
    }

}

不可预知异常处理

统一异常处理

ExceptionCatch中新增方法,用于捕获不可预知异常

    /**
     * 已知异常种类列表
     */
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> OPTIONS;

    private static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();

    static {
        OPTIONS = builder
                .put(HttpMessageNotReadableException.class, CommonCode.PARAMS_ERROR)
                .build();
    }
	
	/**
     * 全局异常类型处理
     *
     * @param e Exception
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Throwable e) {
        log.error("发生异常, 异常信息:{}", e.getMessage());
        if (OPTIONS.containsKey(e.getClass())) {// 该异常为已知异常类型
            return new ResponseResult(OPTIONS.get(e.getClass()));
        }
        return new ResponseResult(CommonCode.SERVER_ERROR);
    }

CMS页面管理开发

增删改查全部完成后的代码如下:

后端

CmsPageService

package com.xuecheng.manage_cms.service;

import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.domain.cms.response.CmsCode;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_cms.dao.CmsPageRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Slf4j
@Service
public class CmsPageService {

    @Autowired
    private CmsPageRepository cmsPageRepository;

    /**
     * 分页查询页面列表
     *
     * @param page 当前页码
     * @param size 每页记录数
     * @param queryPageRequest 查询条件
     */
    public QueryResponseResult findList(int page, int size, QueryPageRequest queryPageRequest) {
        // 页面别名模糊查询
        ExampleMatcher pageAliaseMatcher = ExampleMatcher.matching().withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains());

        CmsPage params = new CmsPage();
        // 站点ID
        if (StringUtils.isNotBlank(queryPageRequest.getSiteId())) {
            params.setSiteId(queryPageRequest.getSiteId());
        }
        // 页面别名
        params.setPageAliase(queryPageRequest.getPageAliase());

        // 构建查询条件
        Example<CmsPage> cmsPageExample = Example.of(params, pageAliaseMatcher);

        if (page <= 0) {
            page = 1;
        }
        // 页码从0开始
        page = page - 1;
        // 查询
        Page<CmsPage> pageResult = cmsPageRepository.findAll(cmsPageExample, PageRequest.of(page, size));
        QueryResult<CmsPage> cmsPageQueryResult = new QueryResult<>();
        cmsPageQueryResult.setList(pageResult.getContent());
        cmsPageQueryResult.setTotal(pageResult.getTotalElements());

        return new QueryResponseResult(CommonCode.SUCCESS, cmsPageQueryResult);
    }

    /**
     * 新增页面
     *
     * @param cmsPage 页面
     */
    public CmsPage add(CmsPage cmsPage) {
        return cmsPageRepository.insert(cmsPage);
    }

    /**
     * 按ID查询页面
     *
     * @param pageId 页面ID
     */
    public CmsPage findByPageId(String pageId) {
        Optional<CmsPage> cmsPage = cmsPageRepository.findById(pageId);
        return cmsPage.orElse(null);
    }

    /**
     * 编辑页面
     *
     * @param cmsPage 页面ID
     */
    public CmsPage edit(CmsPage cmsPage) {
        // 查询
        if (cmsPage != null && StringUtils.isNotBlank(cmsPage.getPageId())) {
            Optional<CmsPage> optionalCmsPage = cmsPageRepository.findById(cmsPage.getPageId());
            if (optionalCmsPage.isPresent()) {
                CmsPage one = optionalCmsPage.get();
                // 执行更新
                one.setTemplateId(cmsPage.getTemplateId());
                one.setSiteId(cmsPage.getSiteId());
                one.setPageAliase(cmsPage.getPageAliase());
                one.setPageName(cmsPage.getPageName());
                one.setPageWebPath(cmsPage.getPageWebPath());
                one.setPagePhysicalPath(cmsPage.getPagePhysicalPath());
                // 保存
                return cmsPageRepository.save(one);
            }
        }

        return null;
    }

    /**
     * 删除指定ID的页面
     *
     * @param pageId 页面ID
     */
    public void deleteById(String pageId) {
        // 查询
        cmsPageRepository.deleteById(pageId);
    }
}

CmsPageController

package com.xuecheng.manage_cms.controller;

import com.xuecheng.api.cms.CmsPageControllerApi;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.domain.cms.response.CmsCode;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.manage_cms.service.CmsPageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("cms/page")
public class CmsPageController implements CmsPageControllerApi {

    @Autowired
    private CmsPageService cmsPageService;

    @Override
    @GetMapping("list/{page}/{size}")
    public QueryResponseResult findList(@PathVariable("page") int page,
                                        @PathVariable("size") int size,
                                        QueryPageRequest queryPageRequest) {
        return cmsPageService.findList(page, size, queryPageRequest);
    }

    @Override
    @PostMapping
    public CmsPageResult add(@RequestBody CmsPage cmsPage) {
        if (cmsPage == null) {
            ExceptionCast.cast(CommonCode.PARAMS_ERROR);
        }
        // 校验是否已存在
        CmsPage _cmsPage = cmsPageService.findBySiteIdAndPageNameAndPageWebPath(cmsPage.getSiteId(), cmsPage.getPageName(), cmsPage.getPageWebPath());
        if (_cmsPage != null) {
            ExceptionCast.cast(CmsCode.CMS_ADDPAGE_EXISTSNAME);
        }
        return new CmsPageResult(CommonCode.SUCCESS, cmsPageService.add(cmsPage));
    }

    @Override
    @GetMapping("/{pageId}")
    public CmsPageResult getCmsPage(@PathVariable("pageId") String pageId) {
        CmsPage cmsPage = cmsPageService.findByPageId(pageId);
        if (cmsPage == null) {
            ExceptionCast.cast(CmsCode.CMS_EDITPAGE_NOTEXISTS);
        }
        return new CmsPageResult(CommonCode.SUCCESS, cmsPage);
    }

    @Override
    @DeleteMapping("/{pageId}")
    public CmsPageResult deleteById(@PathVariable("pageId") String pageId) {
        if (StringUtils.isBlank(pageId)) {
            ExceptionCast.cast(CommonCode.PARAMS_ERROR);
        }
        cmsPageService.deleteById(pageId);
        return new CmsPageResult(CommonCode.SUCCESS, null);
    }

    @Override
    @PutMapping
    public CmsPageResult edit(@RequestBody CmsPage cmsPage) {
        if (cmsPage == null) {
            ExceptionCast.cast(CommonCode.PARAMS_ERROR);
        }
        CmsPage edit = cmsPageService.edit(cmsPage);
        if (edit == null) {
            ExceptionCast.cast(CommonCode.FAIL);
        }
        return new CmsPageResult(CommonCode.SUCCESS, edit);
    }


}

CmsPageControllerApi

package com.xuecheng.api.cms;

import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value = "CMS页面管理接口", description = "CMS页面管理接口,提供页面的增删改查")
public interface CmsPageControllerApi {

    @ApiOperation("分页查询页面列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, paramType = "path"),
            @ApiImplicitParam(name = "size", value = "每页记录数", required = true, paramType = "path")
    })
    QueryResponseResult findList(int page, int size, QueryPageRequest queryPageRequest);

    @ApiOperation("新增页面")
    CmsPageResult add(CmsPage cmsPage);

    @ApiOperation("修改页面")
    CmsPageResult edit(CmsPage cmsPage);

    @ApiOperation("按ID获取页面")
    CmsPageResult getCmsPage(String pageId);

    @ApiOperation("按ID删除页面")
    CmsPageResult deleteById(String pageId);

}

前端

page_list.vue

  

  

page_add.vue

  

  

page_edit.vue

  

  

定义路由

修改src/module/cms/router/index.js

import Home from '@/module/home/page/home.vue'
import page_list from '@/module/cms/page/page_list.vue'
import page_add from '@/module/cms/page/page_add.vue'
import page_edit from '@/module/cms/page/page_edit.vue'

export default [{ 
  path: '/cms', 
  component: Home, 
  name: 'CMS内容管理', 
  hidden: false, 
  children:[{
    path:'/cms/page/list',
    name:'页面列表',
    component: page_list,
    hidden:false
  },{
    path:'/cms/page/add',
    name:'页面新增',
    component: page_add,
    hidden:true
  },{
    path:'/cms/page/edit',
    name:'页面修改',
    component: page_edit,
    hidden:true
  }]
}]

定义API

src/module/cms/api/cms.js中新增API定义

/**
 * 新增页面
 */
export const add = (params) => { 
    return http.requestPost(apiUrl + '/cms/page', params)
}

/**
 * 修改页面
 */
export const edit = (params) => { 
    return http.requestPut(apiUrl + '/cms/page', params)
}

/**
 * 按ID查询页面
 */
export const findCmsPageById = (pageId) => { 
    return http.requestQuickGet(apiUrl + '/cms/page/'+ pageId)
}

/**
 * 按ID删除页面
 */
export const deleteCmsPageById = (pageId) => { 
    return http.requestDelete(apiUrl + '/cms/page/'+ pageId)
}

CMS站点管理开发

增删改查全部完成后的代码如下:

后端

CmsSiteResult

新增返回实体类

package com.xuecheng.framework.domain.cms.response;

import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import lombok.Data;

@Data
public class CmsSiteResult extends ResponseResult {
    CmsSite cmsSite;
    public CmsSiteResult(ResultCode resultCode, CmsSite cmsSite) {
        super(resultCode);
        this.cmsSite = cmsSite;
    }
}

CmsSiteRepository

package com.xuecheng.manage_cms.dao;

import com.xuecheng.framework.domain.cms.CmsSite;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface CmsSiteRepository extends MongoRepository<CmsSite, String> {
}

CmsSiteService

package com.xuecheng.manage_cms.service;

import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_cms.dao.CmsSiteRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class CmsSiteService {

    @Autowired
    private CmsSiteRepository cmsSiteRepository;

    public QueryResponseResult findAll() {
        List<CmsSite> cmsSiteList = cmsSiteRepository.findAll();
        QueryResult<CmsSite> queryResult = new QueryResult<>(cmsSiteList, cmsSiteList.size());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    /**
     * 分页查询页面列表
     *
     * @param page 当前页码
     * @param size 每页记录数
     */
    public QueryResponseResult findList(int page, int size) {
        if (page <= 0) {
            page = 1;
        }
        // 页码从0开始
        page = page - 1;
        // 查询
        Page<CmsSite> siteResult = cmsSiteRepository.findAll(PageRequest.of(page, size));
        QueryResult<CmsSite> cmsSiteQueryResult = new QueryResult<>();
        cmsSiteQueryResult.setList(siteResult.getContent());
        cmsSiteQueryResult.setTotal(siteResult.getTotalElements());

        return new QueryResponseResult(CommonCode.SUCCESS, cmsSiteQueryResult);
    }

    /**
     * 新增站点
     *
     * @param cmsSite 站点
     */
    public CmsSite add(CmsSite cmsSite) {
        return cmsSiteRepository.insert(cmsSite);
    }

    /**
     * 按ID查询站点
     *
     * @param siteId 站点ID
     */
    public CmsSite findBySiteId(String siteId) {
        Optional<CmsSite> cmsSite = cmsSiteRepository.findById(siteId);
        return cmsSite.orElse(null);
    }

    /**
     * 编辑站点
     *
     * @param cmsSite 站点
     */
    public CmsSite edit(CmsSite cmsSite) {
        // 查询
        if (cmsSite != null && StringUtils.isNotBlank(cmsSite.getSiteId())) {
            Optional<CmsSite> optionalCmsSite = cmsSiteRepository.findById(cmsSite.getSiteId());
            if (optionalCmsSite.isPresent()) {
                CmsSite one = optionalCmsSite.get();
                // 执行更新
                one.setSiteCreateTime(cmsSite.getSiteCreateTime());
                one.setSiteDomain(cmsSite.getSiteDomain());
                one.setSiteName(cmsSite.getSiteName());
                one.setSitePort(cmsSite.getSitePort());
                one.setSiteWebPath(cmsSite.getSiteWebPath());
                // 保存
                return cmsSiteRepository.save(one);
            }
        }

        return null;
    }

    /**
     * 删除指定ID的站点
     *
     * @param siteId 站点ID
     */
    public void deleteById(String siteId) {
        // 查询
        cmsSiteRepository.deleteById(siteId);
    }
}

CmsSiteController

package com.xuecheng.manage_cms.controller;

import com.xuecheng.api.cms.CmsSiteControllerApi;
import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.framework.domain.cms.response.CmsSiteResult;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.manage_cms.service.CmsSiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("cms/site")
public class CmsSiteController implements CmsSiteControllerApi {

    @Autowired
    private CmsSiteService cmsSiteService;

    @Override
    @GetMapping
    public QueryResponseResult findAll() {
        return cmsSiteService.findAll();
    }

    @Override
    @GetMapping("list/{page}/{size}")
    public QueryResponseResult findList(@PathVariable("page") int page,
                                        @PathVariable("size") int size) {
        return cmsSiteService.findList(page, size);
    }

    @Override
    @PostMapping
    public CmsSiteResult add(@RequestBody CmsSite cmsSite) {
        return new CmsSiteResult(CommonCode.SUCCESS, cmsSiteService.add(cmsSite));
    }

    @Override
    @GetMapping("/{siteId}")
    public CmsSiteResult getCmsSite(@PathVariable("siteId") String siteId) {
        CmsSite cmsSite = cmsSiteService.findBySiteId(siteId);
        if (cmsSite == null) {
            return new CmsSiteResult(CommonCode.FAIL, null);
        }
        return new CmsSiteResult(CommonCode.SUCCESS, cmsSite);
    }

    @Override
    @DeleteMapping("/{siteId}")
    public CmsSiteResult deleteById(@PathVariable("siteId") String siteId) {
        try {
            cmsSiteService.deleteById(siteId);
        } catch (Exception e) {
            return new CmsSiteResult(CommonCode.FAIL, null);
        }
        return new CmsSiteResult(CommonCode.SUCCESS, null);
    }

    @Override
    @PutMapping
    public CmsSiteResult edit(@RequestBody CmsSite cmsSite) {
        CmsSite edit = cmsSiteService.edit(cmsSite);
        if (edit != null) {
            return new CmsSiteResult(CommonCode.SUCCESS, edit);
        }
        return new CmsSiteResult(CommonCode.FAIL, null);
    }


}

CmsSiteControllerApi

package com.xuecheng.api.cms;

import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.domain.cms.response.CmsSiteResult;
import com.xuecheng.framework.model.response.QueryResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value = "CMS站点管理接口", description = "CMS页面站点管理接口,提供站点的增删改查")
public interface CmsSiteControllerApi {


    @ApiOperation("查询所有站点信息")
    QueryResponseResult findAll();

    @ApiOperation("分页查询站点列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, paramType = "path"),
            @ApiImplicitParam(name = "size", value = "每页记录数", required = true, paramType = "path")
    })
    QueryResponseResult findList(int page, int size);

    @ApiOperation("新增站点")
    CmsSiteResult add(CmsSite cmsSite);

    @ApiOperation("修改站点")
    CmsSiteResult edit(CmsSite cmsSite);

    @ApiOperation("按ID获取站点")
    CmsSiteResult getCmsSite(String siteId);

    @ApiOperation("按ID删除站点")
    CmsSiteResult deleteById(String siteId);

}

前端

site_list.vue

  

  

site_add.vue

  

  

site_edit.vue

  

  

定义路由

修改src/module/cms/router/index.js

import Home from '@/module/home/page/home.vue'
import page_list from '@/module/cms/page/page_list.vue'
import page_add from '@/module/cms/page/page_add.vue'
import page_edit from '@/module/cms/page/page_edit.vue'
import site_list from '@/module/cms/page/site_list.vue'
import site_add from '@/module/cms/page/site_add.vue'
import site_edit from '@/module/cms/page/site_edit.vue'

export default [{ 
  path: '/cms', 
  component: Home, 
  name: 'CMS内容管理', 
  hidden: false, 
  children:[{
    path:'/cms/page/list',
    name:'页面列表',
    component: page_list,
    hidden:false
  },{
    path:'/cms/page/add',
    name:'页面新增',
    component: page_add,
    hidden:true
  },{
    path:'/cms/page/edit',
    name:'页面修改',
    component: page_edit,
    hidden:true
  },{
    path:'/cms/site/list',
    name:'站点列表',
    component: site_list,
    hidden:false
  },{
    path:'/cms/site/add',
    name:'站点新增',
    component: site_add,
    hidden:true
  },{
    path:'/cms/site/edit',
    name:'站点修改',
    component: site_edit,
    hidden:true
  }]
}]

定义API

src/module/cms/api/cms.js中新增API定义

/********************************************
 * CMS站点相关API
 ********************************************/
/**
 * 分页查询CMS站点
 */ 
export const site_list = (page,size) => {
    return http.requestQuickGet(apiUrl + '/cms/site/list/'+page+'/'+size) 
}

/**
 * 查询所有站点信息
 */
export const site_list_all = () => { 
    return http.requestQuickGet(apiUrl + '/cms/site') 
}

/**
 * 新增站点
 */
export const addCmsSite = (params) => { 
    return http.requestPost(apiUrl + '/cms/site', params)
}

/**
 * 修改站点
 */
export const editCmsSite = (params) => { 
    return http.requestPut(apiUrl + '/cms/site', params)
}

/**
 * 按ID查询站点
 */
export const findCmsSiteById = (pageId) => { 
    return http.requestQuickGet(apiUrl + '/cms/site/'+ pageId)
}

/**
 * 按ID删除站点
 */
export const deleteCmsSiteById = (pageId) => { 
    return http.requestDelete(apiUrl + '/cms/site/'+ pageId)
}

CMS模板管理开发

增删改查全部完成后的代码如下:

后端

CmsTemplateResult

新增返回shitilei

package com.xuecheng.framework.domain.cms.response;

import com.xuecheng.framework.domain.cms.CmsTemplate;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import lombok.Data;

@Data
public class CmsTemplateResult extends ResponseResult {
    CmsTemplate cmsTemplate;
    public CmsTemplateResult(ResultCode resultCode, CmsTemplate cmsTemplate) {
        super(resultCode);
        this.cmsTemplate = cmsTemplate;
    }
}

CmsTemplateRepository

package com.xuecheng.manage_cms.dao;

import com.xuecheng.framework.domain.cms.CmsTemplate;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface CmsTemplateRepository extends MongoRepository<CmsTemplate, String> {
}

CmsTemplateService

package com.xuecheng.manage_cms.service;

import com.xuecheng.framework.domain.cms.CmsTemplate;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_cms.dao.CmsTemplateRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class CmsTemplateService {

    @Autowired
    private CmsTemplateRepository cmsTemplateRepository;

    public QueryResponseResult findAll() {
        List<CmsTemplate> cmsTemplateList = cmsTemplateRepository.findAll();
        QueryResult<CmsTemplate> queryResult = new QueryResult<>(cmsTemplateList, cmsTemplateList.size());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    /**
     * 分页查询页面列表
     *
     * @param page 当前页码
     * @param size 每页记录数
     */
    public QueryResponseResult findList(int page, int size) {
        if (page <= 0) {
            page = 1;
        }
        // 页码从0开始
        page = page - 1;
        // 查询
        Page<CmsTemplate> templateResult = cmsTemplateRepository.findAll(PageRequest.of(page, size));
        QueryResult<CmsTemplate> templateQueryResult = new QueryResult<>();
        templateQueryResult.setList(templateResult.getContent());
        templateQueryResult.setTotal(templateResult.getTotalElements());

        return new QueryResponseResult(CommonCode.SUCCESS, templateQueryResult);
    }


    /**
     * 新增模板
     *
     * @param cmsTemplate 模板
     */
    public CmsTemplate add(CmsTemplate cmsTemplate) {
        return cmsTemplateRepository.insert(cmsTemplate);
    }

    /**
     * 按ID查询模板
     *
     * @param templateId 模板ID
     */
    public CmsTemplate findBySiteId(String templateId) {
        Optional<CmsTemplate> cmsTemplate = cmsTemplateRepository.findById(templateId);
        return cmsTemplate.orElse(null);
    }

    /**
     * 编辑模板
     *
     * @param cmsTemplate 模板
     */
    public CmsTemplate edit(CmsTemplate cmsTemplate) {
        // 查询
        if (cmsTemplate != null && StringUtils.isNotBlank(cmsTemplate.getTemplateId())) {
            Optional<CmsTemplate> optionalCmsTemplate = cmsTemplateRepository.findById(cmsTemplate.getTemplateId());
            if (optionalCmsTemplate.isPresent()) {
                CmsTemplate one = optionalCmsTemplate.get();
                // 执行更新
                one.setSiteId(cmsTemplate.getSiteId());
                one.setTemplateFileId(cmsTemplate.getTemplateFileId());
                one.setTemplateName(cmsTemplate.getTemplateName());
                one.setTemplateParameter(cmsTemplate.getTemplateParameter());
                // 保存
                return cmsTemplateRepository.save(one);
            }
        }

        return null;
    }

    /**
     * 删除指定ID的模板
     *
     * @param templateId 模板ID
     */
    public void deleteById(String templateId) {
        // 查询
        cmsTemplateRepository.deleteById(templateId);
    }
}

CmsTemplateController

package com.xuecheng.manage_cms.controller;

import com.xuecheng.api.cms.CmsTemplateControllerApi;
import com.xuecheng.framework.domain.cms.CmsTemplate;
import com.xuecheng.framework.domain.cms.response.CmsTemplateResult;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.manage_cms.service.CmsTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("cms/template")
public class CmsTemplateController implements CmsTemplateControllerApi {

    @Autowired
    private CmsTemplateService cmsTemplateService;

    @Override
    @GetMapping
    public QueryResponseResult findAll() {
        return cmsTemplateService.findAll();
    }

    @Override
    @GetMapping("list/{page}/{size}")
    public QueryResponseResult findList(@PathVariable("page") int page,
                                        @PathVariable("size") int size) {
        return cmsTemplateService.findList(page, size);
    }

    @Override
    @PostMapping
    public CmsTemplateResult add(@RequestBody CmsTemplate cmsTemplate) {
        return new CmsTemplateResult(CommonCode.SUCCESS, cmsTemplateService.add(cmsTemplate));
    }

    @Override
    @GetMapping("/{templateId}")
    public CmsTemplateResult getCmsTemplate(@PathVariable("templateId") String templateId) {
        CmsTemplate cmsTemplate = cmsTemplateService.findBySiteId(templateId);
        if (cmsTemplate == null) {
            return new CmsTemplateResult(CommonCode.FAIL, null);
        }
        return new CmsTemplateResult(CommonCode.SUCCESS, cmsTemplate);
    }

    @Override
    @DeleteMapping("/{templateId}")
    public CmsTemplateResult deleteById(@PathVariable("templateId") String templateId) {
        try {
            cmsTemplateService.deleteById(templateId);
        } catch (Exception e) {
            return new CmsTemplateResult(CommonCode.FAIL, null);
        }
        return new CmsTemplateResult(CommonCode.SUCCESS, null);
    }

    @Override
    @PutMapping
    public CmsTemplateResult edit(@RequestBody CmsTemplate cmsTemplate) {
        CmsTemplate edit = cmsTemplateService.edit(cmsTemplate);
        if (edit != null) {
            return new CmsTemplateResult(CommonCode.SUCCESS, edit);
        }
        return new CmsTemplateResult(CommonCode.FAIL, null);
    }

}

CmsTemplateControllerApi

package com.xuecheng.api.cms;

import com.xuecheng.framework.domain.cms.CmsTemplate;
import com.xuecheng.framework.domain.cms.response.CmsTemplateResult;
import com.xuecheng.framework.model.response.QueryResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value = "CMS模板管理接口", description = "CMS页面模板管理接口,提供模板的增删改查")
public interface CmsTemplateControllerApi {

    @ApiOperation("查询所有模板信息")
    QueryResponseResult findAll();

    @ApiOperation("分页查询模板列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, paramType = "path"),
            @ApiImplicitParam(name = "size", value = "每页记录数", required = true, paramType = "path")
    })
    QueryResponseResult findList(int page, int size);

    @ApiOperation("新增模板")
    CmsTemplateResult add(CmsTemplate cmsTemplate);

    @ApiOperation("修改模板")
    CmsTemplateResult edit(CmsTemplate cmsTemplate);

    @ApiOperation("按ID获取模板")
    CmsTemplateResult getCmsTemplate(String templateId);

    @ApiOperation("按ID删除模板")
    CmsTemplateResult deleteById(String templateId);

}

前端

template_list.vue

  

  

template_add.vue

  

  

template_edit.vue

  

  

定义路由

修改src/module/cms/router/index.js

import Home from '@/module/home/page/home.vue'
import page_list from '@/module/cms/page/page_list.vue'
import page_add from '@/module/cms/page/page_add.vue'
import page_edit from '@/module/cms/page/page_edit.vue'
import site_list from '@/module/cms/page/site_list.vue'
import site_add from '@/module/cms/page/site_add.vue'
import site_edit from '@/module/cms/page/site_edit.vue'
import template_list from '@/module/cms/page/template_list.vue'
import template_add from '@/module/cms/page/template_add.vue'
import template_edit from '@/module/cms/page/template_edit.vue'

export default [{ 
  path: '/cms', 
  component: Home, 
  name: 'CMS内容管理', 
  hidden: false, 
  children:[{
    path:'/cms/page/list',
    name:'页面列表',
    component: page_list,
    hidden:false
  },{
    path:'/cms/page/add',
    name:'页面新增',
    component: page_add,
    hidden:true
  },{
    path:'/cms/page/edit',
    name:'页面修改',
    component: page_edit,
    hidden:true
  },{
    path:'/cms/site/list',
    name:'站点列表',
    component: site_list,
    hidden:false
  },{
    path:'/cms/site/add',
    name:'站点新增',
    component: site_add,
    hidden:true
  },{
    path:'/cms/site/edit',
    name:'站点修改',
    component: site_edit,
    hidden:true
  },{
    path:'/cms/template/list',
    name:'模板列表',
    component: template_list,
    hidden:false
  },{
    path:'/cms/template/add',
    name:'模板新增',
    component: template_add,
    hidden:true
  },{
    path:'/cms/template/edit',
    name:'模板修改',
    component: template_edit,
    hidden:true
  }]
}]

定义API

src/module/cms/api/cms.js中新增API定义

/********************************************
 * CMS模板相关API
 ********************************************/
/**
 * 分页查询CMS模板
 */ 
export const template_list = (page,size) => {
    return http.requestQuickGet(apiUrl + '/cms/template/list/'+page+'/'+size) 
} 
/**
 * 查询所有模板信息
 */
export const template_list_all = () => { 
    return http.requestQuickGet(apiUrl + '/cms/template') 
}

/**
 * 新增模板
 */
export const addCmsTemplate = (params) => { 
    return http.requestPost(apiUrl + '/cms/template', params)
}

/**
 * 修改模板
 */
export const editCmsTemplate = (params) => { 
    return http.requestPut(apiUrl + '/cms/template', params)
}

/**
 * 按ID查询模板
 */
export const findCmsTemplateById = (pageId) => { 
    return http.requestQuickGet(apiUrl + '/cms/template/'+ pageId)
}

/**
 * 按ID删除模板
 */
export const deleteCmsTemplateById = (pageId) => { 
    return http.requestDelete(apiUrl + '/cms/template/'+ pageId)
}

以上内容全部由博主编写并测试通过

你可能感兴趣的:(学成在线)