接收表单参数
1. 在Action中定义表单属性
<form action="login" method="post" name="form">
User:<s:textfield name="username"/><br/>
Password:<s:password name="password"/><br/>
<s:submit value="提交"/>
</form>
在Action中定义
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
2. 表单参数封装成类
<form action="login" method="post" name="form">
User:<s:textfield name="user.username"/><br/>
Password:<s:password name=" user.password"/><br/>
<s:submit value="提交"/>
</form>
Model类
public class test {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
在Action中定义Model对象
private User user;
public getUser(){
return user;
}
public void setUser(User user){
this.user=user;
}
3. 实现ModelDriven接口
表单及Model、Action中User定义与上面相同,对Action类:
public class loginAction extends ActionSupport implements ModelDriven<User>{
User user=new User();
...
public Users getModel()
{
return user;
}
}
在View显示Action中的变量
在Action定义
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
然后在jsp中,
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:property value="username" />
或
String username = (String) request.getAttribute("username");
获取Session
方法1
在前一篇文章已有介绍,这里简要再记录一下
private RbacAdmins rbacAdmin;
public RbacAdmins getRbacAdmin() {
return rbacAdmin;
}
public void setRbacAdmin(RbacAdmins rbacAdmin) {
this.rbacAdmin = rbacAdmin;
}
@Override
public String execute() throws Exception {
ActionContext actionContext = ActionContext.getContext();
Map session = actionContext.getSession();
rbacAdmin =(RbacAdmins)session.get(Session.ADMIN);
return "APP";
}
方法2(代码未测试)
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class SessionTest1Action extends ActionSupport implements SessionAware {
private Map session;
public void setSession(Map session) {
this.session = session;
}
public String execute() {
this.session.put("USER_NAME", "Test User 1");
return SUCCESS;
}
}