您的位置:首页 > 编程语言 > Java开发

Struts2,spring前台后台的数据传递及配置解析

2014-06-27 09:49 295 查看
刚接触SSH,确实感觉到他的强大和便捷。在学习过程中遇到了一些困惑,解决后想要写写,在自己以后的编程中尽量避免,并帮助一些菜鸟朋友快速入门。

Struts2前台后台的数据传递问题,我要分两方面说,首先,我要说后台数据如何通过前台用户输入来获取的。至于Struts2跳转流程这里不做介绍。首先,Struts利用Action来接收前台数据,他继承了ActionSupport类。在前台中,假设有username和password两个属性,如:

<body>

<form action="login.action">

用户名:<input type="text" name="username"/></br>

密码:<input type="password" name="password"/></br>

<input type="submit" value="注册"/>

</form>

<a href="list.action">查询用户列表</a>

</body>

===========================================================================

1. jsp中链接可以引入struts2的标签

<%@ taglib prefix="s" uri="/struts-tags" %>

<s:url id="url" action="login"></s:url> ----url标记,类型为struts2的action名

<s:a href="%{url}">首页</s:a> ------引用{url}地址

或者采用引入s:url

<a href="<s:url action="login"/>">首页</a>

2.标记在struts.xml中<action name="login" class="loginAction" method="isLogin">method可以指定为loginAction类中的isLogin。

3.action可由spring容器托管,

<bean id="loginAction" class="XXX.XXX.loginAction">

<property name="loginServiceIpml" ref="loginServiceIp"></property>

<property name="student" ref="user"></property>

</bean>

loginServiceIpml和student为spring的Ioc策略引用的对象。

================================================================================================

那么在对应Action中,如LoginAction中,想要接收用户输入的信息,就必须有和前台接收参数同名的属性,按上述代码,LoginAction中必须有username和password两个属性。其次,为了能够获取属性,还要为这两个属性设置特有的get()set()方法,这样Struts2才能调用这两个方法对属性获取。第三,在获取时,直接写属性名就可以。当然,LoginAction要实现ActionSupport。如:

public String execute(){

confirm.add(username, password);

System.out.println(username);

System.out.println(password);

return "success";

}

这样在前台用户输入的信息就能被后台获取了。

第二我要说的是如何在前台获取后台的数据。首先,要用Action访问Servlet API。这里不作为重点,只提供一种方法,即ServletActionContext访问Servlet API。

public String list(){

List list=confirm.list();

ActionContext ct=ActionContext.getContext();

ct.put("box", list);

return "list";

}

用ActionContext.getContext()方法得到PageContext对象。ct.put()方法是将list链表放到名为“box”的里面。box名是任意的。这样就可以在前台获取了。

<table>

<s:iterator value="box" id="li">

<tr>

<td><s:property value="#li.username"/></td>

<td><s:property value="#li.password"/></td>

<td><a href="delete.action?id=<s:property value="#li.id"/>">删除用户</a><td>

</tr>

</s:iterator>

</table>

上面用到Struts2标签,这里不做解释,请查API。iterator用来遍历集合。value值就是后台用put()方法放入的名称,上题是box。property是输出单一属性,value为输出内容。这里重点说一下OGNL表达式。

OGNL为表达式,用来显示对象属性。用OGNL显示属性有两种:

1、当访问OGNL的Stack context里根对象的属性时,可以省略对象名。

如:若foo为context的根对象,假设foo有blah属性,前台获取该属性时,只需写:

blah;//调用了foo的getBlah()方法返回属性值。

2、当访问OGNL的Stack context里非根对象的属性时,要用#对象名.属性访问。

如:#person.name

下面的问题就是如何确定哪些是OGNL的Stack context里根对象,进而选择用哪种方法。

引用-转自:http://blog.csdn.net/a1165117473/article/details/6962244
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐