如何处理从页面到 Servlet 的数据映射
所以这是我有一组复选框属性的交易。两者都是 HTML 复选框,但其中一个被选中 = true,而另一个被选中 = 1。(不知道如何转义,所以不合适的引号只是为了显示)
"<"input type="checkbox" class="attribute" name="trueFalse" value="true"/>
"<"input type="checkbox" class="attribute" name"oneZero" value="1"/>
当它们没有被选中时,问题就出现了,那里我无法找到传递 false 或 0 的方法,而是请求属性不存在。所以我试图找到最好的方法来处理这个问题,到目前为止我已经想出了......
- 使用JS并设置一个隐藏而不是实际的文本框 -我不想这样做,因为对于每个新属性,我需要编辑 JS
- 添加一个具有默认值的枚举
- 创建某种过滤器
有人有更好的想法或喜欢一个选项吗?
处理代码如下
public Map<Utils.Attributes, String> getAttributesFromRequest(HttpServletRequest request, String postfix, String prefix){
Map<Utils.Attributes, String> returnValue = new HashMap<Utils.Attributes, String>();
for (Utils.Attributes attr : Utils.Attributes.values()) {
StringBuilder sb = new StringBuilder();
sb.append(prefix);
sb.append(attr.getName());
sb.append(prefix);
String value = request.getParameter(sb.toString());
if(testValue(value)){
returnValue.put(attr, value);
}
}
return returnValue;
}
So here is the deal I have a set of attributes that are check boxes. Both are HTML checkboxes, but one is checked=true where as the otherone is checked = 1. (Wasn't sure how to escape so the out of place quotes are just for show)
"<"input type="checkbox" class="attribute" name="trueFalse" value="true"/>
"<"input type="checkbox" class="attribute" name"oneZero" value="1"/>
The problem comes in when they are not checked, there is no way I can find to pass a false or 0, instead the request property just doesn't exist. So I am trying to find the best way to handle this, so far I have come up with...
- Use JS and set a hidden instead of the actual textbox
-I don't want to do this because then for each new attribute I need to edit the JS - Add an enum with a default value
- Create some sort of filter
Anyone have better ideas or a fan of one option?
Processing code is as follows
public Map<Utils.Attributes, String> getAttributesFromRequest(HttpServletRequest request, String postfix, String prefix){
Map<Utils.Attributes, String> returnValue = new HashMap<Utils.Attributes, String>();
for (Utils.Attributes attr : Utils.Attributes.values()) {
StringBuilder sb = new StringBuilder();
sb.append(prefix);
sb.append(attr.getName());
sb.append(prefix);
String value = request.getParameter(sb.toString());
if(testValue(value)){
returnValue.put(attr, value);
}
}
return returnValue;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不将默认值放入映射中(false 和 0),并使用请求参数中的值(如果存在)覆盖它们?
Why don't you just put default values in the map (false and 0), and override them with the values from the request parameters if they are present?