Struts2中的数据类型转换以及自定义数据类型转换器,数据类型转换错误的错误流输出
局部类型转换器注册,全局类型转换器注册,数据校验
自定义类型转换器:
package com.inspur.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.inspur.po.User;
import org.apache.struts2.util.StrutsTypeConverter;
public class UserConverter extends StrutsTypeConverter{
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
if(values.length>1){
List<User> userList=new ArrayList<User>();
for(int i=0;i<values.length;i++){
User user=new User();
String[] userValues=values[i].split(",");
user.setUsername(userValues[0]);
user.setPassword(userValues[1]);
userList.add(user);
}
return userList;
}else{
User user=new User();
String[]userValues=values[0].split(",");
user.setUsername(userValues[0]);
user.setPassword(userValues[1]);
return user;
}
}
@Override
public String convertToString(Map context, Object object) {
String result="";
if(object instanceof User){
User user=(User)object;
result+="<"+user.getUsername()+","+user.getPassword()+">";
}else if(object instanceof List){
List<User>userList=(List<User>)object;
result+="[";
for(User iterator_user:userList){
result+="<"+iterator_user.getUsername()+","+iterator_user.getPassword()+">";
}
result+="]";
}
return result;
}
}
Action代码:
package com.inspur.action;
import java.util.Date;
import com.inspur.po.User;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private Date loginTime;
public Date getLoginTime() {
return loginTime;
}
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
private User user;
private String tip;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public String login(){
if(this.getUser().getUsername().equals("lzhq")&&this.getUser().getPassword().equals("123")){
this.setTip("login success");
return SUCCESS;
}else
return ERROR;
}
}
Jsp页面代码
<form action="login.action" method="post" name="loginForm">
name,pass:<input type="text" name="user"/><br/>
loginTime:<input type="text" name="loginTime"/><br/>
<input type="submit" value="login"/>
</form>
<s:fielderror label="converter error information"></s:fielderror>