我想加密用户输入并将其存储在数据库中。我使用Struts2类型转换,所有用户输入都被视为String
,并且以下转换工作正常:
String
至Integer
String
至Long
String
至byte[]
但是,当我尝试转换为目标类型String
时,它不起作用,也不会调用convertFromString()
方法。
@Override
public Object convertFromString(Map context, String[] value, Class arg2) {
String val = value[0];
try {
return ASEEncDecUtil.encrypt(val.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
我不知道我做错了什么。
是否有应该用于加密用户输入的最佳实践?
您很可能正在自定义转换器中扩展StrutsTypeConverter
类。其中convertFromString
和convertToString
方法是从convertValue
方法调用的,看起来像这样:
public Object convertValue(Map context, Object o, Class toClass) {
if (toClass.equals(String.class)) {
return convertToString(context, o);
} else if (o instanceof String[]) {
return convertFromString(context, (String[]) o, toClass);
} else if (o instanceof String) {
return convertFromString(context, new String[]{(String) o}, toClass);
} else {
return performFallbackConversion(context, o, toClass);
}
}
因此,如果toClass
是String
类,则永远不会调用convertFromString
。
要实现您想要的,请扩展com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter
并重写public Object convertValue(Map context, Object o, Class toClass)
方法。
转换器的工作是在不同格式之间执行转换。
它是而不是以某种格式获取对象、对其执行业务然后以相同格式返回它的正确工具。
也就是说,对于这类事情,你可以使用几种机制(正交机制,如Struts2 Interceptors和Java EE Decorator,或特定机制,如Action Methods,甚至Mutators/Accessors),根据你需要使用它们的次数/地点等因素,每种机制都更合适。
最简单的方法(我是KISS范式的粉丝)是访问器/突变体的方法:
public class KeepItSimpleStupidAction extends ActionSupport {
@Inject Logger LOG;
private String text; // text is always encrypted inside the action
public String getText() { // but it can also be read decrypted by calling the getter
return ASEEncDecUtil.decrypt(text.getBytes("UTF-8"));
}
public void setText(String text) { // the setter automatically encrypts it
this.text = ASEEncDecUtil.encrypt(text.getBytes("UTF-8"));
}
public String execute() {
LOG.debug("text decrypted: " + getText());
LOG.debug("text encrypted: " + text);
return SUCCESS;
}
}