zoukankan      html  css  js  c++  java
  • Struts2(接受表单参数)请求数据自动封装和数据类型转换

    Struts2请求数据自动封装:

      (1)实现原理:参数拦截器

      (2)方式1:jsp表单数据填充到action中的属性;

             普通的成员变量,必须给set,get可以不给的。

           注意点,Action中定义成员变量,成员变量的setXxx方法名中的Xxx和表单中name属性提交的参数对应起来的;

      (3)方式2:领域模型接受表单的参数(常用),jsp表单数据填充到action的对象的属性;

             对象类型,一定给get方法。

           注意点:Action中定义封装的实体类对象如private User user,并给set,get方法,在jsp页面需要注意是user.id;

      (4)方式3:模型驱动接受表单的参数,了解即可,这里省略;


    1:方式1:

    第一步:引包,省去

    第二步:配置struts2的过滤器

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
     3   <display-name>struts2_20170221</display-name>
     4   <welcome-file-list>
     5     <welcome-file>index.html</welcome-file>
     6     <welcome-file>index.htm</welcome-file>
     7     <welcome-file>index.jsp</welcome-file>
     8     <welcome-file>default.html</welcome-file>
     9     <welcome-file>default.htm</welcome-file>
    10     <welcome-file>default.jsp</welcome-file>
    11   </welcome-file-list>
    12   
    13   <!-- struts2过滤器 -->
    14   <filter>
    15       <!-- 过滤器名称 -->
    16       <filter-name>struts2</filter-name>
    17       <!-- 过滤器类 -->
    18       <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    19   </filter>
    20   <!-- struts2过滤器映射 -->
    21   <filter-mapping>
    22       <!-- 过滤器名称 -->
    23       <filter-name>struts2</filter-name>
    24       <!-- 过滤器映射 -->
    25       <url-pattern>/*</url-pattern>
    26   </filter-mapping>
    27   
    28 </web-app>

    第三步:开发Action

     1 package com.bie.type;
     2 
     3 import java.util.Date;
     4 
     5 import com.opensymphony.xwork2.ActionSupport;
     6 
     7 /** 
     8 * @author BieHongLi 
     9 * @version 创建时间:2017年2月21日 下午8:39:13 
    10 * Struts2的核心业务,请求数据自动封装和类型转换
    11 * 这个继承不继承即可extends ActionSupport,习惯继承了
    12 */
    13 public class TypeAction extends ActionSupport{
    14 
    15 
    16     private static final long serialVersionUID = 1L;
    17     private String name;
    18     private String password;
    19     private int age;
    20     private Date birthday;//Date日期类型,导入的utilsl类型的
    21     
    22     //普通的成员变量,必须给set,get可以不给的。
    23     public String getName() {
    24         return name;
    25     }
    26     public String getPassword() {
    27         return password;
    28     }
    29     public int getAge() {
    30         return age;
    31     }
    32     public Date getBirthday() {
    33         return birthday;
    34     }
    35 
    36 
    37     //处理注册请求,String类型的,不能带参数的
    38     public String register() {
    39         System.out.println(name+" "+password+" "+age+" "+birthday);
    40         return SUCCESS;
    41     }
    42 }

    第四步:配置struts.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">

    <struts>
        
        <!-- 声明包 -->
        <package name="finalPackage" extends="struts-default">
            <action name="requestAction" class="com.bie.finalImpl.FinalAction">
                <result name="success">success.jsp</result>
            </action>
            
            <action name="ImplAction" class="com.bie.finalImpl.ImplAction">
                <result name="success">success.jsp</result>
            </action>
            
            <action name="type_*" class="com.bie.type.TypeAction" method="{1}">
                <result name="success">show.jsp</result>
            </action>
        </package>
        
    </struts>

    第五步:注册页面index.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>表单提交的页面</title>
     8 </head>
     9 <body>
    10 <form action="${pageContext.request.contextPath}/type_register.action" method="post">
    11     账号:<input type="text" name="name"/>
    12     密码:<input type="password" name="password"/>
    13     年龄:<input type="text" name="age"/>
    14     出生:<input type="text" name="birthday"/>
    15     <input type="submit" value="注册"/>
    16 </form>
    17 </body>
    18 </html>

    第六步:显示页面show.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>显示的页面</title>
     8 </head>
     9 <body>
    10 <h1>Struts2的进行数据封装和类型转换的使用</h1>
    11 </body>
    12 </html>

     方式2:

    第一步:引包,省去

    第二步:配置struts2的过滤器,和上面的一样

    第三步:开发Action

     1 package com.bie.type;
     2 
     3 import java.util.Date;
     4 
     5 import com.opensymphony.xwork2.ActionSupport;
     6 
     7 /** 
     8 * @author BieHongLi 
     9 * @version 创建时间:2017年2月21日 下午8:39:13 
    10 * Struts2的核心业务,请求数据自动封装和类型转换
    11 * 这个继承不继承即可extends ActionSupport,习惯继承了
    12 */
    13 public class TypeAction extends ActionSupport{
    14 
    15 
    16     private static final long serialVersionUID = 1L;
    17     private User user;//对象类型,一定给get方法
    18     public User getUser() {
    19         return user;
    20     }
    21     public void setUser(User user) {
    22         this.user = user;
    23     }
    24     
    25     //处理注册请求,String类型的,不能带参数的
    26     public String register() {
    27         System.out.println(user.getName());
    28         System.out.println(user.getPassword());
    29         System.out.println(user.getAge());
    30         System.out.println(user.getBirthday());
    31         return SUCCESS;
    32     }
    33     
    34 }

    第四步:在开发action之前需要先创建一个实体类User.java

     1 package com.bie.type;
     2 
     3 import java.util.Date;
     4 
     5 /** 
     6 * @author BieHongLi 
     7 * @version 创建时间:2017年2月22日 下午4:17:02 
     8 * 
     9 */
    10 public class User {
    11 
    12     private String name;
    13     private String password;
    14     private int age;
    15     private Date birthday;//Date日期类型,导入的utilsl类型的
    16     
    17     //普通的成员变量,必须给set,get可以不给的。
    18     public void setName(String name) {
    19         this.name = name;
    20     }
    21     public void setPassword(String password) {
    22         this.password = password;
    23     }
    24     public void setAge(int age) {
    25         this.age = age;
    26     }
    27     public void setBirthday(Date birthday) {
    28         this.birthday = birthday;
    29     }
    30     public String getName() {
    31         return name;
    32     }
    33     public String getPassword() {
    34         return password;
    35     }
    36     public int getAge() {
    37         return age;
    38     }
    39     public Date getBirthday() {
    40         return birthday;
    41     }
    42     
    43 }

    第五步:配置struts.xml,和上面的一样,省去

    第六步:注册页面index.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>表单提交的页面</title>
     8 </head>
     9 <body>
    10 <form action="${pageContext.request.contextPath}/type_register.action" method="post">
    11     账号:<input type="text" name="user.name"/><br/>
    12     密码:<input type="password" name="user.password"/><br/>
    13     年龄:<input type="text" name="user.age"/><br/>
    14     出生:<input type="text" name="user.birthday"/><br/>
    15     <input type="submit" value="注册"/>
    16 </form>
    17 </body>
    18 </html>

     第七步:显示页面show.jsp,和上面的一样,省去


     2Struts的数据类型转换:

      (1):Struts中jsp提交的数据,struts会自动转换为action中属性的类型。对于基本数据类型以及日期类型会自动转换;日期类型只支持yyyy-MM-dd格式,如何是其他格式,需要自定义类型转换器。

      (2):自定义类型转换器:

        a:局部类型转换器;

        b:全局类型转换器;

      (3):Struts2转换器API:

        |--TypeConverter                             转换器接口

          |--DefaultTypeConverter             默认类型转换器类

            |--StrutsTypeConverter         用户编写的转换器类,继承此类即可

      (4):局部类型转换器,转换器开发步骤:

        《需要注意的是TypeAction和TypeAction-conversion.properties必须在同一目录下,转换器类一般在utils包下

        a:写转换器类,自定义转换器继承StrutsTypeConverter类,重写convertFromString和converToString方法;

        b:注册转换器,配置转换器类(告诉struts应用自己的转换器类)

            --》在同包的action目录下(在action所在包中建立),新建一个properties文件

            --》命名规则:ActionClassName-conversion.properties

               命名举例:TypeAction-conversion.properties

                  《需要注意的是TypeAction必须放在相应的目录下面。》    

        c:内容,在所建立的ActionClassName-conversion.properties书写如下内容;

            user.birthday=转换器全路径(com.bie.type.MyConverter)

        d:总结:

            转换器,不能给其他Action使用。以上的转换器注册时候是与Action的名字相耦合的,因此只能在自己的Action中内部使用,称之为局部类型转换注册方式;


    3:局部类型转换器,转换器开发步骤

      (1):写转换器类(依旧是上面的开发案例和内容,只是增加了转换器,数据类型转换的使用)

    package com.bie.type;

    import java.sql.Date;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Map;

    import org.apache.struts2.util.StrutsTypeConverter;

    /**
    * @author BieHongLi
    * @version 创建时间:2017年2月22日 下午5:10:49
    * 自定义类型转换器
    */
    public class MyConverter extends StrutsTypeConverter{

        /***
         * 把String转换为指定的类型【String to Date】
         * @param context 当前上下文环境
         * @param values  jsp表单提交的字符串的值
         * @param toClass 要转换为目标类型
         */
        @Override
        public Object convertFromString(Map context, String[] values, Class toClass) {
            //判断 内容不能为空
            if(values==null || values.length==0){
                return null;
            }
            //判断类型必须为Date
            if(Date.class!=toClass){
                return null;
            }
            try {
                //转换
                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
                return sdf.parse(values[0]);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public String convertToString(Map arg0, Object arg1) {
            return null;
        }

    }

      (2):配置转换器类(告诉struts应用自己的转换器类)

      (3):内容文件命名为:TypeAction-conversion.properties

    1 user.birthday=com.bie.type.MyConverter

     4:全局类型转换器,转换器开发步骤:《需要写一个转换器,给所有的action用》

      (1):写转换器类  

      (2):配置全局转换器类(告诉struts应用自己的转换器类)

         --》在项目src目录下建立以下固定文件:xwork-conversion.properties  

      (3):内容

         Java.util.Date=转换器类(com.bie.type.MyConverter)

      (4)全局类型转换器,转换器开发步骤

        局部类型转换器和全局类型转换器的主要区别就是配置的不一样;

        文件命名为:xwork-conversion.properties

          要转换称的某种类型的全路径 = 自定义类型转换器的全路径;

    1 java.util.Date=com.bie.type.MyConverter

         注意:可以使用多种日期格式的进行转换,主要改变的是类转换器,这样yyyy-MM-dd/yyyyMMdd/yyyy年MM月dd日,这三种格式都可以进行输入了。

     1 package com.bie.type;
     2 
     3 import java.text.DateFormat;
     4 import java.text.ParseException;
     5 import java.text.SimpleDateFormat;
     6 import java.util.Date;
     7 import java.util.Map;
     8 
     9 import org.apache.struts2.util.StrutsTypeConverter;
    10 
    11 /** 
    12 * @author BieHongLi 
    13 * @version 创建时间:2017年2月22日 下午5:10:49 
    14 * 自定义类型转换器
    15 */
    16 public class MyConverter extends StrutsTypeConverter{
    17 
    18     //新需求:要求项目中要支持的格式,如:yyyy-MM-dd/yyyyMMdd/yyyy年MM月dd日
    19     //先定义项目中支持的转换的格式
    20     DateFormat[] df={
    21         new SimpleDateFormat("yyyy-MM-dd"),
    22         new SimpleDateFormat("yyyyMMdd"),
    23         new SimpleDateFormat("yyyy年MM月dd日")
    24     };
    25     
    26     /***
    27      * 把String转换为指定的类型【String to Date】
    28      * @param context 当前上下文环境
    29      * @param values  jsp表单提交的字符串的值
    30      * @param toClass 要转换为目标类型
    31      */
    32     /*@Override
    33     public Object convertFromString(Map context, String[] values, Class toClass) {
    34         //判断 内容不能为空
    35         if(values==null || values.length==0){
    36             return null;
    37         }
    38         //判断类型必须为Date
    39         if(Date.class!=toClass){
    40             return null;
    41         }
    42         try {
    43             //转换
    44             SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
    45             return sdf.parse(values[0]);
    46         } catch (ParseException e) {
    47             throw new RuntimeException(e);
    48         }
    49     }*/
    50 
    51     
    52     @Override
    53     public Object convertFromString(Map context, String[] values, Class toClass) {
    54         //判断 内容不能为空
    55         if(values==null || values.length==0){
    56             return null;
    57         }
    58         //判断类型必须为Date,注意Date是 java.util.Date;
    59         if(Date.class!=toClass){
    60             return null;
    61         }
    62         //迭代,转换失败向下一个格式转换,转换成功直接返回
    63         for(int i=0;i<df.length;i++){
    64             try {
    65                 //转换
    66                 return df[i].parse(values[0]);
    67             } catch (ParseException e) {
    68                 continue;
    69             }
    70         }
    71         return null;
    72     }
    73     @Override
    74     public String convertToString(Map arg0, Object arg1) {
    75         return null;
    76     }
    77 
    78 }
  • 相关阅读:
    Mac 终端自动补全忽略大小写
    AtCoder ABC 155F Perils in Parallel
    AtCoder ABC 155E Payment
    AtCoder ABC 155D Pairs
    AtCoder ABC 154F Many Many Paths
    牛客 边界都是1的最大正方形大小
    牛客 打印N个数组整体最大的Top K
    牛客 数组中子数组的最大累乘积
    牛客 在数组中找到一个局部最小的位置
    牛客 子矩阵最大累加和问题
  • 原文地址:https://www.cnblogs.com/biehongli/p/6426330.html
Copyright © 2011-2022 走看看