2.Using Struts 2 Tags


本系列文章均为自我学习而作

针对于第一篇的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)

                                                                                   Struts 2 Form
<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方法(猜测))

Add Static Field
private static int helloCount = 0;
	
public int getHelloCount() {
	return helloCount;
}

public void setHelloCount(int helloCount) {
	HelloWorldAction.helloCount = helloCount;

}
这块是添加在HelloWorldAction.java里的,是用来表示访问次数的值(注意getHelloCount是不能设置为static的)

Increase helloCount
helloCount++;
在execute方法中添加以上代码用来计数

Use Property Tag To Display helloCount Value
<p>I've said hello <s:property value="helloCount" /> times!</p>

在helloworld.jsp中加入以上代码来进行计数器的显示工作

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中添加:

Add toString Method To Class MessageStore
public String toString() {
		
	return message + " (from toString)";
		
}	
然后修改HelloWorld.jsp删除messageStore后面的message。刷新页面看下就会发现调用的是toString方法了。


tag方法如果大家有兴趣的话可以去搜索struts2 tag帮助文档来查看,谢谢各位~


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值