PrintWriter out = response.getWriter();
out.println(result);
out.flush();
out.close(); // ❌ 不要手動 close,容器會管理
out.close():關閉 Writer 會提交回應並禁止後續寫入,導致 Filter/Wrapper 異常。response.setContentType("application/json;charset=UTF-8"); 必須在 getWriter() 之前。charset 與 JVM/資料庫一致,建議統一 UTF-8。getOutputStream() 則不能再呼叫 getWriter(),二者互斥。@Override
protected void doExecute(String location, ActionInvocation inv) throws Exception {
HttpServletResponse response = (HttpServletResponse) inv.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
String contentType = "application/json;charset=UTF-8";
response.setContentType(contentType);
try (PrintWriter out = response.getWriter()) {
String result = (String) inv.getStack().findValue("jsonResult");
out.write(result);
out.flush(); // 可選,容器會自動 flush
}
}
繼承 StrutsResultSupport 實作 execute 而非 doExecute,利用框架內建序列化支援 (JSON/GSON) 簡化代碼。