使用 Servlet 和 JSP 验证数字
我正在开发一个小型 Servlet &在学习Web开发的同时JSP应用程序。
我有一个关于 jsp 和 servlet 之间的验证和传递值的问题。
我有一个“啤酒”类,具有“评级”属性(双精度类型)。
加载“edit.jsp”的 servlet 创建一个 Beer 对象并从数据库加载当前值。
BeerDAO beerdao = new BeerDAO();
Beer beer = beerdao.getBeer(id);
request.setAttribute("beer", beer);
在 JSP 中,对象按以下方式显示:
...
<td class="left">Beer Name:</td>
<td><input type="text" name="name" value="${beer.name}"/></td>
...
<td class="left">Rating:</td>
<td><input type="text" name="rating" value="${beer.rating}"/></td>
...
现在,当我将表单提交到“更新”servlet 时,每个属性都会得到验证。对于“评级”属性,我将其转换为双精度值。
如果我在验证中发现错误(即:评级值是字母,而不是数字),我想返回到包含用户输入的值和错误消息的表单。问题是,我需要请求中的 Beer 对象显示在表单中,但我无法将“评级”值传递给它,因为它的类型不正确。所以现在我正在将用户播种回具有空评级的表单。
我猜我做错了。那么,验证数字并返回编辑表单的正确方法是什么?
I'm working on a small Servlets & JSP application while learning web development.
I have a question regarding validations and passing values between jsp and servlets.
I have a "Beer" class, with a "rating" property (of type double).
The servlet that loads "edit.jsp" creates a Beer object and loads the current values from the DB.
BeerDAO beerdao = new BeerDAO();
Beer beer = beerdao.getBeer(id);
request.setAttribute("beer", beer);
In the JSP, the object is displayed in the following manner:
...
<td class="left">Beer Name:</td>
<td><input type="text" name="name" value="${beer.name}"/></td>
...
<td class="left">Rating:</td>
<td><input type="text" name="rating" value="${beer.rating}"/></td>
...
Now, when I submit the form to the "update" servlet, each property is validated. In the case of the "rating" property, I convert it to a double.
Should I find an error in the validation (ie: letters, instead of numbers for the rating value), I want to go back to the form with the values that the user typed and an error message. Thing is, I need a Beer object in the request to be displayed in the form, but I can't pass the "rating" value to it, because it's not of the correct type. So right now I'm seeding the user back to a form with an empty rating.
I'm guessing I'm going at it wrong. So, what would be the proper way to validate numbers and get back to the edit form?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最基本的方法是在请求范围内有一个 Map,其中键表示字段名称,值表示验证错误(如果有)。
然后在视图中,
当没有消息(因此验证已通过)时,条件表达式将显示啤酒评级,否则将显示用户提交的值作为请求参数。
与具体问题无关,在没有 XML 转义的情况下重新显示用户提交的数据很容易出现 XSS 攻击。我强烈建议安装 JSTL 并使用
fn:escapeXml()
函数对值进行转义。The most basic approach would be to have a
Map<String, String>
in the request scope where the key represents the field name and the value represents the validation error -if any.And then in the view
The conditional expression will show the beer rating when there is no message (and thus validation has passed) and otherwise the user-submitted value as request parameter.
Unrelated to the concrete problem, redisplaying user submitted data without XML-escaping it is prone to XSS attacks. I strongly suggest to install JSTL and use
fn:escapeXml()
function to escape the values.