初學 SSH 搭建項目時,常遇到三個實戰問題:JSP 混寫 Java 代碼、數據庫文本前端換行失效、圖片存數據庫還是磁盤。本文給出生產級解決方案。
錯誤做法:在 `index.jsp` 直接 `new Dao()` 查詢並 `session.setAttribute`
正確分層:
// 1. Controller (Struts2 Action)
public class IndexAction extends ActionSupport {
@Autowired private NewsService newsService;
private List newsList;
public String execute() {
newsList = newsService.getLatest(10);
return SUCCESS;
}
// getter/setter
}
// 2. struts.xml
/WEB-INF/jsp/index.jsp
// 3. JSP (純展示)
${news.title}
核心原則:JSP 僅做展示,業務邏輯在 Service,數據訪問在 DAO,控制器調度。首頁訪問走 `index.action` 而非直接 `index.jsp`。
原因:HTML 忽略換行符,需轉為 `
` 或 CSS `white-space: pre-wrap`
方案對比:
| 方案 | 優點 | 缺點 |
|---|---|---|
| 存儲時替換 `\n`→` ` | 前端直接輸出 | 污染原始數據,編輯困難 |
| 前端 CSS `white-space: pre-wrap` | 保持原始數據,零處理 | 需防 XSS,配合 `escapeXml="false"` |
| 前端 JS 替換渲染 | 可控性強 | 需額外渲染邏輯 |
推薦:存儲原始文本,前端 `
結論:文件存磁盤/對象存儲 (OSS),數據庫存路徑 URL
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
String ext = FilenameUtils.getExtension(file.getOriginalFilename());
String filename = UUID.randomUUID() + "." + ext;
Path path = Paths.get(uploadDir, filename);
Files.copy(file.getInputStream(), path);
return "https://cdn.example.com/" + filename; // 返回 URL 存 DB
}