整合作业
This commit is contained in:
@@ -9,8 +9,8 @@ import java.util.Date;
|
||||
|
||||
public class JwtUtil {
|
||||
private static final String SECRET = "ycjy-learning-secret-key-32bytes!!"; // 密钥
|
||||
private static final SecretKey KEY = Keys.hmacShaKeyFor(SECRET.getBytes());
|
||||
private static final long EXPIRE_MS = 24 * 60 * 60 * 1000L;
|
||||
private static final SecretKey KEY = Keys.hmacShaKeyFor(SECRET.getBytes()); // 密钥对象
|
||||
private static final long EXPIRE_MS = 24 * 60 * 60 * 1000L; // 过期时间
|
||||
|
||||
public static String generate(Integer userId, String username) {
|
||||
Date now = new Date();
|
||||
|
||||
@@ -14,8 +14,10 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.File;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@@ -46,6 +48,11 @@ public class WebAppConfig implements WebMvcConfigurer {
|
||||
return factoryBean.getObject();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public StandardServletMultipartResolver multipartResolver() {
|
||||
return new StandardServletMultipartResolver();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
@@ -60,5 +67,7 @@ public class WebAppConfig implements WebMvcConfigurer {
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/**")
|
||||
.addResourceLocations("classpath:/static/");
|
||||
registry.addResourceHandler("/upload/**")
|
||||
.addResourceLocations("file:" + System.getProperty("user.dir") + File.separator + "upload" + File.separator);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.ycjy.config;
|
||||
|
||||
import jakarta.servlet.MultipartConfigElement;
|
||||
import jakarta.servlet.ServletRegistration;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
@@ -18,4 +20,9 @@ public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServlet
|
||||
protected String[] getServletMappings() {
|
||||
return new String[]{"/"};
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
|
||||
registration.setMultipartConfig(new MultipartConfigElement(""));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,12 @@ public class ProductController {
|
||||
return Result.success(getProdect.getProdectAll());
|
||||
}
|
||||
|
||||
@PostMapping("/product")
|
||||
public Result<Void> add(@RequestBody Product product) {
|
||||
productService.add(product);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
/** 删除商品,必须登录;DELETE /api/product/{id} */
|
||||
@DeleteMapping("/product/{id}")
|
||||
public Result<Void> delete(@PathVariable("id") Integer id,
|
||||
@@ -53,49 +59,48 @@ public class ProductController {
|
||||
return Result.success(logMapper.getAll());
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载商品图片
|
||||
* GET /api/product/{id}/download
|
||||
*/
|
||||
/** 下载:价格 > 5000 必须登录,其余免登录 */
|
||||
@GetMapping("/product/{id}/download")
|
||||
public ResponseEntity<byte[]> download(@PathVariable("id") Integer id,
|
||||
@RequestHeader(value = "Authorization", required = false) String auth) {
|
||||
// 1. 校验登录
|
||||
if (auth == null || !auth.startsWith("Bearer ")) {
|
||||
return ResponseEntity.status(401).build();
|
||||
}
|
||||
Claims claims = JwtUtil.parse(auth.substring(7));
|
||||
if (claims == null) {
|
||||
return ResponseEntity.status(401).build();
|
||||
}
|
||||
|
||||
// 2. 查商品
|
||||
Product product = productService.getById(id);
|
||||
if (product == null || product.getImage() == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
if (product == null || product.getImage() == null) return ResponseEntity.notFound().build();
|
||||
|
||||
// 价格超过 5000 必须登录
|
||||
if (product.getPrice() > 5000) {
|
||||
if (auth == null || !auth.startsWith("Bearer ")) return ResponseEntity.status(401).build();
|
||||
Claims claims = JwtUtil.parse(auth.substring(7));
|
||||
if (claims == null) return ResponseEntity.status(401).build();
|
||||
}
|
||||
|
||||
// 3. 从 classpath 读文件
|
||||
// product.getImage() 形如 "/a.png",去掉开头的 "/" 变成 "a.png"
|
||||
String fileName = product.getImage().replaceFirst("^/", "");
|
||||
byte[] bytes = null;
|
||||
|
||||
// 先找 classpath:/static/(老图片 /a.png)
|
||||
ClassPathResource resource = new ClassPathResource("static/" + fileName);
|
||||
if (!resource.exists()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
try (InputStream in = resource.getInputStream()) {
|
||||
byte[] bytes = in.readAllBytes();
|
||||
|
||||
// 4. 告诉浏览器"这是附件,请下载"
|
||||
String downloadName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
|
||||
headers.setContentDispositionFormData("attachment", downloadName);
|
||||
headers.setContentLength(bytes.length);
|
||||
|
||||
return ResponseEntity.ok().headers(headers).body(bytes);
|
||||
try {
|
||||
if (resource.exists()) {
|
||||
try (InputStream in = resource.getInputStream()) {
|
||||
bytes = in.readAllBytes();
|
||||
}
|
||||
} else {
|
||||
// 再找磁盘 upload 目录(新上传图片 upload/xxx.png)
|
||||
java.io.File diskFile = new java.io.File(System.getProperty("user.dir"), fileName);
|
||||
if (diskFile.exists()) {
|
||||
bytes = java.nio.file.Files.readAllBytes(diskFile.toPath());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).build();
|
||||
}
|
||||
|
||||
if (bytes == null) return ResponseEntity.notFound().build();
|
||||
|
||||
String downloadName = URLEncoder.encode(fileName.substring(fileName.lastIndexOf('/') + 1), StandardCharsets.UTF_8);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
|
||||
headers.setContentDispositionFormData("attachment", downloadName);
|
||||
headers.setContentLength(bytes.length);
|
||||
return ResponseEntity.ok().headers(headers).body(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,4 +9,5 @@ public interface ProductMapper {
|
||||
List<Product> getProdectAll();
|
||||
Product getById(@Param("id") Integer id);
|
||||
int deleteById(@Param("id") Integer id);
|
||||
int insert(Product product);
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
// 获取商品
|
||||
@Service
|
||||
public class ProductService {
|
||||
@Autowired
|
||||
@@ -20,6 +19,10 @@ public class ProductService {
|
||||
return getProdect.getProdectAll();
|
||||
}
|
||||
|
||||
public boolean add(Product product) {
|
||||
return getProdect.insert(product) > 0;
|
||||
}
|
||||
|
||||
public boolean delete(Integer id, String username) {
|
||||
Product product = getProdect.getById(id);
|
||||
if (product == null) return false;
|
||||
|
||||
@@ -14,4 +14,8 @@
|
||||
<delete id="deleteById">
|
||||
DELETE FROM demo_product WHERE id = #{id}
|
||||
</delete>
|
||||
<insert id="insert" parameterType="com.ycjy.dao.Product" useGeneratedKeys="true" keyProperty="id">
|
||||
INSERT INTO demo_product (name, p_desc, price, image)
|
||||
VALUES (#{name}, #{p_desc}, #{price}, #{image})
|
||||
</insert>
|
||||
</mapper>
|
||||
+88
-7
@@ -104,6 +104,9 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
<h1 id="products-heading">商品管理</h1>
|
||||
<div class="status" id="statusText">加载商品中…</div>
|
||||
</div>
|
||||
<div style="padding: var(--space-sm) var(--space-lg); border-bottom: 1px solid var(--color-rule); display: flex; justify-content: flex-end;">
|
||||
<button id="addProductBtn" class="btn btn-primary">新增商品</button>
|
||||
</div>
|
||||
<div class="error" id="errorBox" role="alert"></div>
|
||||
<div class="table-wrap">
|
||||
<table id="productTable" style="display:none;">
|
||||
@@ -144,6 +147,24 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div class="modal-overlay" id="addModalOverlay">
|
||||
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="addTitle">
|
||||
<h2 id="addTitle">新增商品</h2>
|
||||
<label for="addName">名称</label>
|
||||
<input type="text" id="addName" placeholder="商品名称">
|
||||
<label for="addDesc">描述</label>
|
||||
<input type="text" id="addDesc" placeholder="商品描述">
|
||||
<label for="addPrice">价格</label>
|
||||
<input type="number" id="addPrice" placeholder="0.00" step="0.01">
|
||||
<label for="addImage">图片</label>
|
||||
<input type="file" id="addImage" accept="image/*" style="padding-top: 6px;">
|
||||
<div class="modal-actions">
|
||||
<button class="btn btn-ghost" id="cancelAdd">取消</button>
|
||||
<button class="btn btn-primary" id="confirmAdd">保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="modalOverlay">
|
||||
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="loginTitle">
|
||||
<h2 id="loginTitle">用户登录</h2>
|
||||
@@ -284,16 +305,18 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
showLogin();
|
||||
return;
|
||||
}
|
||||
if (!isLoggedIn()) {
|
||||
alert('请先登录');
|
||||
showLogin();
|
||||
return;
|
||||
const headers = {};
|
||||
if (price > 5000) {
|
||||
if (!isLoggedIn()) {
|
||||
alert('该商品价格超过 5000 元,请先登录');
|
||||
showLogin();
|
||||
return;
|
||||
}
|
||||
headers['Authorization'] = 'Bearer ' + token;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API}/product/${p.id}/download`, {
|
||||
headers: { 'Authorization': 'Bearer ' + token }
|
||||
});
|
||||
const res = await fetch(`${API}/product/${p.id}/download`, { headers });
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) throw new Error('登录已失效,请重新登录');
|
||||
throw new Error('HTTP ' + res.status);
|
||||
@@ -397,6 +420,58 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
});
|
||||
}
|
||||
|
||||
// ========== 新增商品 ==========
|
||||
function showAdd() {
|
||||
$('addModalOverlay').style.display = 'flex';
|
||||
$('addName').value = '';
|
||||
$('addDesc').value = '';
|
||||
$('addPrice').value = '';
|
||||
$('addImage').value = '';
|
||||
$('addName').focus();
|
||||
}
|
||||
function hideAdd() {
|
||||
$('addModalOverlay').style.display = 'none';
|
||||
}
|
||||
|
||||
async function uploadImage(file) {
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
const res = await fetch(`${API}/upload`, { method: 'POST', body: fd });
|
||||
const result = await res.json();
|
||||
if (result.code !== 200) throw new Error(result.message || '上传失败');
|
||||
return result.data.url;
|
||||
}
|
||||
|
||||
async function doAdd() {
|
||||
const name = $('addName').value.trim();
|
||||
const desc = $('addDesc').value.trim();
|
||||
const price = parseFloat($('addPrice').value);
|
||||
const fileInput = $('addImage');
|
||||
|
||||
if (!name) return alert('请输入商品名称');
|
||||
if (isNaN(price)) return alert('请输入有效价格');
|
||||
if (!fileInput.files.length) return alert('请选择图片');
|
||||
|
||||
const btn = $('confirmAdd');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const url = await uploadImage(fileInput.files[0]);
|
||||
const res = await fetch(`${API}/product`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, p_desc: desc, price, image: url })
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.code !== 200) throw new Error(result.message || '保存失败');
|
||||
hideAdd();
|
||||
await loadProducts();
|
||||
} catch (e) {
|
||||
alert('保存失败:' + e.message);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 登录弹窗 ==========
|
||||
function showLogin() {
|
||||
$('modalOverlay').style.display = 'flex';
|
||||
@@ -455,6 +530,12 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
$('modalOverlay').onclick = e => {
|
||||
if (e.target === $('modalOverlay')) hideLogin();
|
||||
};
|
||||
$('addProductBtn').onclick = showAdd;
|
||||
$('cancelAdd').onclick = hideAdd;
|
||||
$('confirmAdd').onclick = doAdd;
|
||||
$('addModalOverlay').onclick = e => {
|
||||
if (e.target === $('addModalOverlay')) hideAdd();
|
||||
};
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape' && $('modalOverlay').style.display === 'flex') hideLogin();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user