FormBean中使用Map map接收参数

 

a.编写jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="html" uri="http://jakarta.apache.org/struts/tags-html" %>
<!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>
 <table boder="1" bordercolor="green" width="100%">
  <html:form action="/general.do?method=loadArea" method="post">
     <tr>
       <td>用户名:</td>
       <td>
         <html:text property="value(name)"></html:text>  
       </td>
     </tr> 
     <tr>
       <td>密码:</td>
       <td>
        <html:text property="value(password)"></html:text>
        </td>
     </tr>
     <tr>
     <td colspan="2">
       <html:submit value="submit"></html:submit>
     </td>
     </tr>
  </html:form>
  </table>
</body>
</html>

 

b.编写一个ActionForm

package com.hsp.form;

import java.util.HashMap;
import java.util.Map;

import org.apache.struts.action.ActionForm;

public class MapForm extends ActionForm{
	
	private Map<String, Object> myMap = new HashMap<String, Object>();
	
	
	public void setValue(String key, Object value){
		if(key != null && value != null){
			myMap.put(key, value);
		}
	}
	
	public Object getValue(String key){
		if(key != null){
		   return myMap.get(key);
		}else{
			return null;
		}
		
	}

}

 

c.编写Action

package com.hsp.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.hsp.bean.Area;
import com.hsp.form.MapForm;

public class GeneralAction extends DispatchAction{
	

	public ActionForward loadArea(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	   
		MapForm mapForm = (MapForm)form;
		
		String name =  (String)mapForm.getValue("name");
		String password = (String)mapForm.getValue("password");
		String name2 = request.getParameter("value(name)"); //也可以这么取值
//		String password = request.getParameter("password");
		System.out.println("name2:"+name2);
		System.out.println(name);
		System.out.println(password);
		
		List<Area> areas = new ArrayList<Area>();
		Area area1 = new Area("hubei", "湖北");
		Area area2 = new Area("hunan", "湖南");
		Area area3 = new Area("guangdong", "广东");
		Area area4 = new Area("sichuan", "四川");
		areas.add(area1);
		areas.add(area2);
		areas.add(area3);
		areas.add(area4);
		
		request.setAttribute("areas", areas);
	    

		return mapping.findForward("success");
	}

}

 

你可能感兴趣的:(String)