Struts2使用OGNL表示式封裝輸入資料(直接封裝Map型別)
阿新 • • 發佈:2019-02-15
struts2使用OGNL表示式封裝資料,不僅支援物件,而且還支援諸如List,Map的容器
User.java
package HelloWorld;publicclass User {
private String username;
private String password;
private String[] books;
public String[] getBooks() {
return books;
}
publicvoid setBooks(String[] books)
this.books = books;
}
public String getUsername() {
return username;
}
publicvoid setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
this.password = password;
}
}
LoginAction.java
package HelloWorld;import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
publicclass LoginAction implements Action{
private String tip;
private Map<String,User> users;
public Map<String, User> getUsers() {
return users;
}
publicvoid setUsers(Map<String, User> users) {
this.users = users;
}
public String execute() throws Exception{
//用第一個user做邏輯判斷
if(this.getUsers().get("one").getUsername().equals("admin")&&this.getUsers().get("one").getPassword().equals("1234")){
ActionContext.getContext().getSession().put("user", this.getUsers().get("one").getUsername());
BookService bs=new BookService();
this.getUsers().get("one").setBooks(bs.getBooks());
this.setTip("welcome welcome");
return SUCCESS;
}else{
return ERROR;
}
}
public String getTip() {
return tip;
}
publicvoid setTip(String tip) {
this.tip = tip;
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=gb2312"pageEncoding="gb2312"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title></title>
</head>
<body>
<s:form action="Login">
<s:textfield name="users['one'].username" key="username"></s:textfield>
<s:textfield name="users['one'].password" key="password"></s:textfield>
<s:textfield name="users['two'].username" key="username"></s:textfield>
<s:textfield name="users['two'].password" key="password"></s:textfield>
<s:submit value="login"></s:submit>
</s:form>
</body>
</html>
上面使用users['one'].username直接將輸入資料封裝成Map容器中的兩個物件