20190723 BaseController封装

本文介绍了一个SpringBoot项目中如何通过基类BaseController实现统一的异常处理、工具方法封装及请求信息获取等通用操作,包括了从请求头中获取用户信息、设备信息、系统code等内容。
部署运行你感兴趣的模型镜像

1、BaseService的封装思路一样,很多通用性的方法都可以放在父类里面

2、请求头获取信息;

3、工具性操作封装到父类里面;

4、如果获取不到值,直接抛异常;

package com.yunque.www.springbootdemo.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunque.www.springbootdemo.exceptions.PicaException;
import com.yunque.www.springbootdemo.exceptions.PicaResultCode;
import com.yunque.www.springbootdemo.pojo.BaseResult;
import com.yunque.www.springbootdemo.redis.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class BaseController {

    public Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public RedisUtils redisUtils;

    //todo:把通用性的操作封装到父类里面
    @Autowired
    private DoctorServiceClient doctorServiceClient;

    @Autowired
    private PermissionServiceClient permissionServiceClient;


    public PicaUser getPicaUser() {
        return this.getCurrentPicaUser();
    }

    public PicaUser fetchPicaUser() {
        return this.getCurrentPicaUser();
    }


    /**
     * 封装统一的返回对象
     *
     * @param data
     * @param <T>
     * @return
     */
    public <T> BaseResult<T> getBaseResult(T data) {
        BaseResult baseResult = BaseResult.buildSuccess();
        baseResult.setData(data);
        return baseResult;
    }

    /**
     * 获取PicaUser
     *
     * @return
     */
    public PicaUser getCurrentPicaUser() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");
        PicaUser picaUser = null;
        if (StringUtils.isEmpty(token)) {
            return null;
        } else {
            //封装redis中的方法
            picaUser = redisUtils.getToken(token, PicaUser.class);
            if (picaUser != null) {
                picaUser.setToken(token);
            }
        }
        return picaUser;
    }

    /**
     * 从请求头中获取token
     *
     * @return
     */
    public String getTokenFromHeader() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest().getHeader("token");
    }

    /**
     * 从请求头中获取系统code
     *
     * @return
     */
    public String getSysCodeFromHeader() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest().getHeader("sysCode");
    }

    /**
     * 从请求头中获取设备信息
     *
     * @return
     */
    public String getDeviceInfoFromHeader() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest().getHeader("deviceInfo");
    }

    /**
     * 获取请求头信息
     *
     * @return
     */
    public Map<String, Object> getHeader() {
        Map<String, Object> map = new HashMap<>();
        map.put("picaUser", this.getCurrentPicaUser());
        map.put("sysCode", this.getSysCodeFromHeader());
        map.put("deviceInfo", this.getDeviceInfoFromHeader());
        return map;
    }

    /**
     * 获取请求的ip地址
     *
     * @return
     */
    protected final String getIpAddr() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }


    /**
     * 获取app版本号
     *
     * @return
     */
    public String getAppVersion() {
        String deviceInfoFromHeader = this.getDeviceInfoFromHeader();
        if (StringUtils.isEmpty(deviceInfoFromHeader)) {
            return "";
        }
        //todo:转化成json字符串获取其中某一个键值对的值
        try {
            JSONObject jsonObject = JSONObject.parseObject(deviceInfoFromHeader);
            return jsonObject.getString("app_version");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取userId
     *
     * @return
     */
    public long getUserIdByToken() {
        try {
            PicaUser picaUser = this.getCurrentPicaUser();
            return picaUser.getId().longValue();
        } catch (Exception e) {
            e.printStackTrace();
            //todo:直接抛出异常
            throw new PicaException(PicaResultCode.LOGIN_FAIL);
        }
    }

    /**
     * 从token获取userId,如果获取不到则抛出异常
     *
     * @return
     */
    public long fetchUserIdByToken() {
        String token = this.getTokenFromHeader();
        if (StringUtils.isEmpty(token)) {
            throw new PicaException(PicaResultCode.LOGIN_FAIL);
        }
        return this.getUserIdByToken();
    }

    /**
     * 获取当前用户的角色
     *
     * @return
     */
    public List<PermissionRoleDto> getRoles() {
        long userId = this.getUserIdByToken();
        DoctorHospitalDto doctorHospitalDto = (DoctorHospitalDto) doctorServiceClient.getHospitalInfoById(userId).getData();
        if (doctorHospitalDto == null || doctorHospitalDto.getHospitalId() == null) {
            throw new PicaException("40000", "权限被拒绝");
        }
        List<PermissionRoleDto> roles = (List<PermissionRoleDto>) permissionServiceClient.getPermissionRoles(userId).getData();
        if (!CollectionUtils.isEmpty(roles)) {
            return roles;
        }
        return null;
    }

    /**
     * 发送短息
     */
    public void sendMessage(String mobile, String content, String senderId) {
        Map<Object, Object> map = new HashMap<>();
        map.put("mobileSmsEntityContentList", new ArrayList<>());
        map.put("sign", "sign");
        map.put("userId", senderId);
        map.put("batchNo", "batchNo");
        //todo:把集合转化成字符串
        String data = JSON.toJSONString(map);
        //进行发送短息的操作,发送一个网络请求
        //判断短信发送的结果
        String jsonObj = "";
        if (StringUtils.isEmpty(jsonObj)) {
            logger.info("发送短信成功,返回结果:{}", jsonObj);
        } else {
            logger.error("发送短信失败");
        }


    }
}

 

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

<think>好的,用户的问题是关于如何在项目中添加和配置BaseController或其相关框架。首先,我需要明确用户提到的BaseController是什么。根据提供的引用内容,特别是引用[1]和[2],BaseController似乎是在CodeIgniter和若依(RuoYi)框架中使用的一个基类控制器,用于提供通用功能,比如视图自动加载或布局支持。 接下来,用户可能是在使用类似CodeIgniter或Spring MVC的框架,需要集成BaseController。但引用中提到的CodeIgniter-base-controller项目已经被标记为弃用,所以需要提醒用户这一点。此外,引用[3]和[4]涉及Spring MVC的注解和配置,说明用户可能对Spring MVC中的控制器配置也有兴趣。 我需要分情况讨论,因为不同的框架有不同的配置方法。首先处理CodeIgniter的情况,然后是若依框架,最后是Spring MVC,因为用户可能混淆了不同框架中的BaseController概念。 对于CodeIgniter,虽然原项目已弃用,但安装步骤仍然可以给出,同时建议替代方案。对于若依框架,引用[2]提到继承BaseController,需要说明其用途和配置方法。在Spring MVC中,通常不会直接使用BaseController,但可以通过自定义基类来实现类似功能,需要指导用户如何创建和配置。 此外,用户可能不太清楚不同框架之间的区别,需要明确区分,并提供每一步的具体操作,比如依赖添加、继承类、方法重写等。同时,要检查是否有遗漏的步骤,比如自动加载配置或注解的使用,确保配置正确。 最后,生成相关问题时要覆盖不同框架和常见问题,帮助用户进一步探索可能的需求。</think>### 如何添加和配置 BaseController 或相关框架 #### 一、CodeIgniter 的 BaseController 配置(已弃用) 引用[1]提到的 `codeigniter-base-controller` 是一个已弃用的项目,但若需参考其实现逻辑: 1. **手动实现基类控制器** - 在 `application/core/` 目录下创建 `MY_Controller.php` ```php class BaseController extends CI_Controller { public function __construct() { parent::__construct(); // 添加通用逻辑(如视图自动加载) } } ``` - 其他控制器继承此基类: ```php class UserController extends BaseController { // 控制器方法 } ``` #### 二、若依(RuoYi)框架的 BaseController 引用[2]提到若依框架通过继承 `BaseController` 实现通用功能(如日志记录、权限验证): 1. **配置步骤** - 查看 `BaseController` 的源码位置(通常位于 `framework/web/core` 目录) - 新建控制器时直接继承: ```java @Controller @RequestMapping("/user") public class UserController extends BaseController { // 使用基类提供的公共方法 } ``` - 确保项目依赖包含若依的 `framework` 模块(通过 Maven/Gradle 配置) #### 三、Spring MVC 自定义基类控制器 引用[3][4]提到 Spring MVC 中可通过自定义基类实现通用逻辑: 1. **创建 BaseController 类** ```java @Controller public class BaseController { // 通用方法(如统一响应格式) protected ResponseEntity<Result> success(Object data) { return ResponseEntity.ok(Result.success(data)); } } ``` 2. **子类控制器继承** ```java @RestController @RequestMapping("/api") public class UserController extends BaseController { @GetMapping("/users") public ResponseEntity<Result> getUsers() { return success(userService.getAll()); } } ``` 3. **依赖配置(Maven)** ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` #### 四、通用注意事项 1. **框架兼容性** - 不同框架的 `BaseController` 实现方式不同,需遵循各自规范(如 CodeIgniter 要求文件路径,Spring 依赖注解) 2. **功能扩展** - 基类通常用于封装:请求预处理、日志记录、权限校验等[^2][^4] ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值