Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 15.重构 Service 接口

原文地址:http://www.work100.net/training/monolithic-project-iot-cloud-admin-manager-rebuild-service.html
更多教程:光束云 - 免费课程

重构 Service 层

序号 文内章节 视频
1 概述 -
2 定义BaseService通用接口 -
3 重构AuthManagerService接口 -
4 重构AuthManagerServiceImpl实现 -
5 重构ManagerController -
6 实例源码 -

请参照如上章节导航进行阅读

1.概述

上一节课已经对 Dao 层进行了重构,提取了通用方法,本节将对 Service 层进行重构。

2.定义BaseService通用接口

iot-cloud-commons 项目下新增 BaseService 接口,代码如下:

package net.work100.training.stage2.iot.cloud.commons.service;

import net.work100.training.stage2.iot.cloud.commons.dto.AbstractBaseDomain;
import net.work100.training.stage2.iot.cloud.commons.dto.BaseResult;
import net.work100.training.stage2.iot.cloud.commons.dto.BaseSearcher;
import net.work100.training.stage2.iot.cloud.commons.dto.PageInfo;

import java.util.List;

/**
 * <p>Title: BaseService</p>
 * <p>Description: </p>
 *
 * @author liuxiaojun
 * @date 2020-03-18 09:47
 * ------------------- History -------------------
 * <date>      <author>       <desc>
 * 2020-03-18   liuxiaojun     初始创建
 * -----------------------------------------------
 */
public interface BaseService<T extends AbstractBaseDomain, Searcher extends BaseSearcher> {

    /**
     * 查询全部表记录
     *
     * @return
     */
    List<T> selectAll();

    /**
     * 新增
     *
     * @param entity
     * @return
     */
    BaseResult insert(T entity);

    /**
     * 更新
     *
     * @param entity
     * @return
     */
    BaseResult update(T entity);

    /**
     * 删除
     *
     * @param entityKey
     */
    void delete(String entityKey);

    /**
     * 批量删除
     *
     * @param entityKeys
     */
    void multiDelete(String[] entityKeys);

    /**
     * 获取单个对象
     *
     * @param id
     * @return
     */
    T getById(Long id);

    /**
     * 获取对象
     *
     * @param entityKey
     * @return
     */
    T getByKey(String entityKey);

    /**
     * 搜索
     *
     * @param searcher 搜索器
     * @return
     */
    List<T> search(Searcher searcher);

    /**
     * 分页搜索
     *
     * @param draw
     * @param start    起始位置
     * @param length   每页长度
     * @param searcher 搜索器
     * @return
     */
    PageInfo<T> pageSearch(int draw, int start, int length, Searcher searcher);
}

3.重构AuthManagerService接口

接下来重构 AuthManagerService 接口,代码如下:

package net.work100.training.stage2.iot.cloud.web.admin.service;

import net.work100.training.stage2.iot.cloud.commons.service.BaseService;
import net.work100.training.stage2.iot.cloud.domain.AuthManager;
import net.work100.training.stage2.iot.cloud.web.admin.dto.auth.ManagerSearcher;

import java.util.List;

/**
 * <p>Title: AuthManagerService</p>
 * <p>Description: </p>
 * <p>Url: http://www.work100.net/training/monolithic-project-iot-cloud-admin.html</p>
 *
 * @author liuxiaojun
 * @date 2020-02-23 23:01
 * ------------------- History -------------------
 * <date>      <author>       <desc>
 * 2020-02-23   liuxiaojun     初始创建
 * -----------------------------------------------
 */
public interface AuthManagerService extends BaseService<AuthManager, ManagerSearcher> {

    /**
     * 登录验证
     *
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    AuthManager login(String userName, String password);

}

4.重构AuthManagerServiceImpl实现

接下来重构 AuthManagerServiceImpl 实现,代码如下:

package net.work100.training.stage2.iot.cloud.web.admin.service.impl;

import net.work100.training.stage2.iot.cloud.commons.dto.BaseResult;
import net.work100.training.stage2.iot.cloud.commons.dto.PageInfo;
import net.work100.training.stage2.iot.cloud.commons.utils.EncryptionUtils;
import net.work100.training.stage2.iot.cloud.domain.AuthManager;
import net.work100.training.stage2.iot.cloud.web.admin.dao.AuthManagerDao;
import net.work100.training.stage2.iot.cloud.web.admin.dto.auth.ManagerSearcher;
import net.work100.training.stage2.iot.cloud.web.admin.service.AuthManagerService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>Title: AuthManagerServiceImpl</p>
 * <p>Description: </p>
 * <p>Url: http://www.work100.net/training/monolithic-project-iot-cloud-admin.html</p>
 *
 * @author liuxiaojun
 * @date 2020-02-23 23:06
 * ------------------- History -------------------
 * <date>      <author>       <desc>
 * 2020-02-23   liuxiaojun     初始创建
 * -----------------------------------------------
 */
@Service
public class AuthManagerServiceImpl implements AuthManagerService {

    @Autowired
    private AuthManagerDao authManagerDao;

    @Override
    public List<AuthManager> selectAll() {
        return authManagerDao.selectAll();
    }

    @Override
    public BaseResult insert(AuthManager authManager) {
        if (authManagerDao.getByUserName(authManager.getUserName()) != null) {
            return BaseResult.fail("用户名已经存在");
        }
        try {
            // 生成 userKey
            authManager.setUserKey(generateUserKey(authManager.getUserName()));

            // 密码加密
            authManager.setPassword(EncryptionUtils.encryptPassword(EncryptionUtils.EncryptionType.MD5, authManager.getPassword()));
            authManager.setCreated(new Date());
            authManager.setUpdated(new Date());

            authManagerDao.insert(authManager);
            return BaseResult.success("新增账户成功");
        } catch (Exception ex) {
            return BaseResult.fail("未知错误");
        }
    }

    @Override
    public BaseResult update(AuthManager authManager) {
        if (authManagerDao.getByKey(authManager.getUserKey()) == null) {
            return BaseResult.fail("用户不存在");
        }
        try {
            authManager.setUpdated(new Date());

            authManagerDao.update(authManager);
            return BaseResult.success("账户更新成功");
        } catch (Exception ex) {
            return BaseResult.fail("未知错误");
        }
    }

    @Override
    public void delete(String userKey) {
        authManagerDao.delete(userKey);
    }

    @Override
    public void multiDelete(String[] userKeys) {
        authManagerDao.multiDelete(userKeys);
    }

    @Override
    public AuthManager getById(Long id) {
        return authManagerDao.getById(id);
    }

    @Override
    public AuthManager getByKey(String userKey) {
        return authManagerDao.getByKey(userKey);
    }

    @Override
    public List<AuthManager> search(ManagerSearcher managerSearcher) {
        AuthManager authManager = new AuthManager();
        if (!managerSearcher.isAdvanced()) {
            authManager.setUserName(managerSearcher.getKeyword());
            authManager.setRoles("");
            authManager.setStatus(-1);
        } else {
            authManager.setUserName(managerSearcher.getUserName());
            authManager.setRoles(managerSearcher.getRoles());
            authManager.setStatus(managerSearcher.getStatus());
        }
        return authManagerDao.search(authManager);
    }

    @Override
    public PageInfo<AuthManager> pageSearch(int draw, int start, int length, ManagerSearcher managerSearcher) {
        Map<String, Object> params = new HashMap<>();
        params.put("start", start);
        params.put("length", length);
        AuthManager authManager = new AuthManager();

        if (!managerSearcher.isAdvanced()) {
            authManager.setUserName(managerSearcher.getKeyword());
            authManager.setRoles("");
            authManager.setStatus(-1);

            params.put("userName", managerSearcher.getKeyword());
            params.put("roles", "");
            params.put("status", -1);
        } else {
            authManager.setUserName(managerSearcher.getUserName());
            authManager.setRoles(managerSearcher.getRoles());
            authManager.setStatus(managerSearcher.getStatus());

            params.put("userName", managerSearcher.getUserName());
            params.put("roles", managerSearcher.getRoles());
            params.put("status", managerSearcher.getStatus());
        }

        // 处理分页结果
        PageInfo<AuthManager> authManagerPageInfo = new PageInfo<>();
        authManagerPageInfo.setDraw(draw);

        // 获取记录数
        int recordsTotal = authManagerDao.count(authManager);
        authManagerPageInfo.setRecordsTotal(recordsTotal);
        authManagerPageInfo.setRecordsFiltered(recordsTotal);

        // 获取分页数据
        List<AuthManager> data = authManagerDao.pageSearch(params);
        authManagerPageInfo.setData(data);

        return authManagerPageInfo;
    }

    @Override
    public AuthManager login(String userName, String password) {
        AuthManager authManager = authManagerDao.getByUserName(userName);
        if (authManager != null && authManager.getStatus() == 1) {
            // 验证密码,如果验证通过,则返回用户信息
            if (EncryptionUtils.validateEncryptPassword(password, authManager.getPassword())) {
                return authManager;
            }
        }
        return null;
    }

    /**
     * 生成 userKey
     *
     * @param userName 用户名
     * @return
     */
    private String generateUserKey(String userName) {
        String strDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sourceUserKey = String.format("%s%s", userName.toLowerCase(), strDate);
        return EncryptionUtils.encryptText(EncryptionUtils.EncryptionType.MD5, sourceUserKey);
    }

}

5.重构ManagerController

接下来重构 ManagerController 实现,代码如下:

package net.work100.training.stage2.iot.cloud.web.admin.web.controller.auth;

import net.work100.training.stage2.iot.cloud.commons.dto.BaseResult;
import net.work100.training.stage2.iot.cloud.commons.dto.PageInfo;
import net.work100.training.stage2.iot.cloud.commons.utils.HttpUtils;
import net.work100.training.stage2.iot.cloud.commons.validator.BeanValidator;
import net.work100.training.stage2.iot.cloud.domain.AuthManager;
import net.work100.training.stage2.iot.cloud.web.admin.dto.auth.ManagerSearcher;
import net.work100.training.stage2.iot.cloud.web.admin.service.AuthManagerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>Title: ManagerController</p>
 * <p>Description: </p>
 * <p>Url: http://www.work100.net/training/monolithic-project-iot-cloud-admin.html</p>
 *
 * @author liuxiaojun
 * @date 2020-03-01 14:01
 * ------------------- History -------------------
 * <date>      <author>       <desc>
 * 2020-03-01   liuxiaojun     初始创建
 * -----------------------------------------------
 */
@Controller
@RequestMapping(value = "auth/manager")
public class ManagerController {

    @Autowired
    private AuthManagerService authManagerService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(Model model) {
        ManagerSearcher managerSearcher = new ManagerSearcher();
        managerSearcher.setKeyword("");
        managerSearcher.setAdvanced(false);
        managerSearcher.setRoles("");
        managerSearcher.setStatus(-1);
        model.addAttribute(managerSearcher);
        
        return "auth/manager_list";
    }

    @RequestMapping(value = "search", method = RequestMethod.POST)
    public String search(ManagerSearcher managerSearcher, Model model) {
        List<AuthManager> authManagers = authManagerService.search(managerSearcher);
        model.addAttribute("managerSearcher", managerSearcher);
        model.addAttribute("authManagers", authManagers);
        return "auth/manager_list";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(Model model) {
        AuthManager authManager = new AuthManager();
        model.addAttribute("authManager", authManager);
        return "auth/manager_add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(AuthManager authManager, Model model, RedirectAttributes redirectAttributes) {
        String validator = BeanValidator.validator(authManager);
        if(validator!=null){
            model.addAttribute("baseResult", BaseResult.fail(validator));
            model.addAttribute("authManager", authManager);
            return "auth/manager_add";
        }

        // 新增处理
        BaseResult baseResult = authManagerService.insert(authManager);
        if (baseResult.getStatus() == HttpUtils.HTTP_STATUS_CODE_OK) {
            redirectAttributes.addFlashAttribute("baseResult", baseResult);
            return "redirect:/auth/manager/list";
        } else {
            model.addAttribute("baseResult", baseResult);
            return "auth/manager_add";
        }
    }

    @RequestMapping(value = "edit/{userKey}", method = RequestMethod.GET)
    public String edit(@PathVariable String userKey, Model model, RedirectAttributes redirectAttributes) {
        if (StringUtils.isBlank(userKey)) {
            redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("参数为空"));
            return "redirect:/auth/manager/list";
        }
        AuthManager authManager = authManagerService.getByKey(userKey);
        if (authManager == null) {
            redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("数据不存在"));
            return "redirect:/auth/manager/list";
        }
        model.addAttribute("authManager", authManager);
        return "auth/manager_edit";
    }

    @RequestMapping(value = "edit/{userKey}", method = RequestMethod.POST)
    public String edit(@PathVariable String userKey, AuthManager authManager, Model model, RedirectAttributes redirectAttributes) {
        // 数据验证
        if (StringUtils.isBlank(userKey)) {
            redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("参数为空"));
            return "redirect:/auth/manager/list";
        }
        if (!userKey.equals(authManager.getUserKey())) {
            redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("非法请求"));
            return "redirect:/auth/manager/list";
        }
        String validator = BeanValidator.validator(authManager);
        if(validator!=null){
            model.addAttribute("baseResult", BaseResult.fail(validator));
            model.addAttribute("authManager", authManager);
            return "auth/manager_edit";
        }

        // 新增处理
        BaseResult baseResult = authManagerService.update(authManager);
        if (baseResult.getStatus() == HttpUtils.HTTP_STATUS_CODE_OK) {
            redirectAttributes.addFlashAttribute("baseResult", baseResult);
            return "redirect:/auth/manager/list";
        } else {
            model.addAttribute("baseResult", baseResult);
            return "auth/manager_edit";
        }
    }


    @RequestMapping(value = "delete/{userKey}", method = RequestMethod.GET)
    public String delete(@PathVariable String userKey, RedirectAttributes redirectAttributes) {
        if (StringUtils.isBlank(userKey)) {
            redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("参数为空"));
            return "redirect:/auth/manager/list";
        }
        AuthManager authManager = authManagerService.getByKey(userKey);
        if (authManager == null) {
            redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("数据不存在"));
            return "redirect:/auth/manager/list";
        }
        authManagerService.delete(userKey);
        redirectAttributes.addFlashAttribute("baseResult", BaseResult.success(String.format("账户[%s]已被成功删除", authManager.getUserName())));
        return "redirect:/auth/manager/list";
    }

    @ResponseBody
    @RequestMapping(value = "multi-delete", method = RequestMethod.POST)
    public BaseResult multiDelete(String userKeys) {
        try {
            String[] arrUserKeys = userKeys.split(",");
            if (arrUserKeys == null || arrUserKeys.length <= 0) {
                return BaseResult.fail("请至少选择一条记录");
            }
            for (String userKey : arrUserKeys) {
                if ("8c41b9a54b2e2a4180cc1271b4672779".equals(userKey)) {
                    return BaseResult.fail("不能删除默认管理员账号:xiaojun.liu");
                }
            }
            authManagerService.multiDelete(arrUserKeys);
            return BaseResult.success("操作成功");
        } catch (Exception ex) {
            return BaseResult.fail("未知错误");
        }
    }

    @ResponseBody
    @RequestMapping(value = "page-search", method = RequestMethod.POST)
    public PageInfo<AuthManager> pageSearch(HttpServletRequest request) {
        String strDraw = request.getParameter("draw");
        String strStart = request.getParameter("start");
        String strLength = request.getParameter("length");
        String strAdvanced = request.getParameter("advanced");
        String keyword = request.getParameter("keyword");
        String userName = request.getParameter("userName");
        String roles = request.getParameter("roles");
        String strStatus = request.getParameter("status");

        int draw = strDraw == null ? 0 : Integer.parseInt(strDraw);
        int start = strStart == null ? 0 : Integer.parseInt(strStart);
        int length = strLength == null ? 0 : Integer.parseInt(strLength);
        boolean advanced = strAdvanced == null ? false : Boolean.parseBoolean(strAdvanced);
        int status = strStatus == null ? 0 : Integer.parseInt(strStatus);

        ManagerSearcher managerSearcher = new ManagerSearcher();
        managerSearcher.setAdvanced(advanced);
        managerSearcher.setKeyword(keyword);
        managerSearcher.setUserName(userName);
        managerSearcher.setRoles(roles);
        managerSearcher.setStatus(status);

        return authManagerService.pageSearch(draw, start, length, managerSearcher);
    }
}

6.实例源码

实例源码已经托管到如下地址:


上一篇:重构Dao层

下一篇:重构Service实现


如果对课程内容感兴趣,可以扫码关注我们的 公众号QQ群,及时关注我们的课程更新

posted @ 2020-04-01 15:34  光束云  阅读(320)  评论(0编辑  收藏  举报