從值棧獲取對象
-------------------siwuxie095
從值棧獲取對象
1、具體步驟
(1)在 Action 中向值棧放對象
(2)在 JSP 頁面中從值棧獲取對象
2、具體實現
(1)編寫實體類
User.java:
package com.siwuxie095.entity;
// User 實體類 public class User {
private String username; private String password; private String address;
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; }
public String getAddress() {
return address; } public void setAddress(String address) { this.address = address; }
@Override public String toString() { return "User [username=" + username + ", password=" + password + ", address=" + address + "]"; }
} |
(2)編寫 Action
ObjectAction.java:
package com.siwuxie095.action;
import com.opensymphony.xwork2.ActionSupport; import com.siwuxie095.entity.User;
public class ObjectAction extends ActionSupport {
/* * (1) 在 Action 中定義實體類對象 * * 因為總歸是要 new 的,所以就在這 * 裏創建,而不是聲明了 */ private User user=new User();
/* * (2) 提供實體類對象的 get 方法即可 */ public User getUser() { return user; }
@Override public String execute() throws Exception {
/* * 如果上面僅僅是聲明了實體類對象, * 那麽就要在這裏創建,即 new 出來 */
/* * (3) 在執行的方法中,向實體類對象中設置值 */
user.setUsername("siwuxie095"); user.setPassword("8888"); user.setAddress("China");
return SUCCESS; } } |
(3)配置 Action
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="demo" extends="struts-default" namespace="/">
<action name="object" class="com.siwuxie095.action.ObjectAction"> <result name="success">/object.jsp</result> </action>
</package>
</struts> |
(4)編寫頁面
object.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 引入 Struts2 標簽庫 --> <%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Object</title> </head> <body>
<!-- 獲取值棧中實體類對象的值 --> <s:property value="user.username"></s:property> <s:property value="user.password"></s:property> <s:property value="user.address"></s:property>
</body> </html> |
(5)訪問路徑
http://localhost:8080/工程名/object.action
【made by siwuxie095】
從值棧獲取對象