使用来自JavaBean的数据填充JSP页面中的复选框 [英] Populating checkboxes in JSP page with data from a JavaBean

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

问题描述

我有一个JSP页面,其中带有如下HTML表单中的复选框

I have a JSP page with checkboxes inside an HTML form as below

现在,在编辑用户 Skill 时,我想从表中获取逗号分隔的值并填充JSP中的复选框.以下代码从数据库表中提取了CSV技能.

Now while editing user Skill I want to take the comma separated values from the table and populate the checkboxes in JSP. The following code brings the CSV Skills from the database table.

      List<UserDetails> Skills = new ArrayList<UserDetails>();

      pstmt = (PreparedStatement) conn.prepareStatement(strSQL);
      rs    = pstmt.executeQuery();       
      String strSkills = rs.getString("Skills");

      List<String> items = Arrays.asList(strSkills.split("\\s*,\\s*"));

      objUserDetails.setSkills(items.toArray(new String[0]));

      Skills.add(objUserDetails);

      return Skills;

现在,我需要在JSP中的复选框中选中相应的技能.我使用了Request getAttribute()方法,并且将如下所示传递给JSP

Now I need to populate the checkboxes in JSP with the respective Skills checked. I used the Request getAttribute() method and I am passing to JSP as below

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
   dbUtil objdbUtil     = new dbUtil();
   List<UserDetails> Skills = objdbUtil.getSkills();

   request.setAttribute("arrSkills", Skills);
   RequestDispatcher rqst = request.getRequestDispatcher("Skills.jsp");
   rqst.forward(request, response);
}

如何使用在arrSkills数组中获得的技能并填充复选框.我尝试使用

How to use the Skills which I got in arrSkills array and populate the check boxes. I tried using

<c:forEach var="account" items="${arrUsersList}">
    <input type="checkbox" name="chkSkills" id="chkPHP" value="PHP"/>PHP
    <input type="checkbox" name="chkSkills" id="chkJava" value="Java"/>Java
    <input type="checkbox" name="chkSkills" id="chkMySQL" value="MySQL"/>MySQL
    <input type="checkbox" name="chkSkills" id="chkJavascript" value="Javascript"/>Javascript
    <input type="checkbox" name="chkSkills" id="chkJQuery" value="JQuery"/>JQuery
    <input type="checkbox" name="chkSkills" id="chkNode" value="Node"/>Node Js
</c:forEach>

但是我确信这不是使用它的正确方法.

But I am sure this is not the right way to use it.

推荐答案

检查您的示例,这里有一些注意事项.

Examining your example, here are some notes.

1)与您的技能变量相关.
在Java局部变量中,按惯例,实例变量和类变量在CamelCase中写成,首字母小写.

1) Related to your Skills variable.
In Java local variables, instance variables, and class variables by convention are written in CamelCase with lowercase first letter.

阅读Wikipedia文章,了解 Java命名约定 .
另请参见 代码约定中有关命名约定的第9章用于Java™编程语言 .

Read Wikipedia article for Java naming conventions.
Also see chapter 9 about Naming conventions from the Code Conventions for the Java™ Programming Language.

这样会更好:

List<UserDetails> skills = new ArrayList<UserDetails>();

List<UserDetails> skills = new ArrayList<UserDetails>();

2)再次与您的Skills变量相关.
您将其命名为技能,尽管从代码中可以清楚地看出,技能只是 UserDetails 对象的属性的一个.我正在做一个假设,但是 UserDetails 类仅是关于用户技能的吗?如果,那么最好以类名的形式反映出来,例如 UserSkills . 否则,如果技能只是用户详细信息之一,那么类似的方法会更好:

2) Again related to your Skills variable.
You named it skills, although from your code it is clear that skills is just one of the properties of the UserDetails object. I am making an assumption, but is the UserDetails class only about user skills? If yes, then it would be better to somehow reflect this in the class name, like UserSkills, for example. Otherwise, if the skills is just one of the user details, then something like this would be better:

List<UserDetails> userDetailsList = new ArrayList<UserDetails>();

List<UserDetails> userDetailsList = new ArrayList<UserDetails>();

同样,强烈建议使用有意义的变量名.阅读上面的命名约定.

Again, it is highly recommended to use meaningful variable names. Read the Naming conventions above.

3)调用

3) You don't need to cast to PreparedStatement when calling Connection.prepareStatement() method because it already returns PreparedStatement object. So just do:

pstmt = conn.prepareStatement(strSQL); 


作为对问题的答案,您当然可以使用<c:forLoop> /jstl/info> JSTL ,例如,以遍历所有用户的列表并输出每个用户的相关详细信息.这是一种常见的做法.


As an answer to your question, yes, of course you can use <c:forLoop> from the JSTL, for example to iterate thru the list of all users and output the related details for each user. It is a common practice.

您的问题还不太清楚,但让我猜想.
在您的示例中,您只有有限的技能列表,我的意思是只有PHP,Java,MySQL,JavaScript,jQuery,Node.js,并且对于每个用户,您都希望选中相关的复选框 if 用户具有适当的技能.

It was not very clear from your question, but let me guess.
In your example, you have only the finite list of skills, I mean only PHP, Java, MySQL, JavaScript, jQuery, Node.js, and for each user you want the related check boxes to be checked if the user has the appropriate skill.

如果上述假设正确,那么这是一种可能的解决方案.

If the above assumption is correct then here is one of the possible solutions.

设置一个属性,该属性包含数组或所需的所有技能的列表.

Set an attribute containing the array or a list of all the skills you need.

考虑到列表仅限于预定义的值,您可以将该列表存储在ServletContext中,以便整个应用程序都可以使用.最好在实现 ServletContextListener .

Considering the fact that the list is limited to just the predefined values, you can store that list in ServletContext, so that it would be available to the whole application. It is better to set such global objects in the class that implements ServletContextListener.

示例: AppContextListener.java :

package com.example.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        String[] skills = {"PHP", "Java", "MySQL", "JavaScript", "jQuery", "Node.js"};
        event.getServletContext().setAttribute("skills", skills);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {

    }
} 

NB!为了接收这些通知事件(contextInitialized,contextDestroyed),必须在Web应用程序的部署描述符中声明实现类,用WebListener对其进行注释,或者通过以下方式之一进行注册:在ServletContext上定义的addListener方法.在这里,我使用了@WebListener注释.

NB! In order to receive these notification events (contextInitialized, contextDestroyed), the implementation class must be either declared in the deployment descriptor of the web application, annotated with WebListener, or registered via one of the addListener methods defined on ServletContext. Here I used @WebListener annotation.

我没有时间去深入了解体系结构的细节,但是对于本示例,我假设存在一个类 User ,其中包含与用户相关的信息.其中包括以Map<String, Boolean>形式实现的属性技能.它具有getter和setter(例如public Map<String, Boolean> getSkills()public void setSkills(Map<String, Boolean> skills)).

I don't have time to deepen into architectural details, but for this example I assume there is a class User, that contains user related info. Among others it contains property skills implemented as a Map<String, Boolean>. It has getters and setters (like public Map<String, Boolean> getSkills() and public void setSkills(Map<String, Boolean> skills)).

示例: User.java

package com.example.model;

import java.util.Date;
import java.util.Map;

public class User {

    private String fisrtName;
    private String lastName;
    private Date birthday;
    ...
    private Map<Sting, Boolean> skills;

    // getters and setters here
}


在某个地方的在处理通过doPost()方法中通过某种HTML表单提交的数据的一个servlet 中,您将填充用户技能和其他详细信息.像这样的东西(简化的例子):


And somewhere, in one of your servlets that processes data submitted thru some HTML form in the doPost() method, you populate the user skills and other details. Something like this (simplified example):

User user = new User();
// set the user related data like first name or something like that
...
// get the list of available skills from ServletContext
String[] skills = (String[]) getServletContext().getAttribute("skills");
Map<String, Boolean> userSkills = new HashMap<String, Boolean>();

// Set the appropriate skills
for (String skill: skills) {
    if (request.getParameter(skill) != null) {
        userSkills.put(skill, true);
    } else {
        userSkills.put(skill, false);
    }
}

...
// Set user skills
user.setSkills(userSkills);
...

这样,您就不必对技能名称进行硬编码,否则您可以这样做:

This way you don't hard code the skills' names, otherwise you could do like this:

...
Map<String, Boolean> userSkills = new HashMap<String, Boolean>();
if (request.getParameter("PHP") != null) {
    userSkills.put("PHP", true);
} else {
    userSkills.put("PHP", false);
}
// the same way for Java, MySQL and others
...


现在,在某个servlet中,将所有用户都设为List<User> users,在请求范围内设置一个属性,例如request.setAttribute("users", users),以存储用户列表并转发到将输出数据的某个视图(JSP页面)与所有用户有关.


Now in some servlet, get all the users as, for example, a List<User> users, set an attribute in the request scope, like request.setAttribute("users", users) to store the users list and forward to some view (JSP page) that will output the data related to all users.

输出用户相关数据的JSP页面的简单示例: users.jsp

Simple example of JSP page that outputs the user related data: users.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <%-- We iterate thru all the users --%>
    <c:forEach items="${users}" var="user">
        <!-- Outputting different user related data -->
        ...
        <!-- Now outputting the user skills -->
        <h3>User skills</h3>
        <%-- In the inside loop, we iterate thru all the available skills, stored in the ServletContext --%>
        <c:forEach items="${skills}" var="skill">
            <c:choose>
                <%-- If the user has the appropriate skill, the related checkbox will be checked. Otherwise unchecked. --%>
                <%-- Note: using skill as a key in the map of user skills --%>
                <c:when test="${user.skills[skill] == true}">
                    <input type="checkbox" name="chkSkills" value="${skill}" checked="checked">${skill}&nbsp;
                </c:when>
                <c:otherwise>
                    <input type="checkbox" name="chkSkills" value="${skill}">${skill}&nbsp;
                </c:otherwise>
            </c:choose>
        </c:forEach>
    </c:forEach>
</body>
</html>

或使用<c:if>标记更紧凑的变体: users.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <c:forEach items="${users}" var="user">
        ...
        <h3>User skills</h3>
        <c:forEach items="${skills}" var="skill">
            <%-- Note: here <c:if> tag is used right inside <input> tag --%>
            <input type="checkbox" name="chkSkills" value="${skill}" <c:if test="${user.skills[skill]}">checked="checked"</c:if>>${skill}&nbsp;
        </c:forEach>
    </c:forEach>
</body>
</html>

注意:
要在JSP中注释JSP特定的代码部分,最好以
<%-- Some comment --%>的形式使用 JSP注释.与HTML注释(以<!-- Some comment -->的形式)不同,JSP注释在发送到客户端的结果页面中将不可见.

NOTE:
to comment JSP specific parts of code inside JSP, better use JSP comments in the form of
<%-- Some comment --%>. Unlike HTML comments (in the form of <!-- Some comment -->), JSP comments will not be visible in the resulting page that will be send to a client.

希望这会对您有所帮助,并提供一些有用的想法.

Hope this will help you and give some useful ideas.

这篇关于使用来自JavaBean的数据填充JSP页面中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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