本文是依照参考文档学习时的总结,参考文档原文:Using Struts 2 TagsCoding Struts 2 Actions

Struts 2 url Tag

前面使用的servlet-api-2.5,而2.5中默认不支持EL,所以需要在index.jsp中添加,

1
<%@ page isELIgnored="false"%>

为了方便与JSTL标签对比,在pom.xml中添加,

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

.jsp中taglib指令,

1
2
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
1
2
3
4
5
6
7
<s:url action="hello" var="helloLink">
<s:param name="userName">Bruce Phillips</s:param>
</s:url>
<c:url value="hello.action" var="hello">
<c:param name="userName" value="Bruce Phillips" />
</c:url>

两者都会对URL编码,访问链接${helloLink}${hello}均为.../hello.action?userName=Bruce+Phillips

Struts 2 property tag
1
<s:property value="messageStore" />

如上使用property标签,返回MessageStore对象,默认调用其toString()方法,可以覆盖Object的toString()方法。

Processing Form Input In The Action Class
1
2
3
4
<s:form action="hello">
<s:textfield name="userName" label="Your name" />
<s:submit value="Submit" />
</s:form>

form标签得到的HTML源码为

1
2
3
4
5
6
7
8
9
10
11
12
13
<form id="hello" name="hello" action="/.../hello.action" method="post">
<table class="wwFormTable">
<tr>
<td class="tdLabel"><label for="hello_userName" class="label">Your name:</label></td>
<td><input type="text" name="userName" value="" id="hello_userName"/></td>
</tr>
<tr>
<td colspan="2"><div align="right">
<input type="submit" id="hello_0" value="Submit"/>
</div></td>
</tr>
</table>
</form>

在HelloWorldAction.java中添加

1
2
3
4
5
6
7
8
9
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}

使用setUserName(String userName)方法获得userName参数,类似于Servlet中

1
String userName = request.getParameter("userName");

如果未添加会提示类似错误,

com.opensymphony.xwork2.util.logging.jdk.JdkLogger error
严重: Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting ‘userName’ on ‘class me.struts.ex.helloworld.action.HelloWorldAction: Error setting expression ‘userName’ with value [‘Bruce Phillips ‘, ]

在HelloWorld.jsp中使用,

1
<s:property value="userName" />

可以直接获得userName参数。