Struts2 模糊查詢包含兩層:Action 接收參數 與 DAO 執行 SQL。前端提交關鍵字,Action 透傳至 Service/DAO,SQL 拼接 LIKE 條件返回結果。
@Action(value = "search", results = { @Result(name = "success", location = "/result.jsp") })
public String execute() {
// 接收前端傳遞的關鍵字
String keyword = request.getParameter("keyword");
// 調用 Service 查詢
List<Record> list = recordService.fuzzySearch(keyword);
// 放入值棧供 JSP 顯示
ActionContext.getContext().put("recordList", list);
return SUCCESS;
}
public List<Record> fuzzySearch(String keyword) {
String sql = "SELECT * FROM records WHERE title LIKE ? OR content LIKE ?";
String param = "%" + keyword + "%";
return jdbcTemplate.query(sql, new Object[]{param, param}, new BeanPropertyRowMapper<>(Record.class));
}
關鍵點:
PreparedStatement 參數化查詢,防止 SQL 注入% 在 Java 代碼中拼接,而非 SQL 字串拼接OR 連接,必要時加全文索引優化<form action="search.action" method="post">
<input type="text" name="keyword" placeholder="輸入關鍵字">
<input type="submit" value="查詢">
</form>
<c:forEach items="${recordList}" var="r">
<div>${r.title} - ${r.content}</div>
</c:forEach>