整合作业
This commit is contained in:
@@ -36,5 +36,4 @@ public class JwtUtil {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.ycjy.common;
|
||||
|
||||
|
||||
public final class UploadConstants {
|
||||
public static final String UPLOAD_DIR = "Z:/Edg浏览器默认下载位/sctplu";
|
||||
|
||||
private UploadConstants() {
|
||||
}
|
||||
}
|
||||
@@ -16,11 +16,12 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
@Autowired
|
||||
private ProductService productService;
|
||||
|
||||
// 拦截器,检查请求是否合法
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
String method = request.getMethod();
|
||||
String uri = request.getRequestURI();
|
||||
String auth = request.getHeader("Authorization");
|
||||
String method = request.getMethod();// 请求方法
|
||||
String uri = request.getRequestURI();// 请求 URI
|
||||
String auth = request.getHeader("Authorization");// 请求头 Authorization
|
||||
|
||||
// 已登录就把 username 放进 request,供 Controller 取用
|
||||
Claims claims = parse(auth);
|
||||
|
||||
@@ -19,7 +19,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import com.ycjy.common.UploadConstants;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@@ -84,7 +86,10 @@ public class WebAppConfig implements WebMvcConfigurer {
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/**")
|
||||
.addResourceLocations("classpath:/static/");
|
||||
// 固定目录:图片放在部署目录之外,重新编译/部署也不会丢;用 toUri 编码中文路径
|
||||
String uploadLocation = Path.of(UploadConstants.UPLOAD_DIR).toUri().toString();
|
||||
if (!uploadLocation.endsWith("/")) uploadLocation += "/";
|
||||
registry.addResourceHandler("/upload/**")
|
||||
.addResourceLocations("file:Z:/Spring-study/Spring-ZY-crud/upload/");
|
||||
.addResourceLocations(uploadLocation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.ycjy.controller;
|
||||
|
||||
import com.ycjy.common.Result;
|
||||
import com.ycjy.common.UploadConstants;
|
||||
import com.ycjy.dao.DeleteLog;
|
||||
import com.ycjy.dao.Product;
|
||||
import com.ycjy.service.ProductService;
|
||||
@@ -34,6 +35,13 @@ public class ProductController {
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
// 修改商品
|
||||
@PostMapping("/update/product")
|
||||
public Result<Void> update(@RequestBody Product product) {
|
||||
productService.update(product);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
// 删除商品
|
||||
@DeleteMapping("/product/{id}")
|
||||
public Result<Void> delete(@PathVariable("id") Integer id, HttpServletRequest request) {
|
||||
@@ -56,18 +64,18 @@ public class ProductController {
|
||||
Product product = productService.getById(id);
|
||||
if (product == null || product.getImage() == null) return ResponseEntity.notFound().build();
|
||||
|
||||
// 获取文件名
|
||||
String fileName = product.getImage().replaceFirst("^/", "");
|
||||
String imagePath = product.getImage().replaceFirst("^/", "");
|
||||
String fileName = imagePath.substring(imagePath.lastIndexOf('/') + 1);
|
||||
byte[] bytes;
|
||||
try {
|
||||
java.io.File diskFile = new java.io.File("Z:/Spring-study/Spring-ZY-crud", fileName);
|
||||
java.io.File diskFile = new java.io.File(UploadConstants.UPLOAD_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();
|
||||
}
|
||||
|
||||
String downloadName = URLEncoder.encode(fileName.substring(fileName.lastIndexOf('/') + 1), StandardCharsets.UTF_8);
|
||||
String downloadName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
|
||||
headers.setContentDispositionFormData("attachment", downloadName);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.ycjy.controller;
|
||||
|
||||
import com.ycjy.common.Result;
|
||||
import com.ycjy.common.UploadConstants;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@@ -19,7 +20,8 @@ public class UploadController {
|
||||
String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String fileName = UUID.randomUUID().toString().replace("-", "") + ext;
|
||||
|
||||
File dir = new File("Z:/Spring-study/Spring-ZY-crud/upload");
|
||||
// 固定目录:放在部署目录之外,重新编译/部署也不会丢失图片
|
||||
File dir = new File(UploadConstants.UPLOAD_DIR);
|
||||
if (!dir.exists()) dir.mkdirs();
|
||||
file.transferTo(new File(dir, fileName));
|
||||
|
||||
|
||||
@@ -10,4 +10,5 @@ public interface ProductMapper {
|
||||
Product getById(@Param("id") Integer id);
|
||||
int deleteById(@Param("id") Integer id);
|
||||
int insert(Product product);
|
||||
int update(@Param("id") Integer id, @Param("name") String name, @Param("p_desc") String p_desc, @Param("price") Double price, @Param("image") String image);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ public class ProductService {
|
||||
return productMapper.insert(product) > 0;
|
||||
}
|
||||
|
||||
// 删除
|
||||
public boolean delete(Integer id, String username) {
|
||||
if (productMapper.getById(id) == null) return false;
|
||||
productMapper.deleteById(id);
|
||||
@@ -35,7 +36,13 @@ public class ProductService {
|
||||
return productMapper.getById(id);
|
||||
}
|
||||
|
||||
// 获取日志
|
||||
public List<DeleteLog> getLogs() {
|
||||
return logMapper.getAll();
|
||||
}
|
||||
|
||||
// 修改
|
||||
public boolean update(Product product) {
|
||||
return productMapper.update(product.getId(),product.getName(),product.getP_desc(),product.getPrice(),product.getImage()) > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,3 +47,7 @@ create table demo_log
|
||||
pid varchar(20),
|
||||
delete_date datetime default now()
|
||||
)
|
||||
|
||||
|
||||
update demo_product set name = '755', p_desc = '766', price = 5555, image = '/upload/64d8c676487c494ea7e3941dcc870bb3.jpg' where id = 22;
|
||||
select * from demo_product
|
||||
@@ -14,8 +14,12 @@
|
||||
<delete id="deleteById">
|
||||
DELETE FROM demo_product WHERE id = #{id}
|
||||
</delete>
|
||||
<insert id="insert" parameterType="com.ycjy.dao.Product" useGeneratedKeys="true" keyProperty="id">
|
||||
<insert id="insert" parameterType="com.ycjy.dao.Product">
|
||||
INSERT INTO demo_product (name, p_desc, price, image)
|
||||
VALUES (#{name}, #{p_desc}, #{price}, #{image})
|
||||
</insert>
|
||||
<update id="update" parameterType="com.ycjy.dao.Product">
|
||||
UPDATE demo_product SET name = #{name}, p_desc = #{p_desc}, price = #{price}, image = #{image}
|
||||
WHERE id = #{id};
|
||||
</update>
|
||||
</mapper>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 82 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 136 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 82 KiB |
+81
-1
@@ -61,6 +61,8 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
.btn-danger:hover { background: color-mix(in oklab, var(--color-error) 10%, transparent); }
|
||||
.btn-ghost { color: var(--color-ink-2); border-color: var(--color-rule); }
|
||||
.btn-ghost:hover { background: var(--color-paper-2); }
|
||||
.btn-edit { color: var(--color-accent-ink); border-color: color-mix(in oklab, var(--color-accent-2) 55%, transparent); background: color-mix(in oklab, var(--color-accent) 10%, transparent); }
|
||||
.btn-edit:hover { background: color-mix(in oklab, var(--color-accent) 22%, transparent); }
|
||||
|
||||
.login-status { display: inline-block; padding: var(--space-2xs) var(--space-sm); border-radius: var(--radius-pill); font-size: var(--text-xs); color: var(--color-ink-2); background: var(--color-paper-2); border: 1px solid var(--color-rule); }
|
||||
.login-status.logged-in { color: var(--color-accent-ink); background: color-mix(in oklab, var(--color-accent) 16%, var(--color-paper)); border-color: color-mix(in oklab, var(--color-accent) 35%, transparent); }
|
||||
@@ -165,6 +167,24 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="editModalOverlay">
|
||||
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="editTitle">
|
||||
<h2 id="editTitle">编辑商品</h2>
|
||||
<label for="editName">名称</label>
|
||||
<input type="text" id="editName" placeholder="商品名称">
|
||||
<label for="editDesc">描述</label>
|
||||
<input type="text" id="editDesc" placeholder="商品描述">
|
||||
<label for="editPrice">价格</label>
|
||||
<input type="number" id="editPrice" placeholder="0.00" step="0.01">
|
||||
<label for="editImage">图片(不选择则保留原图)</label>
|
||||
<input type="file" id="editImage" accept="image/*" style="padding-top: 6px;">
|
||||
<div class="modal-actions">
|
||||
<button class="btn btn-ghost" id="cancelEdit">取消</button>
|
||||
<button class="btn btn-primary" id="confirmEdit">保存</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>
|
||||
@@ -187,6 +207,7 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
let token = localStorage.getItem('token');
|
||||
let username = localStorage.getItem('username');
|
||||
let products = [];
|
||||
let editingProduct = null;
|
||||
|
||||
const isLoggedIn = () => !!token;
|
||||
|
||||
@@ -287,6 +308,12 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
downloadBtn.onclick = () => handleDownload(p, price);
|
||||
tdAction.appendChild(downloadBtn);
|
||||
|
||||
const editBtn = document.createElement('button');
|
||||
editBtn.className = 'btn btn-edit';
|
||||
editBtn.textContent = '编辑';
|
||||
editBtn.onclick = () => showEdit(p);
|
||||
tdAction.appendChild(editBtn);
|
||||
|
||||
const delBtn = document.createElement('button');
|
||||
delBtn.className = 'btn btn-danger';
|
||||
delBtn.textContent = '删除';
|
||||
@@ -472,6 +499,52 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 编辑商品 ==========
|
||||
function showEdit(product) {
|
||||
editingProduct = product;
|
||||
$('editName').value = product.name || '';
|
||||
$('editDesc').value = product.p_desc || '';
|
||||
$('editPrice').value = product.price ?? '';
|
||||
$('editImage').value = '';
|
||||
$('editModalOverlay').style.display = 'flex';
|
||||
$('editName').focus();
|
||||
}
|
||||
function hideEdit() {
|
||||
$('editModalOverlay').style.display = 'none';
|
||||
}
|
||||
|
||||
async function doEdit() {
|
||||
const name = $('editName').value.trim();
|
||||
const desc = $('editDesc').value.trim();
|
||||
const price = parseFloat($('editPrice').value);
|
||||
const fileInput = $('editImage');
|
||||
|
||||
if (!name) return alert('请输入商品名称');
|
||||
if (isNaN(price)) return alert('请输入有效价格');
|
||||
|
||||
const btn = $('confirmEdit');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
let image = editingProduct.image || '';
|
||||
if (fileInput.files.length) {
|
||||
image = await uploadImage(fileInput.files[0]);
|
||||
}
|
||||
const res = await fetch(`${API}/update/product`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id: editingProduct.id, name, p_desc: desc, price, image })
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.code !== 200) throw new Error(result.message || '保存失败');
|
||||
hideEdit();
|
||||
await loadProducts();
|
||||
} catch (e) {
|
||||
alert('保存失败:' + e.message);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 登录弹窗 ==========
|
||||
function showLogin() {
|
||||
$('modalOverlay').style.display = 'flex';
|
||||
@@ -536,8 +609,15 @@ tbody tr:hover { background: var(--color-paper-2); }
|
||||
$('addModalOverlay').onclick = e => {
|
||||
if (e.target === $('addModalOverlay')) hideAdd();
|
||||
};
|
||||
$('cancelEdit').onclick = hideEdit;
|
||||
$('confirmEdit').onclick = doEdit;
|
||||
$('editModalOverlay').onclick = e => {
|
||||
if (e.target === $('editModalOverlay')) hideEdit();
|
||||
};
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape' && $('modalOverlay').style.display === 'flex') hideLogin();
|
||||
if (e.key !== 'Escape') return;
|
||||
if ($('modalOverlay').style.display === 'flex') hideLogin();
|
||||
if ($('editModalOverlay').style.display === 'flex') hideEdit();
|
||||
});
|
||||
|
||||
// ========== 初始化 ==========
|
||||
|
||||
Reference in New Issue
Block a user