struts2中模型化獲取表單資料
阿新 • • 發佈:2018-11-09
class屬性:action全路徑,對應伺服器的路徑
method屬性:action裡面預設執行的方法execute方法,
(3)result標籤
name屬性:和方法返回值一樣
type屬性: 配置如何到路徑中(轉發/dispatch或者重定向/redirect)
- 表單對應實體類
package bean; public class User { private String name; private String age; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", address=" + address + "]"; } }
-
表單提交的伺服器
package test; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import bean.User; public class InputDemo extends ActionSupport implements ModelDriven<User> { private User user = new User(); @Override public User getModel() { // TODO Auto-generated method stub return user; } public String getUser() { System.out.println(user); return "ok"; } }
伺服器類繼承ActionSupport 實現 ModelDriven介面,建立一個User實體類並 重寫getModel方法得到表單封裝資料
-
struts2核心配置檔案
<?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="hellodemo" extends="struts-default" namespace="/"> <action name="getUser" class="test.InputDemo" method="getUser"> <result name="ok" type="redirect">/jsp/Success.jsp</result> </action> </package> </struts>
(1)package標籤
name屬性:
name屬性值根功能本身沒有關係的,
- 在一個配置檔案中可以寫多個package標籤,name屬性值不能相同的
extends屬性
屬性值固定的,struts-default
- 寫了這個屬性之後,在package裡面配置的類具有action功能
namespace屬性:namespace屬性值和action標籤裡面的name屬性值構成訪問路徑
(2)action標籤
name屬性:
namespace屬性值和action標籤裡面的name屬性值構成訪問路徑
在package標籤裡面寫多個action標籤,但是action的name屬性值不能相同的
-
web.xml
<filter> <description>配置struts2的核心過濾器</description> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping>
-
填表頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="../getUser.action" method="post"> 姓名:<input type="text" name="name"/></br> 年齡:<input type="text" name="age"/></br> 地址:<input type="text" name="address"/></br> <input type="submit" value="提交"> </form> </body> </html>