微服务实战笔记-学成在线-day03

知识点

  1. vue中router的用法
  2. spring-data-mongodb的用法
  3. 服务端异常统一封装处理

vue中router的用法

vue中router 的作用就是从当前页面跳转到另外一个页面,类似于a标签,不同的是,它可以在跳转的时候传递一些参数。

router 跳转页面的方式
  1. 在router/index.js 中指定菜单地址,通过菜单跳转
    在router/index.js中配置
    // /cms/page/edit/:pageId' 通过路径传参路由的写法 类似于/findById/{id}
    export default [{
      path: '/cms',
      component: Home,
      name: 'CMS',
      hidden: false,
      children: [
        {path: '/cms/page/list', component: page_list, name: '页面列表', hidden: false},
        {path: '/cms/page/add', component: page_add, name: '新增页面', hidden: true}, 
        {path: '/cms/page/edit/:pageId', component: page_edit, name: '编辑页面', hidden: true}
      ]
    }
    ]
    // 使用参数代码 通过this.$route.params 获取到传递的参数对象
    this.$route.params.传递的属性
      let pageId = this.$route.params.pageId;
    

2. 通过router-link跳转

```html
		 <!-- router-link类似于a标签-->
        <router-link :to="{path:'/cms/page/add/',query:this.params}">
          <el-button type="primary" size="small">新增页面</el-button>
        </router-link>
  1. 点击按钮跳转(手动跳转)
	this.$router.push({
	path:'需要跳转的地址',
	query:'附带的参数,这些参数会拼接在地址后面,?A=1&B=2'
	})
	//样例
 	this.$router.push({
      path:'/cms/page/edit/'+pageId,
      query:this.params
    });
router 传递参数的方式:
  1. 直接拼接到地址的后面,
	// 传参代码
	// 使用router 中的query传参 会直接拼到地址栏的后面
	this.$router.push({
	path:'需要跳转的地址',
	query:'附带的参数,这些参数会拼接在地址后面,?A=1&B=2'
	})

	// 使用参数代码 通过this.$route.query获取到传递的参数对象
	// this.$route.query.传递的属性
	this.$route.query.page
  1. 使用地址传参 ,类似于spring中的@GetMapping("/findById/{id}"),www.xxx.com/cms/page/findById/123
	// /cms/page/edit/:pageId' 通过路径传参路由的写法 类似于/findById/{id}
	export default [{
	  path: '/cms',
	  component: Home,
	  name: 'CMS',
	  hidden: false,
	  children: [
	    {path: '/cms/page/list', component: page_list, name: '页面列表', hidden: false},
	    {path: '/cms/page/add', component: page_add, name: '新增页面', hidden: true}, 
	    // 注意这个的写法和其它的不一样 
	    {path: '/cms/page/edit/:pageId', component: page_edit, name: '编辑页面', hidden: true}
	  ]
	}
	]
	// 使用参数代码 通过this.$route.params 获取到传递的参数对象
	// this.$route.params.传递的属性
	let pageId = this.$route.params.pageId;

spring-data-mongodb的用法

  1. 业务的dao需要继承MongoRepository

@Repository
public interface CmsPageRepository extends MongoRepository<CmsPage, String> {

    /**
     * 根据站点id 页面名称 webPath询
     * @param siteId
     * @return
     */
    CmsPage findByPageNameAndSiteIdAndPageWebPath(String pageName,String siteId,String
            pageWebPath);


}
  1. 针对与不同维护的查询可以通过方法名去定义,不用去写实现,类似上面的findByPageNameAndSiteIdAndPageWebPath方法
  2. 查询,sping-data-mongodb的查询与sql有点不一样,先上一段样例
		CmsPage cmsPage = new CmsPage();
        if (StringUtils.isNoneEmpty(queryPageRequest.getPageAliase())) {
            cmsPage.setPageAliase(queryPageRequest.getPageAliase());
        }
        if (StringUtils.isNoneEmpty(queryPageRequest.getSiteId())) {
            cmsPage.setSiteId(queryPageRequest.getSiteId());
        }
        if (StringUtils.isNoneEmpty(queryPageRequest.getTemplateId())) {
            cmsPage.setTemplateId(queryPageRequest.getTemplateId());
        }
        // 条件匹配器 如果没有使用条件匹配器指定匹配类型,那么默认使用精确匹配(全匹配)
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<CmsPage> example = Example.of(cmsPage, exampleMatcher);
        Pageable pageable = PageRequest.of(page, size);
        Page<CmsPage> all = cmsPageRepository.findAll(example, pageable);

它的查询条件匹配类型需要使用ExampleMatcher去指定而不是直接写sql

  1. 返回类型Optional,Optional类型可以避免NullPointException
    public CmsPageResult findById(String id) {
        Optional<CmsPage> optional = cmsPageRepository.findById(id);
        if (optional.isPresent()) {
        	// 如果返回值为空的话直接抛出异常
            ExceptionCast.cast(CmsCode.CMS_PAGE_NOT_EXIST);
        }
        return new CmsPageResult(CommonCode.SUCCESS, optional.get());
    }

服务端异常统一封装处理

在这里插入图片描述

服务端异常统一封装需要借助spring框架提供的使用 @ControllerAdvice和@ExceptionHandler注解来捕获指定类型的异常
CustomException.java

package com.xuecheng.framework.exception;

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

/**
 * 封装可以被预知到的异常
 */
public class CustomException extends RuntimeException {

    private ResultCode resultCode;

    public CustomException(ResultCode resultCode){
        //异常信息为错误代码+异常信息
        super("错误代码:"+resultCode.code()+"错误信息:"+resultCode.message());
        this.resultCode = resultCode;
    }

    public ResultCode getResultCode(){
        return this.resultCode;
    }
}

ExceptionCast .java

package com.xuecheng.framework.exception;

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


/**
 * 封装抛出异常的过程
 */
public class ExceptionCast {

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

ExceptionCatch .java

package com.xuecheng.framework.exception;

import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionCatch {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);

    /**
     * ImmutableMap 为谷歌封装的一个map  使用这个map必须通过ImmutableMap.Builder去构建
     * 这个map是线程安全的map,它的优点是一旦经过构建,就不允许修改
     */
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;

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

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customException(CustomException exception) {
        LOGGER.error(exception.getMessage());
        return new ResponseResult(exception.getResultCode());
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception) {
        LOGGER.error(exception.getMessage());
        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();
        }
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (resultCode == null) {
            resultCode = CommonCode.SERVER_ERROR;
        }
        return new ResponseResult(resultCode);
    }

    static {
        builder.put(HttpMessageNotReadableException.class,CommonCode.INVALID_PARAM);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值