字符串长度不同于Javascript到Java代码 [英] String length differs from Javascript to Java code

查看:103
本文介绍了字符串长度不同于Javascript到Java代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSP页面,其中包含一段Javascript验证码,限制了提交时的一定数量的字符。我正在使用< textarea> 所以我不能简单地使用长度属性,例如< input type =text> ;

I've got a JSP page with a piece of Javascript validation code which limits to a certain amount of characters on submit. I'm using a <textarea> so I can't simply use a length attribute like in a <input type="text">.

我使用 document.getElementById(text)。value.length 获取字符串长度。我在Windows上运行Firefox 3.0(但我也用IE 6测试了这种行为)。表单将提交给J2EE servlet。在我的Java servlet中,参数的字符串长度大于2000!

I use document.getElementById("text").value.length to get the string length. I'm running Firefox 3.0 on Windows (but I've tested this behavior with IE 6 also). The form gets submitted to a J2EE servlet. In my Java servlet the string length of the parameter is larger than 2000!

我注意到这可以通过在<$ c $中添加回车来轻松复制C>< TextArea> 。我已经使用Firebug来断言< textare> 的长度,它实际上是2000个字符长。但是在Java方面,回车符转换为UNIX样式( \\\\ n ,而不是 \ n ),因此字符串长度不同!

I've noticed that this can easily be reproduced by adding carriage returns in the <textarea>. I've used Firebug to assert the length of the <textare> and it really is 2000 characters long. On the Java side though, the carriage returns get converted to UNIX style (\r\n, instead of \n), thus the string length differs!

我错过了这里明显的东西或什么?如果没有,你如何可靠(跨平台/浏览器)确保< textarea> 是有限的。

Am I missing something obvious here or what ? If not, how would you reliably (cross-platform / browser) make sure that the <textarea> is limited.

推荐答案

这不是一个JavaScript(或Java)问题 - 两个层都报告了他们正在处理的字符串的准确长度用。你的情况下的问题是在HTTP传输过程中字符串被转换。

This isn't really a JavaScript (or Java) problem - both layers report an accurate length for the string they are dealing with. The problem in your case is that the string gets transformed during the HTTP transmission.

如果你绝对必须确保字符串不超过一定长度,你可以模仿在客户端进行此转换,将\ n的每个实例替换为\ n \\\ - 但仅用于长度验证目的:

If you absolutely must ensure that the string doesn't exceed a certain length, you can mimic this transformation on the client by replacing every instance of "\n" with "\n\r" - but only for length verification purposes:

textarea.value.replace(/\n/g, "\r\n").length

这篇关于字符串长度不同于Javascript到Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆