本篇主要有:设置struts2匹配的扩展名,使用通配符,值栈,声明式异常以及标签。
设置扩展名:
默认是对.action和不加任何扩展名的进行处理。可以设置:
<constant name="struts.action.extension" value="action,do,"></constant>//对.action,.do和不加任何的拦截
为了简化action的配置,可以使用通配符,大致写法如下:
<action name="user_*" class="jsky.action.ActionTestAction" method="{1}"> <result name="success" >/pages/{1}.jsp</result> <result name="error" >/pages/error2.jsp</result> </action>规则:优先匹配无通配符的,若多个通配符的action,按先后顺序{1}{2}第一,二个字符串
值栈:
存放action的堆栈,分为对象栈和Map栈
对象栈: 访问方式:object.propertyName ; object[‘propertyName‘] ; object["propertyName"]
对象可以通过一个从零开始的下标来引用. ObjectStack 里的栈顶对象可以用 [0] 来引用,
它下面的那个对象可以用 [1] 引用,从[0]个对象开始向下搜索匹配的对象
Name:<s:property value="[0].name"/>
Pass:<s:property value="pass"/>
Map栈:里边保存着各种 Map:requestMap, sessionMap, applicationMap, parametersMap, attr
访问方式:#object.propertyName ; #object[‘propertyName‘] ; #object["propertyName"]
session:<s:property value="#session.sessionKey2"/>
声明式异常:
指定action出异常时去的页面 ,大致用法是:
result指定异常后去的页面,exception指的是发生的异常类型
<action name="actiontest2" class="jsky.action.ActionTestAction" method="log"> <exception-mapping result="error" exception="java.lang.ArithmeticException"></exception-mapping> <result name="success" >/pages/show2.jsp</result> <result name="error" >/pages/error2.jsp</result> </action>
struts2带额标签特别多,这里简单提一下:
<!-- URL标签 --> <s:url value="/testurl" var="url"> <s:param name="testId" value="110"></s:param> </s:url> ${url } <hr> 自动对value值OGNL解析,若希望输入字符串有效,加'' <s:url value="/testurl" var="url2"> <s:param name="testId" value="testId"></s:param> </s:url> ${url } <hr> <s:url value="/testurl" var="url3"> <s:param name="testId" value="'testId'"></s:param> </s:url> ${url3 } <hr> 构建请求action的字符串 <s:url action="testAction" namespace="/hello" method="login" var="url4"></s:url> ${url4}
<s:iterator value="#request.users"> ${name }:${pass }<br> </s:iterator>
核心的代码如下:
input.jsp
<body> <s:form action="Regis_save"> <s:textfield name="name" label="Name"> </s:textfield> <s:password name="password" label="Password"></s:password> <s:radio name="gender" list="#{'1':'male','0':'femal'}" label="Gender"></s:radio> <s:select name="department" list="#request.department" listKey="departmentId" listValue="departmentName" label="Department"></s:select> <s:checkboxlist name="role" list="#request.role" listKey="roleId" listValue="roleName" label="Role"></s:checkboxlist> <s:submit value="submit"></s:submit> </s:form> </body>welcome.jsp:
<body> Name: ${name }<br> Pass:${password }<br> Gender:${gender }<br> Department: ${department }<br> Role:${role } </body>主要的action:
public String input() { request.put("department", dao.getDept()); request.put("role", dao.getRole()); return "input"; } public String save() { return "success"; } private Map<String, Object> request; @Override public void setRequest(Map<String, Object> arg0) { // TODO Auto-generated method stub this.request=arg0; }
原文地址:http://blog.csdn.net/js_sky/article/details/44455713