后端开发得到的一些小技巧和方法

25 篇文章 0 订阅
21 篇文章 0 订阅
(1)通过使用request中的getAttribute属性获取绝对的url
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String url = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
// 这里的url的值为 : /user/{id}/score/{sid}

// 与 request.getRequestURI();   URI: /user/1/score/2
// 和request.getRequestURL().toString();   URL: http://localhost:8180/user/1/score/2

(2)aop 使用Around操作时,对于异常处理有两种方法
如果不对其进行其他操作可以直接在方法名后面抛出异常()throw throwable{};
如果相对其进行其他操作,比如记录错误日志等等,可以使用try catch,catch最后使用throw new RuntimeException(throwable)进行异常抛出;

推荐使用下方
   @Around("definePointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        try {
            Object ret = proceedingJoinPoint.proceed();
            logger.info("获取的返回值为: " + JSONObject.toJSONString(ret));
            return ret;
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
      }
(3)
在某些不能直接访问数据库的场景或者 需要获取bean的场景
比如使用mybatis的拦截器,则获取用户的信息,不能直接通过controller->service->dao进行查询
因为经过了dao层,


但是可以在此处 直接通过注解
@Resource
ApplicationContext applicationContext;
然后
applicationContext.getBean(String name); 进行强转 转为需要的Bean,比如
UserDao userDao = (UserDao)applicationContext.getBean("UserDao");
然后这里就可以使用userDao进行逻辑操作了
(4)对于执行一次并且全局调用的对象,可以将其放入到Threadlocal中
,类似于PageHelper的startPage()
方法封装的一样,会封装以一个ThreadLocal对象,下次取直接获取即可
这里例子是,登录的时候 将用户userId存入到ThreadLocal,在一些拦截器中直接通过get方法获取即可

import org.springframework.stereotype.Component;

/**
 * 管理登录用户的工具类
 *
 * @since 2019-12-07 17:10
 **/
@Component
public class AccessUserManager {
    /**
     * 用来存储当前访问用户ID的线程变量池
     */
    private static ThreadLocal<Integer> accessUserIdThread = new ThreadLocal<>();

    /**
     * 取出当前访问的用户ID
     *
     * @return java.lang.Integer 当前访问的用户ID
     * @date 2019-12-07
     */
    public static Integer getAccessUserId() {
        Integer accessUserId = accessUserIdThread.get();
        if (accessUserId != null) {
            return accessUserId;
        } else {
            throw new NullPointerException("当前访问的用户ID为空");
        }
    }

    /**
     * 存入当前访问的用户ID
     *
     * @param accessUserId 用户ID
     * @date 2019-12-07
     */
    public static void setAccessUserId(Integer accessUserId) {
        accessUserIdThread.set(accessUserId);
    }

    /**
     * 清除当前线程保存的用户ID
     *
     * @date 2019-12-07
     */
    public static void clearAccessUserId() {
        accessUserIdThread.remove();
    }
}

4.StringUtils文档 https://www.jianshu.com/p/3c12ae6a4909

5.在编写一些需要效率的sql语句,可以考虑使用原生的jdbc,只需要通过dataSource获取connect进行数据库操作即可

    @Autowired
    DataSource dataSource;

  Connection connection = dataSource.getConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from error_info");
        while(resultSet.next()){
            ErrorInfo errorInfo = new ErrorInfo();
            int id = resultSet.getInt("id");
            String userName = resultSet.getString("user_name");
            String error = resultSet.getString("error");
            String position = resultSet.getString("position");
            Date create_time = resultSet.getDate("create_time");
            errorInfo.setId(id).setUserName(userName).setError(error).setPosition(position).setCreateTime(create_time);
            System.out.println(JSON.toJSONString(errorInfo));
        }

6.重新加载数据库连接,可以使用下面的方法,这里是将配置文件中的数据进行解密

    @Bean
    public DataSource dataSource(DataSourceProperties dataSourceProperties) throws Exception {
        // userName = root  password = admin
        String username = dataSourceProperties.getUsername();
        String password = dataSourceProperties.getPassword();
        dataSourceProperties.setUsername(SymmetricEncoder.decrypt(username));
        dataSourceProperties.setPassword(SymmetricEncoder.decrypt(password));
        return dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值