---
title: "Struts2 ——4、struts2从请求取值的三种方式 "
author: "arne3166"
date: "2010-09-30T17:24:59Z"
tags: ["JSP", "SUN", "Struts", "框架"]
categories: ["企业架构"]
slug: "struts2-4-struts2"
draft: false
lastmod: "2010-09-30T17:28:13Z"
id: 776225
url: "https://arne3166.iteye.com/blog/776225"
---

Struts2作为WEB框架，必不可少的需要请求中取值。（![](/images/smiles/icon_smile.gif)我在这里说是从请求中取值对于一些读者可能有些晦涩，其实如果我说从页面取值可能就好理解一点了，但除了从已经存在的页面里面能够给后台传值，在地址栏里也可以传，甚至在java代码里也是可以的。）

这里就谈谈struts如何从请求中取值。

我介绍三种方式：

三种取值方式：

1，使用默认的action的传递方式。  
2，自定义一个vo，在action中使用这个vo  
3，使用ModelDriven的方式。

 

一、使用默认的action的传递方式

 如果我们的请求里面带有两个参数userName和passWord的话，我们只需要在Action里有这两个私有属性就可以了。

请看我的Action：

```
package study.getValue;
import com.opensymphony.xwork2.Action;
/**
 * 在Action中定义请求里面传过来的值，
 * 并且定义所有的Setter和Getter
 * 这样可以直接在功能方法里面直接使用这些值。
 * @author  arne3166
 * @version  [0100, 2010-9-30]
 */
public class LoginAction
{
    private String userName;//页面里面的userName
    private String passWord;//页面里面的passWord
    //必须的setter和getter方法
    public String getUserName();
    public void setUserName(String userName);
    public String getPassWord();
    public void setPassWord(String passWord);    
    //业务逻辑   
    public String execute()
    {
        if (null!= userName && null != passWord
            && userName.equals("arne3166") && passWord.equals("111111"))
        {
            return Action.SUCCESS;
        }
        else
        {
            return Action.ERROR;
        }
    }
}
```

 在struts .xml里面的配置

```
<action name="loginput" >
	<result>/page/getValue/login_input.jsp</result>
</action>
<action name="login" class="study.getValue.LoginAction">
	<result name="success">/page/getValue/success.jsp</result>
	<result name="error">/page/getValue/fail.jsp</result>
</action>
```

看jsp是怎么写的：

```
<form action="login.action"><!-- name="userName" 和 name="passWord"同Action里面的私有属性对上 -->
用户名：<input name="userName" type="text"/>用户密码<input name="passWord" type="password"/>
<input type="submit" value="提交"/>
</form>
```

 

页面视图

访问路径

http://localhost:8080/struts0100/loginput.action

   
![](http://dl.iteye.com/upload/attachment/322843/2c1589d3-7a06-3fb5-a903-fcd5ce90f2a1.jpg)  
 

 结果页面

```
<!--成功页面 success.jsp-->
<body>
Welcome arne3166!
</body>

<!--失败页面 fail.jsp-->
<body>
You are not the right user!
</body>
```

 效果：当在页面输入arne3166作为用户名并且密码是111111时

![](http://dl.iteye.com/upload/attachment/322961/6ccfb1b4-3ade-3ce0-a539-9219797db344.jpg)

否则

![](http://dl.iteye.com/upload/attachment/322978/c5c1059b-3ca0-319a-b7cd-ed37ab0c4cc2.jpg)

 二、自定义一个vo，在action中使用这个vo

区别于以上的方式，Struts2中允许将页面的值封装起来，放到一个ValueObject（VO）中。就比如上面的例子中的userName和passWord，完全可以放到一个User类中。这样做的好处是，避免如果Action中如果有好多这样的值的话，太多的setter和getter会使得Action看起来比较臃肿的毛病。

看看我们是怎么做的

首先定义User

```
package study.getValue.vo;
public class User
{
    //页面中的值的封装
    private String userName;
    private String passWord;
    //所有的setter和getter
    public String getUserName();
    public void setUserName(String userName);
    public String getPassWord();
    public void setPassWord(String passWord);
}
```

 再看Action被简化成了什么样子

 

```
package study.getValue;
import com.opensymphony.xwork2.Action;
import study.getValue.vo.User;
/**
 *
 * 在Action中定义请求里面传过来Vo，
 * 并且定义VO的Setter和Getter
 * 使用页面参数的时候像使用Vo的属性一样。
 * @author  arne3166
 * @version  [0100, 2010-9-30]
 */
public class VoLoginAction
{
    //将vo作为私有属性
    private User u;
    //setter和getter必不可少
   public User getU();
    public void setU(User u);
    public String execute()
    {
        String userName = u.getUserName();
        String passWord = u.getPassWord();
        if (null!= userName && null != passWord
            && userName.equals("arne3166") && passWord.equals("111111"))
        {
            return Action.SUCCESS;
        }
        else
        {
            return Action.ERROR;
        }
    }
}
```

  

 这样做了，页面任然用原来的当然是不行的，注意到Action中的user对象的引用是u,那么，在页面里面userName也需要修改成u.userName，passWord也应当修改成u.passWord

```
<!--login_input_vo.jsp name="u.passWord"和name="u.passWord"是对Action中User对象进行映射 -->
<form action="loginvo.action">
用户名：<input name="u.userName" type="text"/>用户密码<input name="u.passWord" type="password"/>
<input type="submit" value="提交"/>
</form>
```

 再看看配置文件

 

```
<action name="loginputvo" >
	<result>/page/getValue/login_input_vo.jsp</result>
</action>
<action name="loginvo" class="study.getValue.VoLoginAction">
	<result name="success">/page/getValue/success.jsp</result>
	<result name="error">/page/getValue/fail.jsp</result>
</action>
```

 成功失败后的页面没有什么好修改的。

 

三、使用模型驱动（ModelDriven）的方式。

上面的例子中在页面要写上u.userName，按照习惯前面的“u.”是不是可以不要呢，同时又能保持第二种方式里Action的“纯洁”，Struts2的模型驱动就可以做到。

从实现方式上面需要Action实现模型驱动的接口，先来看Action是怎么写的：

 

```
package study.getValue;
import study.getValue.vo.User;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;
/**
 *
 * Action实现ModelDriven接口。
 * 在Action里定义一个私有变量User，这个User应该被new出来，
 * 不过里面的值是Strus来设置的
 * 不需要Setter和Getter方法
 * @author  arne3166
 * @version  [0100, 2010-9-30]
 */
public class ModelDrivenLoginAction implements ModelDriven<User>
{
    //需要将user对象new出来;
    private User u = new User();
    //实现的接口方法
    @Override
    public User getModel()
    {
        return u;
    }
    public String execute()
    {
        String userName = u.getUserName();
        String passWord = u.getPassWord();
        if (null!= userName && null != passWord
            && userName.equals("arne3166") && passWord.equals("111111"))
        {
            return Action.SUCCESS;
        }
        else
        {
            return Action.ERROR;
        }
    }
}
```

 

下面回到Sturts的配置文件

 

```
<action name="loginputmodeldriven" >
	<result>/page/getValue/login_input_modeldriven.jsp</result>
</action>
<action name="loginmodeldriven" class="study.getValue.ModelDrivenLoginAction">
	<result name="success">/page/getValue/success.jsp</result>
	<result name="error">/page/getValue/fail.jsp</result>
</action>
```

 

再看表单的页面

 

```
<!--又回到原始简单的样式了O(∩_∩)O-->
<form action="loginmodeldriven.action">
用户名：<input name="userName" type="text"/>用户密码<input name="passWord" type="password"/>
<input type="submit" value="提交"/>
</form>
```

 

 这里注意一下，

这是必须的

//需要将user对象new出来;  
private User u = new User();

 如果不将user new出来的话，会在页面给你一个异常吃吃![](/images/smiles/icon_wink.gif)

 

```
Struts Problem Report
Struts has detected an unhandled exception: 

Messages:  
File: study/getValue/ModelDrivenLoginAction.java 
Line number: 23 


--------------------------------------------------------------------------------

Stacktraces
java.lang.NullPointerException 
    study.getValue.ModelDrivenLoginAction.execute(ModelDrivenLoginAction.java:23)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    
```

  下面附上我的代码。