index.jsp struts2 org.apache.struts2"> 跳转到主内容
思享编程网:思考分享,玩转编程世界!

《深入浅出struts2》--第五章,表单标签案例2困惑解决

web.xml文件

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

index.jsp struts2

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

struts2 /*

struts.xml文件

"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">

/jsp/CheckBox2.jsp /jsp/Select.jsp

action类

package app05a;

import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import org.apache.struts2.util.ServletContextAware; import com.opensymphony.xwork2.ActionSupport; public class SelectTestAction extends ActionSupport implements ServletContextAware{ private int city; private int country; private ServletContext cse;

public int getCity() { return city; } public void setCity(int city) { this.city = city; } public int getCountry() { return country; } public void setCountry(int country) { this.country = country; }

public City[] getCities(){ City[] cities=null; if(country==1){ cities=new City[3]; cities[0]=new City(1,"Atlanta"); cities[1]=new City(2,"Chicago"); cities[2]=new City(3,"Detroit"); }else if(country==2){ cities=new City[3]; cities[0]=new City(4,"Vancouver"); cities[1]=new City(5,"Toronto"); cities[2]=new City(6,"Montreal"); }else if(country==3){ cities=new City[2]; cities[0]=new City(7,"Mexico City"); cities[1]=new City(8,"Tijuana"); }else{ cities=new City[0]; } return cities; }

public String show(){

Map countries=new HashMap(); countries.put(1, "US"); countries.put(2, "Canada"); countries.put(3, "Mexico"); cse.setAttribute("countries", countries);

return SUCCESS;

} @Override public void setServletContext(ServletContext cse) { this.cse=cse; }

}

jsp文件:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

<%

String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

onchange="this.form.submit()"/>

执行结果:

我的困惑: 1,从上面执行结果来看,国家和所在的城市关联在一起啦,点击不同的国家显示不同的城市。

但是怎么关联起来的?

首先说明一下,onchange="this.form.submit()"这个变化事件的意思是:每当在国家列表中改变当前所选国家,就让这个表单form提交数据给服务器。

而在本案例中,由于没有显示指出action,则默认是调交给自己所在的URL,在此也就是提交给网址栏中的URL。

然后服务器根据web.xml文件中的filter参数知道了要把这个请求交给本案例中的过滤器处理。

这个StrutsPrepareAndExecuteFilter过滤器根据struts.xml文件,知道了这个请求所要做的动作。

于是先找到ValueStack中SelectTestAction实例(如果没有则创建)。

根据所选的国家代码(1,2或3)对应创建了这个国家下面的cities数组,然后执行动作方法,根据动作方法返回的SUCCESS。

struts把控制权转移到本案例中的jsp页面。

于是在页面显示的国家和城市都是相关联的。

另外说明一下,这个只是一个demo,只是为了实现效果。

我把form表单的action改成别的页面时,改变所选国家时发现跳转到别的页面去啦。

在实际中,这样是不合理的。

这个跳转走,是因为this.form.submit()所致,这个js中的事件作用是让自身所在的表单提交数据,一经提交那么就会跳转到action所指的目的地。

特别说明:这只是经过个人思考,猜测的struts应该是这样运行的。

由于这只是初学struts,后面看struts技术内幕的时候会深入理解,如果发现有错误会来更改。

相关文章