struts2.0学习笔记(五)--Converter(转换器)

项目树形图


WebRoot/WEB-INF/web.xml

 1 <? xml version="1.0" encoding="UTF-8" ?>
 2 < web-app  id ="WebApp_ID"  version ="2.4"
 3     xmlns ="http://java.sun.com/xml/ns/j2ee"
 4     xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
 6      < display-name > Struts2Hello </ display-name >
 7      < filter >
 8          < filter-name > struts2 </ filter-name >
 9          < filter-class >
10             org.apache.struts2.dispatcher.FilterDispatcher
11          </ filter-class > <!--  以过虑器的形式出现  -->
12      </ filter >
13      < filter-mapping >
14          < filter-name > struts2 </ filter-name >
15          < url-pattern > /* </ url-pattern > <!--  过虑所有内容  -->
16      </ filter-mapping >
17      < welcome-file-list >
18          < welcome-file > index.html </ welcome-file >
19          < welcome-file > index.htm </ welcome-file >
20          < welcome-file > index.jsp </ welcome-file >
21          < welcome-file > default.html </ welcome-file >
22          < welcome-file > default.htm </ welcome-file >
23          < welcome-file > default.jsp </ welcome-file >
24      </ welcome-file-list >
25 </ web-app >
26

WebRoot/index.jsp
 1 <% @page contentType="text/html; charset=GBK" %>
 2 <% @taglib prefix="s" uri="/struts-tags" %>
 3 <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
 4 < html >
 5      < head >
 6          < title > Converter </ title >
 7      </ head >
 8
 9      < body >
10          < s:form  action ="HelloWorld"  theme ="simple" >
11              <%
12                // name="loc" 是LoginAction.java中的private Locale loc = Locale.CHINA;
13            
%>
14     Locale: < s:textfield  name ="loc"   />
15              < br >
16              < s:submit  />
17          </ s:form >
18          < br >
19          < h2 >
20              < s:property  value ="msg"   />
21          </ h2 >
22      </ body >
23 </ html >
24


WebRoot/submit.jsp
 1 <% @page contentType="text/html; charset=GBK" %>
 2 <% @taglib prefix="s" uri="/struts-tags" %>
 3
 4 < html >
 5      < head >
 6          < title > submit </ title >
 7      </ head >
 8      <!--  提交页面,页面信息为Action中的集合属性  -->
 9      < body >
10          <!--  错误提示层(错误显示信息), s:fielderror会自动检测页面中所有域(输入框等)中的错误信息 -->
11          < div  style ="color: red" >
12              < s:fielderror ></ s:fielderror >
13          </ div >
14          < s:form  action ="ProductConfirm"  theme ="simple" >
15              < table >
16                  < tr  style ="background-color: powderblue; font-weight: bold;" >
17                      < td >
18                         Product Name
19                      </ td >
20                      < td >
21                         Price
22                      </ td >
23                      < td >
24                         Date of Production
25                      </ td >
26                  </ tr >
27                  <%
28                    //1.s:iterator:使用迭代器
29                        //2.value=new int[3]" status="stat":整形数组集合对应action中的List集合;每次取出一个值存入stat中
30                        //3. products['+#stat.index+'].name:OGNL表达式,相当于<%= "products[" + stat.index + "].name" %>
31                        //        (1)products对应action(ProductConfirm.java)中的 products属性,
32                        //        (2)整个句子的作用是从action中找到products并取出products的name属性
33                        //        (3)规范表达式:%{Action 中的属性集合[整数数组的迭代取值].具体pojo类的属性}
34                
%>
35
36                  < s:iterator  value ="new int[3]"  status ="stat" >
37                      < tr >
38                          < td >
39                              < s:textfield  name ="%{'products['+#stat.index+'].pname'}"   />
40                          </ td >
41                          < td >
42                              < s:textfield  name ="%{'products['+#stat.index+'].price'}"   />
43                          </ td >
44                          < td >
45                              < s:textfield  name ="%{'products['+#stat.index+'].pdate'}"   />
46                          </ td >
47                      </ tr >
48                  </ s:iterator >
49                  < tr >
50                      < td  colspan ="3" >
51                          < s:submit  />
52                      </ td >
53                  </ tr >
54              </ table >
55          </ s:form >
56      </ body >
57 </ html >
58

WebRoot/show.jsp
 1 <% @ page contentType="text/html; charset=GBK" %>
 2 <% @taglib prefix="s" uri="/struts-tags" %>
 3 < html >
 4      < head >
 5          < title > show </ title >
 6      </ head >
 7      <!--  显示页面,显示Action中的集合属性  -->
 8      < body >
 9          < table >
10              < tr  style ="background-color: powderblue; font-weight: bold;" >
11                  < td >
12                     Product Name
13                  </ td >
14                  < td >
15                     Price
16                  </ td >
17                  < td >
18                     Date of Production
19                  </ td >
20              </ tr >
21              <!--  s:iterator value="products" status="stat":与提交页面submit.jsp相同  -->
22              < s:iterator  value ="products"  status ="stat" >
23                  < tr >
24                      < td >
25                          < s:property  value ="pname"   />
26                      </ td >
27                      < td >
28                         $
29                          < s:property  value ="price"   />
30                      </ td >
31                      < td >
32                          < s:property  value ="pdate"   />
33                      </ td >
34                  </ tr >
35              </ s:iterator >
36          </ table >
37      </ body >
38 </ html >
39

src/com.action.LocaleConverter.java
 1 package  com.action;
 2
 3 import  java.lang.reflect.Member;
 4 import  java.util.Locale;
 5 import  java.util.Map;
 6
 7 /** */ /**
 8 * @author ∪∩BUG E-mail: [email protected]
 9 * @version Aug 24, 2008 4:29:04 PM
10 * @转换器类
11 */

12
13 //  继承ognl默认的格式转换类
14 public   class  LocaleConverter  extends  ognl.DefaultTypeConverter  {
15
16    @Override
17    // Map context:上下上下文对象; Object value:待转换对象; Class toType:目标类型
18    public Object convertValue(Map context, Object value, Class toType) {
19
20        // 如果要转换的是本地化类型Locale.class(如整形:Integer.class)
21        if (toType == Locale.class{
22
23            // 把待转换类型强制转换成字符串类型,并取第一个元素
24            String locale = ((String[]) value)[0];
25
26            // 截取字符串去掉"_";如果zh_CN截取得(zh,CN)
27            return new Locale(locale.substring(02), locale.substring(3));
28        }

29        // 转换成字符串类型
30        else if (toType == String.class{
31
32            Locale locale = (Locale) value;
33            return locale.toString();
34        }

35
36        return null;
37    }

38}

src/com.action.LoginAction.java
 1 package  com.action;
 2
 3 import  java.util.Locale;
 4
 5 import  com.opensymphony.xwork2.ActionSupport;
 6 import  com.opensymphony.xwork2.util.LocalizedTextUtil;
 7
 8 /** */ /**
 9 * @author ∪∩BUG E-mail: [email protected]
10 * @version Aug 24, 2008 4:11:04 PM
11 * @Action 类
12 */

13 @SuppressWarnings( " serial " )
14 public   class  LoginAction  extends  ActionSupport  {
15
16    private String msg;
17    private Locale loc = Locale.CHINA;    //默认语言版本的中文
18
19    public LoginAction() {
20        super();
21        // TODO Auto-generated constructor stub
22    }

23
24    public LoginAction(String msg, Locale loc) {
25        super();
26        this.msg = msg;
27        this.loc = loc;
28    }

29
30    @Override
31    public String execute() throws Exception {
32        
33        //LocalizedTextUtil是struts2.0中的国际化初始化工具,
34        //获取当前资源文件中的名为HelloWorld的key,然后使用loc语言版本    
35        msg = LocalizedTextUtil.findDefaultText("HelloWorld", loc);
36        return SUCCESS;
37    }

38
39    public String getMsg() {
40        return msg;
41    }

42
43    public void setMsg(String msg) {
44        this.msg = msg;
45    }

46
47    public Locale getLoc() {
48        return loc;
49    }

50
51    public void setLoc(Locale loc) {
52        this.loc = loc;
53    }

54}

55

src/com.action.ProductConfirm.java
 1 package  com.action;
 2
 3 import  java.util.List;
 4
 5 import  com.opensymphony.xwork2.ActionSupport;
 6 import  com.pojo.Product;
 7
 8 /** */ /**
 9 * @author ∪∩BUG E-mail: [email protected]
10 * @version Aug 24, 2008 9:58:06 PM
11 * @Action类 测试页面的提交功能
12 */

13 @SuppressWarnings( " serial " )
14 public   class  ProductConfirm  extends  ActionSupport  {
15
16    // 标准list集合
17    private List<Product> products;
18
19    public List<Product> getProducts() {
20        return products;
21    }

22
23    public void setProducts(List<Product> products) {
24        this.products = products;
25    }

26
27    @Override
28    public String execute() throws Exception {
29        //遍历products列表
30        for (Product p : products) {
31            System.out.println(p.getPname() + "|" + p.getPrice() + "|"
32                    + p.getPdate());
33        }

34        return SUCCESS;
35    }

36}

37

src/com.pojo.Product.java
 1 package  com.pojo;
 2
 3
 4 import  java.io.Serializable;
 5 import  java.util.Date;
 6
 7 /** */ /**
 8 * @author ∪∩BUG E-mail: [email protected]
 9 * @version Aug 24, 2008 9:51:03 PM
10 * @自定义数据类型
11 */

12 @SuppressWarnings( " serial " )
13 public   class  Product  implements  Serializable  {
14
15    //String,double,Date数据类型系统都内置有他们的转换器,无需另写转换器
16    private String pname;
17    private double price;
18    private Date pdate;
19
20    public Product() {
21
22    }

23
24    public String getPname() {
25        return pname;
26    }

27
28    public void setPname(String pname) {
29        this.pname = pname;
30    }

31
32    public double getPrice() {
33        return price;
34    }

35
36    public void setPrice(double price) {
37        this.price = price;
38    }

39
40    public Date getPdate() {
41        return pdate;
42    }

43
44    public void setPdate(Date pdate) {
45        this.pdate = pdate;
46    }

47
48    public Product(String pname, double price, Date pdate) {
49        super();
50        this.pname = pname;
51        this.price = price;
52        this.pdate = pdate;
53    }

54
55}

56

src/com.action.ProductConfirm-conversion.properties
ProductConfirm-conversion.properties //固定格式Action名-conversion.properties
Element_products=com.pojo.Product    //表明products的转换类型是Product,固定格式添加:Element_集合属性名=集合对象的实现类
Element_products = com.pojo.Product

src/xwork-conversion.properties
xwork-conversion.properties   //全局转换配置文件,必须放在SRC目录下,文件名固定!
java.util.Locale = com.action.LocaleConverter //自动调用com.action.LocaleConverter来转换
java.util.Locale  = com.action.LocaleConverter

src/struts.properties
struts.custom.i18n.resources = globalMessages

src/globalMessages_en_US.properties
HelloWorld = HelloWorld
failtip
= {0} Login failed\ !
language
= Select language
smg
= Now is {0}
succtip
= {0} Welcome,Login success.
usen
= Americal English
zhcn
= Simplified Chinese

src/globalMessages_zh_CN.properties
HelloWorld = \u4F60\u597D
failtip
= {0} \u767B\u5F55\u5931\u8D25
language
= \u9009\u62E9\u8BED\u8A00
smg
= {0} \u73B0\u5728\u7684\u4E8B\u4EF6\u662F {1}
succtip
= {0} \u6B22\u8FCE,\u767B\u5F55\u6210\u529F
usen
= \u82F1\u8BED
zhcn
= \u4E2D\u6587

src/struts.xml
 1 <? xml version="1.0" encoding="GBK" ?>
 2 <! DOCTYPE struts PUBLIC
 3          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 4          "http://struts.apache.org/dtds/struts-2.0.dtd" >
 5 < struts >
 6      < include  file ="struts-default.xml"   /> <!--  使用缺省的struts的配置文件  -->
 7
 8      <!--  包空间 ConverterDemo 继承 struts-default  -->
 9      < package  name ="ConverterDemo"  extends ="struts-default" >
10
11          <!--  映射名name="HelloWorld" 与 index.jsp 中的 action="HelloWorld" 对应,使用com.action.LoginAction来实现  -->
12          < action  name ="HelloWorld"  class ="com.action.LoginAction" >
13              < result > /index.jsp </ result >
14          </ action >
15          <!--  
16             1.映射名name="ProductConfirm" 与 submit.jsp 中的 action="ProductConfirm" 对应,使用com.action.ProductConfirm来实现 
17             2.成功转到show.jsp页面
18             3.失败转入submit.jsp页面
19          -->
20          < action  name ="ProductConfirm"
21             class ="com.action.ProductConfirm" >
22              < result > /show.jsp </ result >
23              < result  name ="input" > /submit.jsp </ result >
24          </ action >
25      </ package >
26 </ struts >
27
28

你可能感兴趣的:(struts2.0学习笔记(五)--Converter(转换器))