本系列文章均为自我学习而作
针对于第一篇的helloworld进行的部分解释及优化过程。
如果未阅读第一篇请移步:hello world using struts2
一个非常常用的跳转链接方式就是index.jsp中的 hello.action来跳转链接这其中其实使用了struts2的tag(s:url)跳转(自动对value加入action后缀名)
那我们现在添加更多的link试试
index.jsp
<s:url action="hello" var="helloLink">
<s:param name="userName">Bruce Phillips</s:param>
</s:url>
<p><a href="${helloLink}">Hello Bruce Phillips</a></p>
//这里利用了EL表达式引用s:url中的var=“helloLink”这里是自己写的,请无视
比起把它当作值来用,struts2 tag提供了一种更好的方法就是给他一个名字(var)然后通过引用这个名字来添加进入你需要的地方
我们把我们的s:url和href分离了,嵌套在s:url标签中的是s2的参数标签。 此标签阐述了参数的名字(就像其中的userName)和他的具体值(Bruce Phillips)。
这里要记住的就是那个s:url中的var属性。这个属性的值就是一个在我们之后的代码中提到的那个url的创建有关的一个参数。
测试上述的锚标签(anchor tag)。记住href的属性是${helloLink}(总算提到了)。这个超链接页面将会成为我们创造使用的{helloLink}参数的url tag一个代替品。
意思基本上就是:造一个var名字,用这个var名字代替原来的在href嵌入s:url,来达到分离效果(这块确实不错)
同时他可以附带参数,什么userName也是会被传进去的
eg:http://localhost:8080/Struts2-HelloWorld/hello.action?userName=Bruce+Phillips
我们的userName被传进去了。相当于超链接带参传递
(下一节我们将讲到struts2是如何实现带参传递这个标签的。)
既然介绍了超链接带参传递,不得不提的就是与之相对的传递方式,表单传参
以下介绍的是struts2的form标签(tag)
<p>Get your own personal hello by filling out and submitting this form.</p>
<s:form action="hello">
<s:textfield name="userName" label="Your name" />
<s:submit value="Submit" />
</s:form>
接下来说的是转型。s:property是可以把大部分形式都转换成string的(通过toString方法(猜测))
private static int helloCount = 0;
public int getHelloCount() {
return helloCount;
}
public void setHelloCount(int helloCount) {
HelloWorldAction.helloCount = helloCount;
}
helloCount++;
<p>I've said hello <s:property value="helloCount" /> times!</p>
the note:Note that even though helloCount is a static field, the get and set methods for helloCount are not static. For Struts 2 to call the getHelloCount method to get the value of helloCount, the getHelloCount method cannot be static.
就是说getHelloCount方法是不能设置为static的,因为他是struts2用来取得HelloCount值的。
重写toString
如果在action中的get方法取得的值是一个对象,property标签就会导致去调用对象的toString方法了,当然,你常常应该去覆盖toString方法在你的模型层内,
请在MessageStore class中添加:
public String toString() {
return message + " (from toString)";
}
tag方法如果大家有兴趣的话可以去搜索struts2 tag帮助文档来查看,谢谢各位~