美文网首页工作生活
SSM之SSM应用实例

SSM之SSM应用实例

作者: TiaNa_na | 来源:发表于2019-10-30 16:12 被阅读0次
    一 日志功能,实现将用户操作日志保存到数据库
    1.准备工作

    新建ssm项目,添加依赖,在spring-mvc.xml添加aop相关配置

    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.1.1.RELEASE</version>
    </dependency>
    
    <!-- 启用 aspectj 方式 AOP-->
        <aop:aspectj-autoproxy proxy-target-class="true"/>
    
    2.实现

    2.1 自定义注解

    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Log {
        /**
         * 操作事件
         */
        String value();
    }
    

    2.2 日志类

    public class UserLog {
       //日志id
        private Integer id;
       //用户id
        private Integer userId;
        //用户ip
        private String ip;
       //操作时间
        private Date createdTime;
       //请求方法
        private String method;
       //请求url
        private String requestUrl;
       //返回结果
        private String result;
      
      //get和set方法
      ...
    }
    

    数据库字段和实体类对应即可
    2.3 数据库mapper

    public interface UserLogMapper {
        int deleteByPrimaryKey(Integer logId);
    
        int insert(UserLog userLog);
    
        UserLog selectByPrimaryKey(Integer logId);
    
        List<UserLog> selectAll();
    
        int updateByPrimaryKey(UserLog record);
    
        /**
         * 查询某一个时间段的数据
         * @param start  开始的时间
         * @param stop   结束的时间
         * */
        List<UserLog> selectUserByPeriod(@Param("start") String start, @Param("stop") String stop);
    }
    

    2.5 service

    @Aspect
    @Component
    public class LogServiceImpl implements LogService {
    /*
         * 获取入参和出参
         * @param joinPoint
         * @param o
         * @return
         * */
        @Override
        public void getByJoinPoint(JoinPoint joinPoint, Object o) throws ClassNotFoundException {
            StringBuffer operateEvent = new StringBuffer();
            String targetName = joinPoint.getTarget().getClass().getName(); // 请求类名称
            String methodName = joinPoint.getSignature().getName(); // 请求方法
            Object[] arguments = joinPoint.getArgs();  //获取入参
            UserLog userLog = new log();
            User loginUser = (User) session.getAttribute("loginUser");
            log.setUserId(loginUser.getId());
           //getHos()是获取客户端ip的方法
            log.setLogIp(getHost(request));
            log.setLogReqUrl(request.getRequestURI());
            log.setLogMethod(joinPoint.getSignature().getDeclaringTypeName() + "," + joinPoint.getSignature().getName());
            // 从o中读取提取返回结果  
            //String result = 
             log.setLogResult(result);
            //保存到数据库
            int insert = mapper.insert(log);
    

    2.4 LogAspect.java:日志切面

    @Aspect
    @Component
    @Order(3)
    public class LogAspect {
    
        // 注入Service用于把日志保存数据库
        @Autowired
        private LogService logService;
    
        // 切点
      //@annotation用于匹配当前执行方法持有指定注解的方法;
        @Pointcut("@annotation(com.cateringsystem.service.web.log.Log)") 
        public void logAspect() {
        }
     
        @Around("logAspect()")
        public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
            Object result = joinPoint.proceed();
            logService.getByJoinPoint(joinPoint, result);
            return result;
        }
    }
    

    2.5 在需要生成日志的Controller上加上@Log注解,当然在service层加注解也可以

    @RestController
    public class UserController {
    
       @Log(value = "  ")
       @RequestMapping(value = "/getUser", method = RequestMethod.GET)
       public String getUser(Model model,String parameter1,Integer parameter2) {
           ...
       }
    }
    
    3.测试

    运行项目,请求getUser这个方法,数据库就多了一条记录.
    参考https://my.oschina.net/u/3136014/blog/904643#comments

    二 文件上传下载
    1 上传文件
         /**
         * form 表单上传图片/文件的方法
         *
         * @param savePath      获取图片/文件保存路径
         * @param multipartFile 文件上传对象
         */
        public static String setMultipartFile(String savePath, MultipartFile multipartFile) throws IOException {
            // 获取文件对象
            File file = new File(savePath);
            // 获取路径
            String basePath = file.getPath();
            // 重命名后的文件
            String relativePath = getMakeRelativePath(multipartFile.getOriginalFilename());
            // 创建一个文件
            File target = new File(basePath.concat(relativePath));
            target.getParentFile();
            // 转移图片数据
            multipartFile.transferTo(target);
            String fileName = target.getName();
            return fileName;
        }
    
    • controller接口可参照下文的wangEditor实现富文本编辑的controller接口
    2 下载文件
        @RequestMapping(value = "/pic/{id}", method = RequestMethod.GET)
        public Result getPic(@PathVariable("id") Integer id, HttpServletResponse response) throws Exception {
           //根据id获取图片名
            Test test = deviceService.getById(id);
            String fileName = test .getPic;
          //从本地获取图片,实际开发中需要从服务器获取
            File file = new File(“f:/test/”.concat(fileName));
           long fileSize = file.length();
            // 重置response
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes(), "GBK"));
            response.addHeader("Content-Length", String.valueOf(fileSize));
    
            // 读取并以流的方式输出
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = (bis.read(buffer))) != -1) {
                bos.write(buffer, 0, length);
            }
    
            bos.flush();
            bos.close();
            bis.close();
    
            return null;
        }
    
    三 wangEditor实现富文本编辑

    官方文档
    这个富文本编辑器使用中最需要注意的是上传图片功能。服务器配置如下:

    1 返回类

    官方文档给出了这样的说明:https://www.kancloud.cn/wangfupeng/wangeditor3/335782
    首先我们需要定义一个返回类,返回类必须是下面的格式。

    @Data
    public class ImgResult<T> {
    
        /**
         * 错误码
         */
        private int errno;
    
        /**
         *  data 是一个数组,返回若干图片的线上地址
         */
        private String[] data;
    }
    
    2 controller接口写法
        @RequestMapping(value = "/uploads", method = RequestMethod.POST)
        public ImgResult upload(@RequestParam(value = "files", required = false) MultipartFile[] files) throws IOException {
            ImgResult result = new ImgResult();
          // form 表单上传多张图片/文件的方法
            List<String> picPath = Upload.setMultipartFiles("F:/test/", files);
            int index = 0;
            String[] url = new String[picPath.size()];
            for (String s : picPath) {
                url[index++] = s;
            }
            result.setData(url);
            return result;
        }
    
    四 quartz定时任务
    quartz定时任务基础知识可查看https://blog.csdn.net/noaman_wgs/article/details/80984873

    定时任务相关内容网上资料很多,不再多做说明。

    相关文章

      网友评论

        本文标题:SSM之SSM应用实例

        本文链接:https://www.haomeiwen.com/subject/qcgwcctx.html