使用数据库中的值设置jsp复选框 [英] Setting jsp checkbox with a value from database

查看:262
本文介绍了使用数据库中的值设置jsp复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的.我正在制作一个具有数据库后端的Java Web应用程序,以便对某些数据进行CRUD.单击项目旁边的编辑"按钮时,它将导航到包含当前数据的表单以进行编辑.字段之一是布尔值,我想将其显示为复选框,以便True使其处于选中状态,而False使其保持未选中状态.

我尝试了许多不同的变体,但似乎都没有用.以下是一些示例,其中<%= action.get("stable")%>返回带有TrueFalse

的字符串

<input TYPE=checkbox name="stable" value=<%= action.get("stable") %>

<input TYPE=checkbox name="stable" value=<%= action.get("stable")?"True":"False" %><%= action.get("stable")?"checked":"" %>

<input TYPE=checkbox name="stable" checked=<%= action.get("stable")%>/>

那么如何根据action.get("stable")

返回的字符串将复选框设置为选中还是未选中

如果问题有点琐碎,谢谢您的帮助.

解决方案

选中的复选框的正确标记是checked="checked".如果未选中,则完全不存在checked属性.

您应该使用JSTL和JSP EL生成它,因为scriptlet是过去的东西,多年以来都不应该在JSP中使用.请参阅如何避免JSP文件中的Java代码?. /p>

这当然需要进行一些重构,以便操作bean具有返回布尔值的常规isStable()方法,这将更加干净.但是无论如何,这是使用现有代码的工作方式:

<input type="checkbox" name="stable" <% 
    if ("True".equals(action.get("stable"))) {
        out.print("checked=\"checked\"");
    } %>/>

请注意,所有属性也都应该用引号引起来.

Ok. I'm making a java web app with a database backend to do some CRUD on some data. When the edit button is clicked next to an item, it navigates to a form with the current data for editing. One of the fields is boolean and I would like to display it as a checkbox so that True makes it checked and False leaves it unchecked.

I have tried many different variations none seem to work. Here are some examples where <%= action.get("stable")%> returns a string with either True or False

<input TYPE=checkbox name="stable" value=<%= action.get("stable") %>

<input TYPE=checkbox name="stable" value=<%= action.get("stable")?"True":"False" %><%= action.get("stable")?"checked":"" %>

<input TYPE=checkbox name="stable" checked=<%= action.get("stable")%>/>

So how do you set a check box to checked/unchecked depending on the string returned with action.get("stable")

Thank you for any help sorry if the question is a bit trivial.

解决方案

The correct markup for a checked checkbox is checked="checked". If it's not checked, the checked attribute must not be present at all.

You should generate it using the JSTL and the JSP EL, because scriptlets are something from the past which should not be used in JSPs for years. See How to avoid Java code in JSP files?.

This would of course need some refactoring so that the action bean has a regular isStable() method returning a boolean, which would be much cleaner. But anyway, here's how it would work using your existing code :

<input type="checkbox" name="stable" <% 
    if ("True".equals(action.get("stable"))) {
        out.print("checked=\"checked\"");
    } %>/>

Note that all attributes should also be surrounded by quotes.

这篇关于使用数据库中的值设置jsp复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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