1.在web.xml定义Filter来拦截用户请求。
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.需要以POST方式提交时定义包含表单数据的JSP页面,如果仅需要以GET方式提交,则无须经过这一步。
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title><s:text name = "loginPage"/></title>
</head>
<body>
<s:form action = "login">
<s:textfield name = "userName" key = "user"/>
<s:textfield name = "password" key = "pass"/>
<s:submit key = "login"/>
</s:form>
</body>
</html>
3.定义处理请求的Action类。
4.配置Action。
<action name="login" class="">
...
</action>
5.配置处理结果与物理视图之间的映射关系。
<action name = "login" class = "com.wj.www.action.LoginAction">
<result name = "error">/WEB-INF/content/error.jsp</result>
<result name = "success">/WEB-INF/content/welcome.jsp</result>
</action>
6.编写视图资源
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="utf-8"%>
<%@taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><s:text name = "errorPage"/></title>
</head>
<body>
<s:text name = "failTip"/>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><s:text name = "successPage"/></title>
</head>
<body>
<s:text name = "succTip">
<s:param>${sessionScope.user}</s:param>
</s:text>
</body>
7注意
国际化.properties文件注意加_zh_CN
空格和占位符不能转为Unicode
否则转不成功
<!-- 指定全局国际化资源文件 -->
<constant name="struts.custom.i18n.resources" value="mess"/>
8.原理
业务控制器只负责返回处理结果,而处理结果与视图的关联,仍由StrutsPrepareAndExcuteFilter来决定。