package com.de.debook.config; import com.de.debook.interceptor.AuthorityInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class ConfigRegistCanter implements WebMvcConfigurer { //注册拦截器 //addPathPatterns 用来设置拦截路径 //excludePathPatterns 用来设置白名单,也就是不需要触发这个拦截器的路径。 //addPathPatterns("/**") 表示拦截所有的请求 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AuthorityInterceptor()) .excludePathPatterns("/user/login.html") .excludePathPatterns("/user/login") .excludePathPatterns("/user/login.out") .excludePathPatterns("/user/register.html") .excludePathPatterns("/user/register") .excludePathPatterns("/admin/register.html") .excludePathPatterns("/index.html") .excludePathPatterns("/js/**") .excludePathPatterns("/css/**") .excludePathPatterns("/images/**") .excludePathPatterns("/layui/**") .excludePathPatterns("/wangEditor/**"); } //这个方法是用来配置静态资源的,比如html,js,css等 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { } }

时间: 2024-01-24 16:20:04 浏览: 29
这是一个 Spring Boot 配置类,用于注册拦截器和配置静态资源的映射路径。具体来说,代码中的 `AuthorityInterceptor` 是自定义的拦截器类,用来实现用户权限的控制。在 `addInterceptors` 方法中,通过 `registry.addInterceptor()` 方法添加拦截器,并使用 `excludePathPatterns` 方法设置白名单,即不需要被拦截的路径。在这个例子中,白名单包括登录、注册等页面、静态资源等。在 `addResourceHandlers` 方法中,可以配置静态资源的映射路径。
相关问题

package com.de.debook.init; import com.de.debook.constant.WebConstant; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import org.springframework.util.ClassUtils; @Component public class InitConfig implements CommandLineRunner { @Override public void run(String... strings) throws Exception { // 项目路径 WebConstant.WEB_FILE_ROOT = ClassUtils.getDefaultClassLoader() .getResource("").getPath().substring(1); // 图片存储目录 WebConstant.FILE_STORAGE_ROOT = WebConstant.WEB_FILE_ROOT + "static/images/"; } }

这是一个Spring Boot项目的初始化配置类,实现了CommandLineRunner接口,用于在Spring Boot应用程序启动时执行一些初始化操作。 具体来说,该配置类的run方法实现了以下两个操作: 1. 获取项目路径:通过ClassUtils.getDefaultClassLoader().getResource("").getPath()方法获取当前类所在的classpath路径,然后通过substring(1)方法去掉开头的“/”字符,得到项目的根路径。 2. 设置图片存储目录:将WebConstant.WEB_FILE_ROOT和"static/images/"拼接起来,得到图片存储目录的绝对路径,保存到WebConstant.FILE_STORAGE_ROOT中。 这里的WebConstant是一个常量类,用于保存项目中的常量值。通过这个配置类,我们可以方便地获取项目路径和设置图片存储目录,从而方便地进行文件操作。

package com.de.debook.interceptor; import com.de.debook.entity.User; import com.de.debook.constant.WebConstant; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @Component public class AuthorityInterceptor implements HandlerInterceptor { // 权限拦截器 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); User user = (User) session.getAttribute(WebConstant.SESSION_KEY_USER); // 用户未登录状态返回登录页面 if (user == null) { response.sendRedirect("/user/login.html"); return false; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }

这段代码是一个权限拦截器,用于拦截未登录用户的访问。在 preHandle 方法中,首先获取 HttpSession 中的 User 对象,如果 User 为 null,说明用户未登录,此时将请求重定向到登录页面,并返回 false,拦截请求。如果 User 不为 null,说明用户已经登录,放行请求,返回 true。其他两个方法没有实现,不做处理。

相关推荐

package com.de.debook.controller; import com.de.debook.bo.ResponseBean; import com.de.debook.constant.WebConstant; import com.de.debook.utils.FileUploadUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.Map; @RestController public class UploadFileController { private static final int FILE_SIZE_MAX = 20 * 1024 * 1024; // 上传限制大小 /** * @param multipartFile * @description: 通用文件上传处理器 * @return: java.util.Map<java.lang.String , java.lang.Object> */ @RequestMapping(value = "/uploadFile", produces = "application/json;charset=UTF-8") public Map<String, Object> fileUpload(@RequestParam("file") MultipartFile multipartFile) { ResponseBean responseBean = new ResponseBean(); if (multipartFile != null) { String realName = multipartFile.getOriginalFilename(); // 原始文件名 String suffix = FileUploadUtils.fileSuffix(realName); // 文件名后缀 String tmpFileName = FileUploadUtils.createTmpFileName(suffix); // 生成保证不重复的临时文件名 if (multipartFile.getSize() > FILE_SIZE_MAX) { responseBean.putError("上传失败:文件大小不得超过20MB"); return responseBean.getResponseMap(); } File tmpFile = new File(WebConstant.FILE_STORAGE_ROOT,tmpFileName); try { multipartFile.transferTo(tmpFile); // 写入本地 responseBean.putData("data", "/images/" + tmpFileName); } catch (IOException e) { responseBean.putError("上传失败:" + e.getMessage()); e.printStackTrace(); } } return responseBean.getResponseMap(); } }

<?xml version="1.0" encoding="UTF-8"?> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <groupId>com.de</groupId> <artifactId>debook</artifactId> <version>0.0.1-SNAPSHOT</version> <name>debook</name> <description>Demo project for Spring Boot</description> <java.version>1.8</java.version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.7</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> </dependencies> <build> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </build>

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.de.debook.mapper.CategoryMapper"> <resultMap id="BaseResultMap" type="com.de.debook.entity.Category"> <id column="id" jdbcType="INTEGER" property="id"/> <result column="name" jdbcType="VARCHAR" property="name"/> </resultMap> <resultMap id="StatisticsResultMap" type="com.de.debook.entity.Statistics"> <result column="name" jdbcType="VARCHAR" property="name"/> <result column="value" jdbcType="VARCHAR" property="value"/> </resultMap> <sql id="Base_Column_List"> id, name </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from category where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from category where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.de.debook.entity.Category"> insert into category (id, name) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.de.debook.entity.Category"> insert into category <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="name != null"> name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="name != null"> #{name,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.de.debook.entity.Category"> update category <set> <if test="name != null"> name = #{name,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.de.debook.entity.Category"> update category set name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> <select id="selectAll" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from category order by id asc </select> <select id="selectStatistics" resultMap="StatisticsResultMap"> SELECT t1.name as name, COUNT(*) as value FROM category t1, debook t2 WHERE t1.id = t2.category_id GROUP BY t1.id order by t1.id asc </select> </mapper>

package com.de.debook.utils; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; public class FileUploadUtils { /** * @param * @description: 生成一个唯一的ID * @return: java.lang.String */ public static String createUUID() { String s = UUID.randomUUID().toString(); String s2 = s.substring(24).replace("-", ""); return s2.toUpperCase(); } /** * @description: 得到一个保证不重复的临时文件名 * @return: java.lang.String */ public static String createTmpFileName(String suffix) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); String datestr = sdf.format(new Date()); String name = datestr + "-" + createUUID() + "." + suffix; return name; } /** * @param fileName 原始文件名 * @description: 得到文件的后缀名 * @return: java.lang.String */ public static String fileSuffix(String fileName) { int p = fileName.lastIndexOf('.'); if (p >= 0) { return fileName.substring(p + 1).toLowerCase(); } return ""; } public static void deleteDir(String dirPath) { File file = new File(dirPath); if (file.isFile()) { file.delete(); } else { File[] files = file.listFiles(); if (files == null) { file.delete(); } else { for (int i = 0; i < files.length; i++) { deleteDir(files[i].getAbsolutePath()); } file.delete(); } } } public static byte[] getFileByteArray(File file) { long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { System.out.println("file too big..."); return null; } byte[] buffer = null; try (FileInputStream fi = new FileInputStream(file)) { buffer = new byte[(int) fileSize]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } // 确保所有数据均被读取 if (offset != buffer.length) { throw new IOException("Could not completely read file" + file.getName()); } } catch (Exception e) { e.printStackTrace(); } return buffer; } public static void writeBytesToFile(byte[] bs, String file) throws IOException { OutputStream out = new FileOutputStream(file); InputStream is = new ByteArrayInputStream(bs); byte[] buff = new byte[1024]; int len = 0; while ((len = is.read(buff)) != -1) { out.write(buff, 0, len); } is.close(); out.close(); } }

最新推荐

recommend-type

rockyou.txt

rockyou
recommend-type

ASP+ACCESS网上人才信息管理系统(源代码+论文)【ASP】.zip

ASP+ACCESS网上人才信息管理系统(源代码+论文)【ASP】
recommend-type

河北金融学院经济大数据课设2024年 软科学校爬虫课设

河北金融学院经济大数据课设2024年 软科学校爬虫课设
recommend-type

widgetsnbextension-4.0.0b0-py3-none-any.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

协同过滤服务+源代码+文档说明

- 不懂运行,下载完可以私聊问,可远程教学 该资源内项目源码是个人的毕设,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! <项目介绍> 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。 --------
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB图像处理算法宝典:从理论到实战

![MATLAB图像处理算法宝典:从理论到实战](https://img-blog.csdnimg.cn/20200717112736401.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2d1emhhbzk5MDE=,size_16,color_FFFFFF,t_70) # 1. MATLAB图像处理基础理论 MATLAB图像处理是一种利用MATLAB编程语言进行图像处理的强大工具。它提供了丰富的函数和工具箱,用于图像获取、增强、分
recommend-type

matlab中1/x的非线性规划

在MATLAB中,可以使用非线性规划函数(`fmincon`)来优化一个包含1/x的非线性目标函数。下面是一个简单的例子: ```matlab % 定义目标函数 fun = @(x) 1/x; % 定义约束函数(这里没有约束) nonlcon = []; % 定义初始点 x0 = 1; % 定义优化选项 options = optimoptions('fmincon', 'Display', 'iter'); % 进行非线性规划 [x, fval] = fmincon(fun, x0, [], [], [], [], [], [], nonlcon, options); ``` 在
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。