J2EE系列之Struts2学习笔记(二)中我们讲述了struts2如何从前台web页面向处理后台发送单个字符串值。这一讲讲一下如何处理传入多个数目不定的字符串。
1.新建一个工程SecondLearnStruts2Chap02_02;
2.新建一个web页面hobby.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="hobby" method="post">
爱好:
<input type="checkbox" name="hobby" value="唱歌"/>唱歌
<input type="checkbox" name="hobby" value="跳舞"/>跳舞
<input type="checkbox" name="hobby" value="睡觉"/>睡觉
<input type="checkbox" name="hobby" value="玩CF"/>玩CF
<input type="submit" value="提交"/>
</form>
</body>
</html>
该页面效果为:
这里要解决一下如何把web页面中选择的数目不定的字符串传给后台处理函数。
3.新建一个后台处理类HobbyAction:
package com.test.action;
import com.opensymphony.xwork2.Action;
public class HobbyAction implements Action{
private String[] hobby;
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String execute() throws Exception {
System.out.println("执行了Action的默认方法");
if(hobby != null){
for(String h:hobby){
System.out.println(h);
}
}
return SUCCESS;
}
}
struts2在这里定义了一个字符串数组hobby来接收前台页面传入的数目不定的字符串。在默认执行函数execute中把前台输入的值打印到控制台中。
4.写配置文件struts.xml:
<struts>
<package name="helloWorld" extends="struts-default">
<action name="hobby" class="com.test.action.HobbyAction">
<result name="success">success.jsp</result>
</action>
</package>
</struts>
5.运行程序:
选择好后点击提交按钮,查看控制台:
可以看到,我们已经把前台输入的多个字符串值传给了后台的hobby字符串数组了。