Struts2的类型转换--内建转换器

来源:互联网 发布:ubuntu安装类型选哪个 编辑:程序博客网 时间:2024/06/07 04:21
所有的MVC框架都属于表现层的解决方案,都需要负责收集用户请求参数,并将请求参数传给应用的控制器组件。此时所有的请求参数都是也只能是字符串数据类型,但Java是强类型语言,因此MVC框架必须将这些字符串请求参数转换成相应的数据类型--这个工作是所有的MVC框架都应该提供的功能。

Struts2提供了非常强大的类型转换机制。

本文先来分析下Struts2内建的类型转换器,如下:

  1. boolean和Boolean:完成字符串和布尔值之间的转换
  2. char和Character:完成字符串和字符之间的转换
  3. int和Integer:完成字符串和整型之间的转换
  4. long和Long:完成字符串和长整型之间的转换
  5. float和Float:完成字符串和单精度浮点值之间的转换
  6. double和Double:完成字符串和双精度浮点值之间的转换
  7. Date:完成字符串和日期类型之间的转换,日期格式使用用户请求所在的Locale的SHORT格式
  8. 数组:在默认情况下,数组元素是字符串,如果用户提供了自定义类型转换器,也可以是其他复合类型的数组
  9. 集合:在默认情况下,假定类型为String,并创建一个新的ArrayList封装所有的字符串

注意:
对于数组类型的转换,将按照数组元素的类型来单独转换每一个元素;但对于其他的类型转换,如果转换无法完成,系统将出现类型转换错误。

以一个简单的注册页面来简单认识下Struts2内建的类型转换器。

注册页面:
<body><form action="regist" method="post"><table><caption><h3>用户登录</h3></caption><tr><td>用户名:<input type="text" name="name" /></td></tr><tr><td>密码:<input type="password" name="pass" /></td></tr><tr><td>年龄:<input type="text" name="age" /></td></tr><tr><td>生日:<input type="text" name="birth" /></td></tr><tr align="center"><td colspan="2"><input type="submit" value="注册" /> <inputtype="reset" value="重填" /></td></tr></table></form></body>

成功页面:
<body><h1>您的注册信息如下</h1>用户名:<s:property value="name"/><br/>密码:<s:property value="pass"/><br/>年龄:<s:property value="age"/><br/>生日:<s:property value="birth"/></body>

Action类
package com.test.action;import java.util.Date;import com.opensymphony.xwork2.ActionSupport;public class RegistAction extends ActionSupport{//值对象用于封装请求参数的4个属性private String name;private String pass;private int age;private Date birth;//无参构造函数public RegistAction(){}//初始化全部属性的构造器public RegistAction(String name, String pass, int age, Date birth) {this.name = name;this.pass = pass;this.age = age;this.birth = birth;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPass() {return pass;}public void setPass(String pass) {this.pass = pass;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}}

注意:上面的RegistAction并未重写execute()方法,这是由于该Action继承了ActionSupport类,ActionSupport类已经重写了execute()方法--该方法总是返回success字符串。

struts.xml配置
<action name="regist" class="com.test.action.RegistAction">             <result>welcome.jsp</result>        </action>

在注册页面输入如下信息:

用户名:user 
密码:123456
年龄:10
生日:2016-6-21

注册页面展示如下:




Action处理结果后直接返回成功页面,将会看到如下页面,类型转换成功

原创粉丝点击