struts2类型转换(局部类型转换)

局部类型转换:

在对应的Action的同级目录下新建Action名-conversion.properties(一定要与Action类名对应)

其内容为: 目标转换对象=转换器类(包名+类名)

1、页面发送请求

<form action="convert">
	日期类型:<input type="text" name="birthday">yyyy-mm-dd<br>
	整数类型:<input type="text" name="age"><br>
	<input type="submit" value="提交">
</form>

 

2、找到对应的action,让属性有get和set方法

package hb.convert;

import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;

public class ConvertAction extends ActionSupport{
	
	Date birthday;
	int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	@Override
	public String execute() throws Exception {
		System.out.println(this.birthday);
		System.out.println(this.age);
		return super.execute();
	}
}

3、写一个类型转换类(继承StrutsTypeConverter类)

package hb.convert;

import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

public class ParamTypeConvert extends StrutsTypeConverter {
        //由字符串转为对象执行convertFromString方法
	@Override
	public Object convertFromString(Map map, String[] str, Class clazz) {
		//前端传递过来的字符串
		String datestr = str[0];
		System.out.println(datestr);
		//action中定义的参数类型,在配置文件中定义
		System.out.println(clazz.toString());
		System.out.println(map);
		
		return new Date();
	}
        //由对象转为字符串执行convertToString方法
	@Override
	public String convertToString(Map map, Object obj) {
		Date date = (Date)obj;
		long l = date.getTime();
		String result = new Long(l).toString();
		return result;
	}

}

4、在action同目录下面创建与action同名的properties文件ConvertAction-conversion.properties

    指明action对应的属性由哪个类来转换

birthday=hb.convert.ParamTypeConvert

5、配置struts.xml文件,查看内容

<!-- 测试类型转换 -->
<action name="convert" class="hb.convert.ConvertAction">
<result name="success">/resource/convert/sucess.jsp</result>
</action>

6、显示属性展示到前端的值

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s" uri="/struts-tags" %>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'sucess.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
	<s:property value="birthday"/><br> 
  </body>
</html>

总结:

1、如果是默认类型,struts2会帮我们自动转换,即例子中的String转为int类型,这个不需要我们自己操作

2、类型转换的配置文件名要跟action类同名,并且在同一个目录下面

3、action属性名=包+转换类

猜你喜欢

转载自hbiao68.iteye.com/blog/1757009