<jsp:setProperty name="beanId" property="*"/> 會:**遍歷請求所有參數**,依名稱匹配 Bean 的 setXxx() 方法,**自動型別轉換** (String → int/boolean/Date 等) 並調用 setter。這是 JSP 內建的**表單綁定框架**雛形。
form.html<form action="process.jsp" method="post">
姓名:<input type="text" name="name"><br>
年齡:<input type="text" name="age"><br>
<input type="submit" value="提交">
</form>
SimpleBean.javapackage javabean01;
public class SimpleBean implements java.io.Serializable {
private String name;
private int age;
public SimpleBean() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
process.jsp<%@ page contentType="text/html;charset=gbk" %>
<% request.setCharacterEncoding("gbk"); %> <!-- 解決中文亂碼 -->
<jsp:useBean id="simple" class="javabean01.SimpleBean" scope="request">
<jsp:setProperty name="simple" property="*"/> <!-- 自動綁定所有參數 -->
</jsp:useBean>
<html><body>
<h3>姓名:<jsp:getProperty name="simple" property="name"/></h3>
<h3>年齡:<jsp:getProperty name="simple" property="age"/></h3>
</body></html>
setProperty 使用模式對比| 模式 | 語法 | 適用場景 | 型別轉換 |
|---|---|---|---|
| **全自動映射** | property="*" | 表單欄位與屬性一一對應,最常用 | 自動 (String→目標型別) |
| **指定屬性** | property="name" | 僅綁定特定屬性,其它手工處理 | 自動 |
| **參數重命名** | property="userName" param="name" | 請求參數名與屬性名不一致時 | 自動 |
| **固定值注入** | property="status" value="active" | 預設值、隱性欄位、安全標記 | 字串字面值 |
JSP 內建轉換器僅支援基本型別。複雜型別 (Date、Enum、自訂類) 需:
public void setBirth(String s) { this.birth = new SimpleDateFormat("yyyy-MM-dd").parse(s); }PropertyEditor/Converter。<%@ page pageEncoding="UTF-8" %>request.setCharacterEncoding("UTF-8") (必須在讀取參數前)。server.xml:<Connector URIEncoding="UTF-8" /> (GET 參數)。useUnicode=true&characterEncoding=UTF-8。// Spring MVC Controller
@PostMapping("/process")
public String process(@Valid UserForm form, BindingResult br, Model m) {
if (br.hasErrors()) return "form";
service.save(form);
return "redirect:/success";
}
// UserForm (Java 16 Record)
public record UserForm(
@NotBlank @Size(max=20) String name,
@Min(1) @Max(150) int age
) {}
**聲明式驗證 + Record 不可變 + 重導向結束**,比 JSP 手工綁定安全、簡潔得多。