Populate check boxes in JSP pages with data from JavaBeans

I have a JSP page with check boxes in the HTML form, as shown below

Now, when editing user skills, I want to get comma separated values from the table and fill in the check boxes in the JSP The following code provides 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;

Now I need to fill in the check box in JSP and select the corresponding skills I used the request getattribute () method, and I passed it to the JSP, as shown 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);
}

How to use the skills I acquired in the arrskills array and fill in the check box I tried it

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

But I'm sure it's not the right way to use it

Solution

Check your example. Here are some precautions

1) Related to your skill variables In Java, conventionally variables, instance variables and class variables are written in camelCase with the first lowercase letter

Read the Wikipedia article Java Naming Conventions See also Chapter 9 about code conventions for the Java ™ Naming conventions for programming language

So it would be better:

List and lt& Userdetails gt; skills = new ArrayList< UserDetails>();

2) Again, it is related to your skill variable You named it skill, but it is clear from your code that skill is only one of the properties of the userdetails object I'm making a hypothesis, but is the userdetails class just about user skills? If so, it's best to reflect this in the class name in some way, such as userskills Otherwise, it would be better if skills were just one of the user details:

List and lt& Userdetails gt; userDetailsList = new ArrayList< UserDetails>();

Similarly, it is strongly recommended to use meaningful variable names Read the naming convention above

3) Call connection The preparestatement () method does not need to be cast to Preparedstatement because it has returned the Preparedstatement object So do this:

pstmt = conn.prepareStatement(strsql);

As the answer to your question, yes, of course you can use < C: forloop >, for example, start with JSTL, iterate over the list of all users and output the relevant details of each user This is a common practice

Your question is not very clear, but let me guess In your example, you have only a limited list of skills. I mean only PHP, Java, mysql, JavaScript, jQuery, node JS, and for each user, if the user has the corresponding skills, you need to check the relevant check boxes

If the above assumptions are correct, then this is one of the possible solutions

Set the properties containing the array or the list of required skills

Considering that the list is limited to predefined values, you can store the list in ServletContext so that the whole application can use it It is best to set this kind of global object in the class that implements servletcontextlistener

Example: 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! In order to receive these notification events (contextinitialized, contextdestroyed), the implementation class must be declared in the deployment descriptor of the web application, annotated with weblistener, or registered through one of the addListener methods defined on the ServletContext Here I use the @ weblistener annotation

I don't have time to delve into architectural details, but for this example, I assume that there is a user class that contains user related information It contains attribute skills implemented in map < string, Boolean > It has getters and setters (such as public map < string, Boolean > getskills() and public void setskills (map < string, Boolean > skills))

Example: 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
}

Somewhere, in a servlet that processes data submitted through an HTML form in the dopost () method, you can fill in 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);
...

So you won't hard code the name of the skill, otherwise you can do this:

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

Now in some servlets, get all users, such as list < user > users, and set an attribute in the request scope, such as request SetAttribute ("users", users) to store the user list and forward it to a view (JSP page), which will output data related to all users

A simple example of a JSP page that outputs 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 check@R_244_2419@ 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="check@R_244_2419@" name="chkSkills" value="${skill}" checked="checked">${skill}&nbsp;
                </c:when>
                <c:otherwise>
                    <input type="check@R_244_2419@" name="chkSkills" value="${skill}">${skill}&nbsp;
                </c:otherwise>
            </c:choose>
        </c:forEach>
    </c:forEach>
</body>
</html>

Or a more concise variant uses < C: if > tag: 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="check@R_244_2419@" name="chkSkills" value="${skill}" <c:if test="${user.skills[skill]}">checked="checked"</c:if>>${skill}&nbsp;
        </c:forEach>
    </c:forEach>
</body>
</html>

Note: it is better to use JSP annotation in the form of <% - some comments -% > to annotate JSP specific code parts in JSP Unlike HTML comments (in the form of ), JSP comments will not be displayed in the result page that will be sent to the client

I hope this will help you and give some useful ideas

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>