呈现层:Struts 与 JSP
导读
本篇围绕「呈现层:Struts 与 JSP」展开,先给出可以直接复用的结论,再逐步拆解背后的机制。
Struts 1 时代没有注解、没有 REST,全部靠 XML 配置 + 约定。这一篇把这套"古老但严谨"的套路讲清楚:Action 怎么分发、表单怎么绑定、页面怎么复用、权限怎么在页面上生效。
一、Action 层
1.1 DispatchAction:一个 Action 搞定一个模块
普通 Action 只有一个 execute(),增删改查要写四个 Action 类。DispatchAction 通过 parameter 指定的请求参数,把请求分发到同名方法:
<action path="/org"
type="org.springframework.web.struts.DelegatingActionProxy"
name="orgForm"
scope="request"
parameter="method">
<forward name="index" path="/org/index.jsp"/>
<forward name="add_input" path="/org/add_input.jsp"/>
<forward name="select" path="/org/select.jsp"/>
</action>
| URL | 调用方法 |
|---|---|
/org.do |
unspecified()(未指定 method 时的默认方法) |
/org.do?method=add |
add() |
/org.do?method=del&id=7 |
del() |
/org.do?method=updateInput&id=7 |
updateInput() |
典型结构:
public class OrgAction extends BaseAction {
private OrgManager orgManager;
public void setOrgManager(OrgManager orgManager) { this.orgManager = orgManager; }
/** 列表页(默认) */
@Override
protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
OrgActionForm oaf = (OrgActionForm) form;
request.setAttribute("pm", orgManager.findOrgs(oaf.getParentId()));
return mapping.findForward("index");
}
/** 打开新增页 */
public ActionForward addInput(...) {
return mapping.findForward("add_input");
}
/** 提交新增 */
public ActionForward add(...) throws Exception {
OrgActionForm oaf = (OrgActionForm) form;
Organization org = new Organization();
BeanUtils.copyProperties(org, oaf); // 表单 → 实体
orgManager.addOrg(org, oaf.getParentId());
return mapping.findForward("pub_add_success");
}
/** 删除 */
public ActionForward del(...) throws Exception {
orgManager.delOrg(((OrgActionForm) form).getId());
return mapping.findForward("pub_del_success");
}
}
1.2 BaseAction:统一的登录拦截
public class BaseAction extends DispatchAction {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
User user = (User) request.getSession().getAttribute("login");
if (user == null) {
return mapping.findForward("login");
}
return super.execute(mapping, form, request, response);
}
protected User currentUser(HttpServletRequest request) {
return (User) request.getSession().getAttribute("login");
}
}
所有后台 Action 继承它,登录校验零成本。LoginAction 不继承(否则登录页自己也进不去)。
1.3 Action 由 Spring 创建
type 写 DelegatingActionProxy,Struts 会用 path 去 Spring 容器里找同名 Bean(/org),因此依赖可以直接注入。Bean 记得声明 scope="prototype"——Action 有状态,不能单例。
二、ActionForm:表单绑定
2.1 常规写法
public class DocumentActionForm extends ActionForm {
private int id;
private String title;
private String description;
private FormFile contentFile; // 文件上传,Struts 自动封装
private int workflowId; // 选择的流程
private String transitionName; // 选择的流向
private String approveInfo; // 审批意见
private Map props = new HashMap(); // 动态表单的值(见《动态表单与 Freemarker 渲染》)
// getter / setter
}
Struts 会把同名请求参数自动填充进来,包括文件(FormFile)与日期(配合 UtilDateConverter)。
2.2 批量提交:AutoArrayList
动态表单定义时,要一次提交 N 个表单域。问题在于 List.get(index) 越界——Struts 在绑定 fields[3].fieldName 时,List 里可能还是空的。
解法是让 List 自己在访问时补齐元素:
public class AutoArrayList extends ArrayList {
private Class itemClass;
public AutoArrayList(Class itemClass) { this.itemClass = itemClass; }
@Override
public Object get(int index) {
try {
while (index >= size()) {
add(itemClass.newInstance()); // 自动 new 出元素
}
} catch (Exception e) {
e.printStackTrace();
}
return super.get(index);
}
}
ActionForm 中初始化:
private List fields = new AutoArrayList(FormField.class);
public FormField getField(int index) { return (FormField) fields.get(index); }
页面用 fields[0].fieldName、fields[1].fieldName 命名即可,后端无需关心提交了几行。
2.3 表单 → 实体的拷贝
BeanUtils.copyProperties(document, daf); // 同名属性自动拷贝
配合 ConvertUtils 注册的类型转换器处理 Date;文件类型需要手工从 FormFile 取字节数组。
三、JSP 层
3.1 目录组织
按模块建目录,公共页放 common/:
WebRoot/
├── common/
│ ├── pub_add_success.jsp 新增成功提示
│ ├── pub_update_success.jsp 修改成功提示
│ ├── pub_del_success.jsp 删除成功提示
│ └── exception.jsp 异常提示
├── org/ index.jsp add_input.jsp select.jsp
├── person/ index.jsp add_input.jsp
├── user/ index.jsp add_input.jsp user_role_input.jsp
├── acl/ ...
├── document/ ...
├── workflow/ ...
└── index.jsp 登录页 / 后台首页
3.2 公共提示页与全局转发
<global-forwards>
<forward name="pub_add_success" path="/common/pub_add_success.jsp"/>
<forward name="pub_update_success" path="/common/pub_update_success.jsp"/>
<forward name="pub_del_success" path="/common/pub_del_success.jsp"/>
<forward name="login" path="/index.jsp" redirect="true"/>
</global-forwards>
于是每个 Action 的返回值都可以直接 return mapping.findForward("pub_add_success");,不用为每个模块写一份成功页。
redirect="true"用于登录跳转,避免浏览器地址栏还停留在原操作 URL。
3.3 列表页的标准写法
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="pg" uri="http://jsptags.com/tags/navigation/pager" %>
<%@ taglib prefix="my" uri="http://www.example.com/oa/functions" %>
<c:forEach items="${pm.datas}" var="org">
<tr>
<td>${org.id}</td>
<td><a href="org.do?parentId=${org.id}">${org.name}</a></td>
<td>${org.sn}</td>
<td>${org.description}</td>
<td>
<c:if test="${my:hasPermission(login.id,'org',2)}">
<a href="org.do?method=updateInput&id=${org.id}">修改</a>
</c:if>
<c:if test="${my:hasPermission(login.id,'org',3)}">
<a href="org.do?method=del&id=${org.id}">删除</a>
</c:if>
</td>
</tr>
</c:forEach>
3.4 自定义 EL 函数(.tld)
项目把四类页面逻辑封装成 EL 函数,避免 JSP 里写 Java 脚本:
| 函数 | 类 | 用途 |
|---|---|---|
my:hasPermission(userId, sn, permission) |
SecurityFunctions |
权限即时认证 |
my:form(workflowId) |
DynaFormFunction |
渲染某个流程对应的动态表单 |
my:orgTree(orgs) |
OrgTreeFunction |
渲染机构树 |
my:holiday(y,m,d) |
UtilFunction |
判断是否节假日 |
my:splitApply(apply) |
UtilFunction |
把跨天申请拆成多天 |
声明示例:
<taglib>
<tlib-version>1.0</tlib-version>
<short-name>my</short-name>
<uri>http://www.example.com/oa/functions</uri>
<function>
<name>hasPermission</name>
<function-class>com.oa.web.SecurityFunctions</function-class>
<function-signature>boolean hasPermission(int, java.lang.String, int)</function-signature>
</function>
...
</taglib>
注意:函数方法必须是 public static,但依赖注入的 setter 不能是 static(否则 Spring 无法注入实例),所以采用"静态字段 + 非静态 setter"的写法:
public class SecurityFunctions {
private static AclManager aclManager;
public static boolean hasPermission(...) { return aclManager...; }
public void setAclManager(AclManager aclManager) { SecurityFunctions.aclManager = aclManager; }
}
3.5 国际化资源
MessageResources.properties 配合 struts-config.xml 的 <message-resources>,用于异常消息与界面文案:
exception.org.del=该机构下存在子机构(ID:{0}),不允许删除
异常处理器里用 new ActionMessage(key, values) 取出,页面用 <html:errors/> 展示。
四、页面流程设计方法
每个模块的开发,建议先画出页面流转图,再写代码:
列表页 index.jsp
├─[新增]──> 新增页 add_input.jsp ──[提交]──> 公共成功页
├─[修改]──> 修改页 update_input.jsp ──[提交]──> 公共成功页
├─[删除]──> 公共成功页
└─[下钻]──> 带 parentId 回到列表页
公文模块复杂一些:
公文首页(我的公文)
├─[新建公文]──> 选择流程 select_flow.jsp ──> 公文录入页 add_input.jsp
│ └─[提交]──> 创建公文 + 启动流程实例
├─[提交]──> 选择流向 submit_input.jsp ──[确认]──> 流程前进
├─[查看审批历史]──> approve_history.jsp
└─[审批]──> approve_input.jsp ──[保存]──> 写审批意见
先定页面流程,再定 Action 方法名,这样 struts-config.xml 的 forward 很少需要返工。
五、常见坑
| 现象 | 原因 | 解决 |
|---|---|---|
No bean named '/org' is defined |
applicationContext-actions.xml 里 Bean 的 name 与 struts 的 path 不一致 |
两边必须完全一致(含斜杠) |
| Action 之间数据串了 | Action 是单例 | 加 scope="prototype" |
method 参数无效 |
DispatchAction 的 parameter 没配,或方法签名不对 |
方法签名必须是 (ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) |
| 表单提交中文乱码 | 编码过滤器未生效 | 见《通用基础设施:分页、异常与日志》 |
| 日期字段绑定失败 | 未注册 Converter | UtilDateConverterInitServlet |
${pm.total} 为空 |
Action 里没 setAttribute,或用了 redirect | redirect 会丢失 request 属性,改用 forward |
| 越权访问 | 页面隐藏了按钮但服务端没校验 | Action / Manager 内再调 hasPermission |
六、与现在的主流做法对比
| Struts 1 做法 | 现代等价物 |
|---|---|
struts-config.xml 配置 action |
Spring MVC @RequestMapping 注解 |
ActionForm |
方法参数直接绑定 DTO |
DispatchAction + method 参数 |
RESTful 路径与 HTTP 方法 |
| JSP + JSTL | Thymeleaf / Vue / React |
自定义 .tld EL 函数 |
视图层直接调用服务 / 前端组件 |
DelegatingActionProxy |
Spring 原生 MVC,天然由容器管理 |
理解这些对应关系,有助于把老项目的经验平滑迁移到新框架。
要点小结
- 每个模块的开发,建议先画出页面流转图,再写代码: ``` 列表页 index.jsp ├─[新增]──> 新增页 add_input.jsp ──[提交]──> 公共成…
- | 现象 | 原因 | 解决 | |---|---|---| |
No bean named '/org' is defined| `applicationContex… - | Struts 1 做法 | 现代等价物 | |---|---| |
struts-config.xml配置 action | Spring MVC `@Reques…
由站内小编编辑整理