Struts2的开发方式以及对表单数据的获取和封装

版权声明: https://blog.csdn.net/Mister_yang/article/details/80692927

一。action的三种开发方式

(1)不实现任何接口,不继承任何类除了Object类
<package name="hello" namespace="/" extends="struts-default">
		<action name="helloAction_sys" class="cn.ies.struts2.HelloAction" method="sys">
			<result name="sys">/sys.jsp</result>
		</action>
		<action name="helloAction_show" class="cn.ies.struts2.HelloAction" method="show">
			<result name="show">/show.jsp</result>
		</action>
	</package>

package cn.ies.struts2;

public class HelloAction {
	
	public String sys() {
		System.out.println(this.getClass().getName()+"----sys()");
		return "sys";
	}
	
	public String show() {
		System.out.println(this.getClass().getName()+"----show()");
		return "show";
	}

}

        (2)创建类,实现接口Action。

package cn.ies.struts2;

import com.opensymphony.xwork2.Action;

public class UserAction implements Action{

	@Override
	public String execute() throws Exception {
		System.out.println(this.getClass().getName()+"----");
		return SUCCESS;
	}
}
<action name="userAction" class="cn.ies.struts2.UserAction">
			<result name="success">/add.jsp</result>
		</action>


        (3)创建类,继承ActionSupport类。(开发中最常用的方式)

package cn.ies.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class PersonAction  extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	public String execute() throws Exception {
		return NONE;
	}

	public String sys() {
		System.out.println("action...................");
		return NONE;
	}
	
	public String add() {
		System.out.println("add............");
		return "add";
	}
	public String update() {
		System.out.println("update........");
		return NONE;
	}
	public String delete() {
		System.out.println("delete..........");
		return NONE;
	}
	public String select() {
		System.out.println("select..........");
		return NONE;
	}
}
<action name="personAction" class="cn.ies.struts2.PersonAction" method="add">
	<result name="add">/add.jsp</result>
</action>


二,struts操作三大域对象

    编写操作对象类

package cn.ies.struts2;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class ResponseDataAction extends  ActionSupport{
	@Override
	public String execute() throws Exception {
		/*
		 * request域
		 * */
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("username", "tom");
		//session
		request.getSession().setAttribute("password", "password");
		//servletContext
		ServletContext context = ServletActionContext.getServletContext();
		context.setAttribute("age", 10);
		return SUCCESS;
	}
}

在核心配置文件的package下添加如下配置。

<action name="responseData" class="cn.ies.struts2.ResponseDataAction">
	<result name="success">/data.jsp</result>
</action>

data.jsp文件,显示发送数据的内容。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
	<h1>request:${username }</h1>
	<h1>session:${password }</h1>
	<h1>servletContext:${age }</h1>
</body>
</html>


三。action获取表单提交数据的三种方式

(1)使用ActionContext类
ActionContext context = ActionContext.getContext();
Map<String, Object> map = context.getParameters();
Set<String> set = map.keySet();
for(String key:set) {
Object obj[] = (Object[]) map.get(key);
System.out.println(Arrays.toString(obj));

}

        表单界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
	<form action="${pageContext.request.contextPath }/form1.action" method="post">
		<label for="username">username</label>
		<input type="text" name="username" id="username"/><br/>
		
		<label for="password">password</label>
		<input type="password" name="password" id="password"/><br/>
		<input type="submit" value="submit" />
	</form>
</body>
</html>
        编写action类。
package cn.ies.form;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.eclipse.jdt.internal.compiler.ast.SuperReference;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class Form1Action extends ActionSupport {
	/**
	 * 使用ActionContext类的对象获取数据。
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public String execute() throws Exception {
		//获取actionContext;
		ActionContext context = ActionContext.getContext();
		Map<String, Object> map = context.getParameters();
		Set<String> set = map.keySet();
		for(String key:set) {
			Object obj[] = (Object[]) map.get(key);
			System.out.println(Arrays.toString(obj));
		}
		
		return SUCCESS;
	}
}

        使用分模块开发模式,新建form1.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>
	
	<!-- post请求方式 -->
	<constant name="struts.iln8.encoding" value="utf-8"></constant>

	<package name="form1" extends="struts-default" namespace="/">
	
		<action name="form1"  class="cn.ies.form.Form1Action">
			<result name="success">/hello.jsp</result>
		</action>
	
	</package>	
</struts>

        在核心配置文件中引入新建的配置文件。

<include file="cn/ies/form/form1.xml"></include>


        从运行结果可以看出,通过ActionContext类,可以获取表单上的数据。

(2)使用ServletActionContext类
HttpServletRequest request = ServletActionContext.getRequest();
String username = request.getParameter("username");
String password = request.getParameter("password");

System.out.println("username"+":"+username+"\t password"+":"+password);

            编写表单数据获取类;

package cn.ies.form;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class Form2Action extends ActionSupport{

	/**
	 * 使用ServletActionContext获取request对象,由request对象获取表单中的信息。
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public String execute() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("username"+":"+username+"\t password"+":"+password);
		return "success";
	}
}

        新建form2.xml文件,配置Form2Action的类信息。

<?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>
	
	<!-- post请求方式 -->
	<constant name="struts.iln8.encoding" value="utf-8"></constant>

	<package name="form2" extends="struts-default" namespace="/">
	
		<action name="form2"  class="cn.ies.form.Form2Action">
			<result name="success">/hello.jsp</result>
		</action>
	
	</package>	
</struts>

        在struts2的核心配置文件中引入form2.xml文件。

	<include file="cn/ies/form/form2.xml"></include>

        在我们一般开发中,相对于这三种获取表单的数据的方式,用的最多的就是这一种,但是耦合性很高。如果考虑到数据的封装,会有其他的方式,下面我们将数据封装的时候会讲到。

(3)使用接口注入方式
实现ServletRequestAware接口;
package cn.ies.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

public class Form3Action extends ActionSupport implements ServletRequestAware{

	/**
	 * 通过实现ServletRequestAware接口获取表单的数据
	 */
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	@Override
	public String execute() throws Exception {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("username:" +username);
		System.out.println("password:"+password);
		return SUCCESS;
	}
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

}

        新建form3.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>
	
	<!-- post请求方式 -->
	<constant name="struts.iln8.encoding" value="utf-8"></constant>

	<package name="form3" extends="struts-default" namespace="/">
	
		<action name="form3"  class="cn.ies.form.Form3Action">
			<result name="success">/hello.jsp</result>
		</action>
	
	</package>	
</struts>

        在struts的核心配置文件中引入form3.xml文件。

<include file="cn/ies/form/form3.xml"></include>

        由上面三种实现方式可以看出,方式二相对来说比较简单,也是我们最基本的开发方式。

四,Struts2对数据的封装。

    1)原始数据的封装

        既然是数据封装,那一定会有实体类,那么我们先建一个实体类,它有两个属性username和password

package cn.ies.data;

public class User {
	private String username;
	private String password;
	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;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + "]";
	}
}
package cn.ies.data;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DataDemo3Action extends ActionSupport{
	/**
	 *原始代码数据封装 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	public String execute() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		System.out.println(user.toString());
		return SUCCESS;
	}
}

        新建配置文件data3.xml文件。并在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>
	
	<!-- post请求方式 -->
	<constant name="struts.iln8.encoding" value="utf-8"></constant>

	<package name="data3" extends="struts-default" namespace="/">
	
		<action name="data3"  class="cn.ies.data.DataDemo3Action">
			<result name="success">/hello.jsp</result>
		</action>
	
	</package>	
</struts>
<include file="cn/ies/data/data3.xml"></include>

2)struts2数据封装的三种方式

    <1>属性封装
a>在action的成员变量中定义变量
变量名称和表单输入项的name属性值一样
b>生成变量的set的方法(set和get的方法)
c>:说明,使用属性封装获取表单数据到属性里面,不能把数据

直接封装到实体类对象里面

package cn.ies.data;

import com.opensymphony.xwork2.ActionSupport;

/*
 * 使用属性封装,获取输入值
 * */
public class DataDemo1Action extends ActionSupport {
	/*
	 * 变量名称和表单的输入项name值一致。
	 * */
	private String username;
	private String password;
		
	
	
	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;
	}



	@Override
	public String execute() throws Exception {
		
		System.out.println(username+"\t"+password);
		
		return SUCCESS;
	}
}

<2>模型驱动封装
直接将表单的数据封装到实体类对象中。
a>action实现接口ModelDriven<T>
b>实现接口里面的方法getModel,把c步对象返回

c>在actin里面创建实体类对象。

                        d>:注意的问题
模型驱动封装和属性封装不能同时获取一个form
表单信息,同时使用时,只会执行模型驱动,不会执行属性封装

package cn.ies.data;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/*
 * 使用属性封装,获取输入值
 * */
public class DataDemo2Action extends ActionSupport implements ModelDriven<User>{
	private User  user = new User();
	@Override
	public User getModel() {
		return user;
	}
	@Override
	public String execute() throws Exception {
		System.out.println(user.toString());
		return SUCCESS;
	}
}

<3>表达式封装
                a>.在action里面声明实体类,注意是声明;
b>、生成实体类变量的set和get方法。

c>.在表单输入项中name的属性值里面写形式表达式user.username

        

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
	<form action="${pageContext.request.contextPath }/data4.action" method="post">
		<label for="username">username</label>
		<input type="text" name="user.username" id="username"/><br/>
		
		<label for="password">password</label>
		<input type="password" name="user.password" id="password"/><br/>
		<input type="submit" value="submit" />
	</form>
</body>
</html>
<?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>
	
	<!-- post请求方式 -->
	<constant name="struts.iln8.encoding" value="utf-8"></constant>

	<package name="data4" extends="struts-default" namespace="/">
	
		<action name="data4"  class="cn.ies.data.DataDemo4Action">
			<result name="success">/hello.jsp</result>
		</action>
	
	</package>	
</struts>

package cn.ies.data;

import com.opensymphony.xwork2.ActionSupport;

/*
 * 使用
 * */
public class DataDemo4Action extends ActionSupport {

	private User user;

	public User getUser() {
		return user;
	}


	public void setUser(User user) {
		this.user = user;
	}
	
	@Override
	public String execute() throws Exception {
		
		System.out.println(user.toString());
		
		return SUCCESS;
	}


	
}

我们比较常用的表单数据的获取和封装就是以上几种了。接下来我么来介绍一下将数据封装到map和list集合之中。

五,将表单数据封装到List以及Map集合中

        由前面我们已经知道,我们可以通过表达式的形式将表单的数据封装到单个实体类中,那么如果是多个实体类,如何单个封装就不可以了,这时候struts2为我们提供了封装list集合和map集合。

    (1)List集合的封装

        a>.在action里面声明List<User> list,注意是声明不是创建
b>、生成List集合变量的set和get方法。
c>.在表单输入项中name的属性值里面写形式表达式
list[0].username list[0].password

list[1].username list[1].password

===============================================================

        表单:list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/list.action" method="post">
		<label for="username1">username</label>
		<input type="text" name="list[0].username" id="username1"/><br/>
		
		<label for="password1">password</label>
		<input type="password" name="list[0].password" id="password1"/><br/>
		<hr/>
		<label for="username2">username</label>
		<input type="text" name="list[1].username" id="username2"/><br/>
		
		<label for="password2">password</label>
		<input type="password" name="list[1].password" id="password2"/><br/>
		
		<input type="submit" value="submit" />

</form>
</body>
</html>
            action
package cn.ies.other;

import java.util.Arrays;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

import cn.ies.data.User;

public class ListAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//声明list集合,并提供set和get的方法。
	private List<User> list;
	
	public void setList(List<User> list) {
		this.list = list;
	}
	public List<User> getList() {
		return list;
	}
	@Override
	public String execute() throws Exception {
		System.out.println(list.toString());
		return SUCCESS;
	}
}

list.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>
	
	<!-- post请求方式 -->
	<constant name="struts.iln8.encoding" value="utf-8"></constant>

	<package name="list" extends="struts-default" namespace="/">
	
		<action name="list"  class="cn.ies.other.ListAction">
			<result name="success">/hello.jsp</result>
		</action>
	
	</package>	
</struts>

============================================================================

(2)将数据封装到map集合中。

                a>.在action里面声明Map<String,User> map,注意是声明不是创建
b>、生成Map<String,User>变量的set和get方法。
c>.在表单输入项中name的属性值里面写形式表达式
map['user1'].username map['user1'].password

map['user2'].username map['user2'].password

                                     ==============================

    jsp界面:map.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/map.action" method="post">
		<label for="username1">username</label>
		<input type="text" name="map['user1'].username" id="username1"/><br/>
		
		<label for="password1">password</label>
		<input type="password" name="map['user1'].password" id="password1"/><br/>
		<hr/>
		<label for="username2">username</label>
		<input type="text" name="map['user2'].username" id="username2"/><br/>
		
		<label for="password2">password</label>
		<input type="password" name="map['user2'].password" id="password2"/><br/>
		
		<input type="submit" value="submit" />

</form>
</body>
</html>
        action
package cn.ies.other;

import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;

import cn.ies.data.User;

public class MapAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Map<String,User> map;

	public Map<String, User> getMap() {
		return map;
	}

	public void setMap(Map<String, User> map) {
		this.map = map;
	}
	@Override
	public String execute() throws Exception {
		System.out.println(map.toString());
		
		return SUCCESS;struts2数据封装Demo下载
	}
}

        新建配置文件map.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>
	
	<!-- post请求方式 -->
	<constant name="struts.iln8.encoding" value="utf-8"></constant>

	<package name="map" extends="struts-default" namespace="/">
	
		<action name="map"  class="cn.ies.other.MapAction">
			<result name="success">/hello.jsp</result>
		</action>
	
	</package>	
</struts>

总结:struts提供了五种数据封装的模式,在开发中,经常使用的是第二种,但是遇到多个实例封装的时候,显然是满足不了的,多实例封装时,使用第三种:表达式封装

六:详细Demo下载地址:Strust2数据封装详解Demo下载

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页