在Struts2的Action中取得請求參數值的幾種方法
Posted on 2010-10-04 01:44 石子路口 閱讀(586) 評論(0) 編輯 收藏 所屬分類: Java 、網絡教學資源平臺 、struts2轉自:http://lkf520java.javaeye.com/blog/565989
先看GetRequestParameterAction類代碼:
1
public class GetRequestParameterAction extends ActionSupport {
2
3
private String bookName;
4
private String bookPrice;
5
6
public String getBookName() {
7
return bookName;
8
}
9
10
public void setBookName(String bookName) {
11
this.bookName = bookName;
12
}
13
14
public String getBookPrice() {
15
return bookPrice;
16
}
17
18
public void setBookPrice(String bookPrice) {
19
this.bookPrice = bookPrice;
20
}
21
22
23
public String execute() throws Exception{
24
25
26
//方式一: 將參數作為Action的類屬性,讓OGNL自動填充
27
28
System.out.println("方法一,把參數作為Action的類屬性,讓OGNL自動填充:");
29
System.out.println("bookName: "+this.bookName);
30
System.out.println("bookPrice: " +this.bookPrice);
31
32
33
//方法二:在Action中使用ActionContext得到parameterMap獲取參數:
34
ActionContext context=ActionContext.getContext();
35
Map parameterMap=context.getParameters();
36
37
String bookName2[]=(String[])parameterMap.get("bookName");
38
String bookPrice2[]=(String[])parameterMap.get("bookPrice");
39
40
System.out.println("方法二,在Action中使用ActionContext得到parameterMap獲取參數:");
41
System.out.println("bookName: " +bookName2[0]);
42
System.out.println("bookPrice: " +bookPrice2[0]);
43
44
45
//方法三:在Action中取得HttpServletRequest對象,使用request.getParameter獲取參數
46
HttpServletRequest request = (HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST);
47
48
String bookName=request.getParameter("bookName");
49
String bookPrice=request.getParameter("bookPrice");
50
51
System.out.println("方法三,在Action中取得HttpServletRequest對象,使用request.getParameter獲取參數:");
52
System.out.println("bookName: " +bookName);
53
System.out.println("bookPrice: " +bookPrice);
54
return SUCCESS;
55
56
}
57
58
}
59

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

總結:
- 方法一:當把參數作為Action的類屬性,且提供屬性的getter/setter方法時,xwork的OGNL會自動把request參數的值設置到類屬性中,此時訪問請求參數只需要訪問類屬性即可。
- 方法二:可以通過ActionContext對象Map parameterMap=context.getParameters();方法,得到請求參數Map,然后通過parameterMap來獲取請求參數。需要注意的是:當通過parameterMap的鍵取得參數值時,取得是一個數組對象,即同名參數的值的集合。
- 方法三:通過ActionContext取得HttpServletRequest對象,然后使用request.getParameter("參數名")得到參數值。