1.Converter:
struts.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="converterDemo" extends="struts-default"> <action name="point-*" class="cn.zzsxt.action.MyPointAction" method="{1}"> <result name="success">/success.jsp</result> </action> </package> </struts>
Conversion:
package cn.zzsxt.conversion; import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; import cn.zzsxt.entity.MyPoint; public class MyPointConverter extends StrutsTypeConverter { /** * 10,20 * 将字符串转换为复合类型 * context:上下文 * values:参数的值 * toType:目标类型 */ @Override public Object convertFromString(Map context, String[] values, Class toType) { if(toType==MyPoint.class){ String value = values[0];//获取坐标的值: 10,20 String[] arr = value.split(",");//arr = {"10,20"} //获取x坐标的值 int x = Integer.parseInt(arr[0]); int y = Integer.parseInt(arr[1]); MyPoint myPoint = new MyPoint(); myPoint.setX(x); myPoint.setY(y); return myPoint; } return null; } /** * 将复合类型转换为字符串 */ @Override public String convertToString(Map arg0, Object arg1) { return null; } }
action:
package cn.zzsxt.action; import com.opensymphony.xwork2.ActionSupport; import cn.zzsxt.entity.MyPoint; public class MyPointAction extends ActionSupport { private MyPoint point; public MyPoint getPoint() { return point; } public void setPoint(MyPoint point) { this.point = point; } public String add() throws Exception { System.out.println("执行了add方法,坐标为:"+point); return this.SUCCESS; } }
action包下properties文件(简单类型):
point=cn.zzsxt.conversion.MyPointConverter
conversion包下properties文件(复合类型):
cn.zzsxt.entity.MyPoint=cn.zzsxt.conversion.MyPointConverter
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘index.jsp‘ starting page</title> </head> <body> <form action="point-add.action" method="post"> 请输入坐标(x,y)<input type="text" name="point"><br> <input type="submit" value="提交"> </form> </body> </html>
success.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘index.jsp‘ starting page</title> </head> <body> x=${point.x}<br> y=${point.y}<br> </body> </html>
时间: 2024-10-21 13:22:44