java form表单接收空字符串,有没有简单的方法来将空的Java / Spring表单输入变成空字符串?...

Is there an easy way to turn empty form input into null strings in java? I'm using spring mvc and SimpleJdbcInsert to insert the object into a MySQL database. I'd like to set the blank input to NULL in the database rather than ''. I have quite a few fields, and I'm hoping for a way to do this without manually checking every value.

Thanks!

edit - So I'm an idiot. Several errors combined on my part led me to believe the correct answers below were not correct. I'd written a propertyEditorSupport like this:

class StringEditor extends PropertyEditorSupport {

public void setAsText(String text) {

String value = text.trim();

if ("" == value) {

setValue(null);

}

else {

setValue(value);

}

}

}

Two problems - first, no getAsText, so my form was getting populated with "null" strings! 2nd, my equality check is C++, not java. When I tried the recommended setter, I just reloaded the post, which already contained the "null" strings. Once I cleaned all that up, everything started working. Thanks for the help, and sorry for my "operator error"!

Brett

解决方案

The class you're looking for is:

org.springframework.beans.propertyeditors.StringTrimmerEditor

If you construct it with a true it will convert empty/whitespace strings to null. How to get it registered onto the binder depends on if you want it to be the default or only apply to certain views.

e.g., on a single controller you can just add

@InitBinder

public void initBinder(WebDataBinder binder) {

binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
出现中文乱码的原因可能是因为在表单提交时,使用了不同的字符编码方式。常见的字符编码方式有UTF-8、GBK等。为了解决中文乱码问题,可以尝试以下几种方法: 1. 在表单中添加一个隐藏的input,用于设置字符编码方式: ``` <form method="post" action="submit.php"> <input type="hidden" name="charset" value="utf-8"> ... </form> ``` 在后台接收数据时,可以先获取该input的值,然后使用对应的字符编码方式解码数据。 2. 在后台接收数据时,手动指定字符编码方式: ``` String param = new String(request.getParameter("param").getBytes("iso-8859-1"), "utf-8"); ``` 这里假设前端使用的是UTF-8编码方式,后台使用的是iso-8859-1编码方式。首先将iso-8859-1编码的数据转换为字节数组,然后再使用utf-8编码方式将其转换为字符串。 3. 在web.xml中配置字符编码过滤器: ``` <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 这里使用了Spring框架提供的字符编码过滤器,可以自动将所有请求的字符编码方式设置为UTF-8。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值