---
title: "转贴--在Struts2的Action中取得请求参数值的几种方法"
author: "xvm03"
date: "2010-10-27T18:33:25Z"
tags: []
categories: ["企业架构"]
slug: "struts2-action"
draft: false
lastmod: "2010-10-27T18:52:32Z"
id: 795819
url: "https://xvm03.iteye.com/blog/795819"
---

### [在Struts2的Action中取得请求参数值的几种方法](http://lkf520java.iteye.com/blog/565989)

**文章分类:[Java编程](http://www.iteye.com/blogs/category/java)**

先看GetRequestParameterAction类代码： 

Java代码 

01. **public** **class** GetRequestParameterAction **extends** ActionSupport {
02. **private** String bookName;
03. **private** String bookPrice;
04. **public** String getBookName() {
05. **return** bookName;
06. }
07. **public** **void** setBookName(String bookName) {
08. **this**.bookName = bookName;
09. }
10. **public** String getBookPrice() {
11. **return** bookPrice;
12. }
13. **public** **void** setBookPrice(String bookPrice) {
14. **this**.bookPrice = bookPrice;
15. }
16. **public** String  execute() **throws** Exception{
17. //方式一： 将参数作为Ａction的类属性，让OGNL自动填充
18. System.out.println("方法一，把参数作为Action的类属性,让OGNL自动填充：");
19. System.out.println("bookName: "+**this**.bookName);
20. System.out.println("bookPrice: " +**this**.bookPrice);
21. //方法二:在Action中使用ActionContext得到parameterMap获取参数:
22. ActionContext context=ActionContext.getContext();
23. Map  parameterMap=context.getParameters();
24. String bookName2\[]=(String\[])parameterMap.get("bookName");
25. String bookPrice2\[]=(String\[])parameterMap.get("bookPrice");
26. System.out.println("方法二，在Action中使用ActionContext得到parameterMap获取参数：");
27. System.out.println("bookName: " +bookName2\[0]);
28. System.out.println("bookPrice: " +bookPrice2\[0]);
29. //方法三:在Action中取得HttpServletRequest对象，使用request.getParameter获取参数
30. HttpServletRequest request = (HttpServletRequest)context.get(ServletActionContext.HTTP\_REQUEST);
31. String bookName=request.getParameter("bookName");
32. String bookPrice=request.getParameter("bookPrice");
33. System.out.println("方法三，在Action中取得HttpServletRequest对象，使用request.getParameter获取参数：");
34. System.out.println("bookName: " +bookName);
35. System.out.println("bookPrice: " +bookPrice);
36. **return** SUCCESS;
37. }
38. }

总结：

- 方法一：当把参数作为Action的类属性，且提供属性的getter/setter方法时，xwork的OGNL会自动把request参数的值设置到类属性中，此时访问请求参数只需要访问类属性即可。
  
  方法二：可以通过ActionContext对象Map  parameterMap=context.getParameters();方法，得到请求参数Map，然后通过parameterMap来获取请求参数。需要注意的是：当通过parameterMap的键取得参数值时，取得是一个数组对象，即同名参数的值的集合。
  
  方法三：通过ActionContext取得HttpServletRequest对象，然后使用request.getParameter("参数名")得到参数值