日期:2014-05-17  浏览次数:20732 次

究竟struts2中的DefaultTypeConverter是怎么用的
servlet.java:
package com.aa;

import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;


public class servlet extends DefaultTypeConverter {
@SuppressWarnings("rawtypes")
public java.lang.Object convertValue(java.util.Map context, java.lang.Object value, java.lang.Class toType) {
if(toType == String.class) {
String[] params = (String[])value;
String[] paramsSeparate = params[0].split(",");

javabean jb = new javabean();
jb.setUserName(paramsSeparate[0]);
jb.setUserPass(paramsSeparate[1]);

return jb;
}
else if(toType == javabean.class) {
javabean params = (javabean)value;

return "<" + params.getUserName() + "," + params.getUserPass() + ">";
}

return null;
}
}



SubmitAction-conversion.properties:
user=com.aa.servlet



NewFile.jsp:
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="servlet" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="userName"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="userPass"/></td>
</tr>
<tr>
<input type="submit"/>
<input type="reset"/>
</tr>
</table>
</form>
</body>
</html>


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>
<constant name="struts.devMode" value="true"/>
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
<constant name="struts.i18n.encoding" value="UTF-8"/>

<package name="Submit" extends="struts-default">
<action name="Submit" class="com.aa.SubmitAction">
<result name="input">/NewFile.jsp</result>
<result>/NewFile1.jsp</result>
<result name="error">/Error.jsp</result>
</action>
</package>
</struts>

SubmitAction.java:
package com.aa;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class SubmitAction extends ActionSupport implements ModelDriven<javabean> {
/**

*/
private static final long serialVersionUID = 4296997394602800862L;

private javabean user = new javabean();

@Override
public javabean getModel() {
if(user == null)
user= new javabean();

return user;
}

public void validate() {
if(getModel().getUserName() == null || getModel().getUserName().equa