整合作业
This commit is contained in:
@@ -8,10 +8,11 @@ import javax.crypto.SecretKey;
|
||||
import java.util.Date;
|
||||
|
||||
public class JwtUtil {
|
||||
private static final String SECRET = "ycjy-learning-secret-key-32bytes!!"; // 密钥
|
||||
private static final String SECRET = "asdfg"; // 密钥
|
||||
private static final SecretKey KEY = Keys.hmacShaKeyFor(SECRET.getBytes()); // 密钥对象
|
||||
private static final long EXPIRE_MS = 24 * 60 * 60 * 1000L; // 过期时间
|
||||
|
||||
// 生成JWT
|
||||
public static String generate(Integer userId, String username) {
|
||||
Date now = new Date();
|
||||
return Jwts.builder()
|
||||
@@ -23,6 +24,7 @@ public class JwtUtil {
|
||||
.compact();
|
||||
}
|
||||
|
||||
// 解析JWT
|
||||
public static Claims parse(String token) {
|
||||
try {
|
||||
return Jwts.parser()
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.alibaba.druid.pool.DruidDataSource;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.mybatis.spring.SqlSessionFactoryBean;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
@@ -12,6 +13,7 @@ import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
|
||||
@@ -21,10 +23,11 @@ import java.io.File;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan({"com.ycjy.service","com.ycjy.controller"})
|
||||
@ComponentScan({"com.ycjy.service","com.ycjy.controller","com.ycjy.config"})
|
||||
@PropertySource("classpath:db.properties")
|
||||
@MapperScan("com.ycjy.mapper")
|
||||
public class WebAppConfig implements WebMvcConfigurer {
|
||||
// 配置数据源
|
||||
@Bean(initMethod = "init")
|
||||
public DruidDataSource dataSource(
|
||||
@Value("${jdbc.driverClassName}") String driverClassName,
|
||||
@@ -40,6 +43,7 @@ public class WebAppConfig implements WebMvcConfigurer {
|
||||
return ds;
|
||||
}
|
||||
|
||||
// 配置mybatis工厂
|
||||
@Bean
|
||||
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
|
||||
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
|
||||
@@ -48,11 +52,13 @@ public class WebAppConfig implements WebMvcConfigurer {
|
||||
return factoryBean.getObject();
|
||||
}
|
||||
|
||||
// 配置文件上传
|
||||
@Bean
|
||||
public StandardServletMultipartResolver multipartResolver() {
|
||||
return new StandardServletMultipartResolver();
|
||||
}
|
||||
|
||||
// 添加跨域配置
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
@@ -63,6 +69,17 @@ public class WebAppConfig implements WebMvcConfigurer {
|
||||
.maxAge(3600);
|
||||
}
|
||||
|
||||
// 配置静态资源路径
|
||||
@Autowired
|
||||
private AuthInterceptor authInterceptor;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(authInterceptor)
|
||||
.addPathPatterns("/api/**")
|
||||
.excludePathPatterns("/api/login", "/api/upload", "/api/me", "/api/prodect", "/api/logs");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/**")
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
package com.ycjy.controller;
|
||||
|
||||
import com.ycjy.common.JwtUtil;
|
||||
import com.ycjy.common.Result;
|
||||
import com.ycjy.common.ResultCode;
|
||||
import com.ycjy.dao.DeleteLog;
|
||||
import com.ycjy.dao.Product;
|
||||
import com.ycjy.service.ProductService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
@@ -25,56 +21,48 @@ public class ProductController {
|
||||
@Autowired
|
||||
private ProductService productService;
|
||||
|
||||
// 获取所有商品信息
|
||||
@GetMapping("/prodect")
|
||||
public Result<List<Product>> getProdect() {
|
||||
return Result.success(productService.getAll());
|
||||
}
|
||||
|
||||
// 添加商品
|
||||
@PostMapping("/product")
|
||||
public Result<Void> add(@RequestBody Product product) {
|
||||
productService.add(product);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
// 删除商品
|
||||
@DeleteMapping("/product/{id}")
|
||||
public Result<Void> delete(@PathVariable Integer id,
|
||||
@RequestHeader(value = "Authorization", required = false) String auth) {
|
||||
if (auth == null || !auth.startsWith("Bearer ")) return Result.error(ResultCode.UNAUTHORIZED.getCode(), "请先登录");
|
||||
Claims claims = JwtUtil.parse(auth.substring(7));
|
||||
if (claims == null) return Result.error(ResultCode.UNAUTHORIZED.getCode(), "登录已失效");
|
||||
if (!productService.delete(id, claims.get("username", String.class))) return Result.error("商品不存在");
|
||||
public Result<Void> delete(@PathVariable("id") Integer id, HttpServletRequest request) {
|
||||
// 拦截器放行时已把 username 放进 request
|
||||
String username = (String) request.getAttribute("username");
|
||||
if (!productService.delete(id, username)) return Result.error("商品不存在");
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
// 日志
|
||||
@GetMapping("/logs")
|
||||
public Result<List<DeleteLog>> logs() {
|
||||
return Result.success(productService.getLogs());
|
||||
}
|
||||
|
||||
// 下载商品
|
||||
@GetMapping("/product/{id}/download")
|
||||
public ResponseEntity<byte[]> download(@PathVariable Integer id,
|
||||
@RequestHeader(value = "Authorization", required = false) String auth) {
|
||||
public ResponseEntity<byte[]> download(@PathVariable("id") Integer id) {
|
||||
// 检查是否有这个商品
|
||||
Product product = productService.getById(id);
|
||||
if (product == null || product.getImage() == null) return ResponseEntity.notFound().build();
|
||||
|
||||
if (product.getPrice() > 5000) {
|
||||
if (auth == null || !auth.startsWith("Bearer ")) return ResponseEntity.status(401).build();
|
||||
if (JwtUtil.parse(auth.substring(7)) == null) return ResponseEntity.status(401).build();
|
||||
}
|
||||
|
||||
// 获取文件名
|
||||
String fileName = product.getImage().replaceFirst("^/", "");
|
||||
byte[] bytes;
|
||||
try {
|
||||
ClassPathResource resource = new ClassPathResource("static/" + fileName);
|
||||
if (resource.exists()) {
|
||||
try (InputStream in = resource.getInputStream()) {
|
||||
bytes = in.readAllBytes();
|
||||
}
|
||||
} else {
|
||||
java.io.File diskFile = new java.io.File(System.getProperty("user.dir"), fileName);
|
||||
if (!diskFile.exists()) return ResponseEntity.notFound().build();
|
||||
bytes = java.nio.file.Files.readAllBytes(diskFile.toPath());
|
||||
}
|
||||
java.io.File diskFile = new java.io.File(System.getProperty("user.dir"), fileName);
|
||||
if (!diskFile.exists()) return ResponseEntity.notFound().build();
|
||||
bytes = java.nio.file.Files.readAllBytes(diskFile.toPath());
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).build();
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import com.ycjy.common.Result;
|
||||
import com.ycjy.common.ResultCode;
|
||||
import com.ycjy.dao.User;
|
||||
import com.ycjy.dto.LoginDTO;
|
||||
import com.ycjy.mapper.UserMapper;
|
||||
import com.ycjy.service.UserService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
@@ -28,6 +28,8 @@ create table demo_product
|
||||
image varchar(255) not null
|
||||
)
|
||||
|
||||
UPDATE demo_product SET image = 'upload/a.png' WHERE image = '/a.png';
|
||||
|
||||
-- 模拟商品数据
|
||||
INSERT INTO demo_product (name, p_desc, price, image)
|
||||
VALUES ('iPhone 15', 'Apple最新款智能手机,A16芯片', 5999.00, '/a.png'),
|
||||
|
||||
Reference in New Issue
Block a user