【问题标题】:How to pass the obj to jsp and create multiple div in looping?如何将obj传递给jsp并在循环中创建多个div?
【发布时间】:2018-11-12 21:00:18
【问题描述】:
{

    "Form": [{
            "Question": "Name of the locations in which your Company is located",
            "Answers": ["Bombay", "Delhi", "Chennai"],
            "Type": "Checkbox"
        },
        {
            "Question": "Count of Employees in your company",
            "Answers": ["10-99", "100-1000", "More than 1000"],
            "Type": "Radio"
        },
        {
            "Question": "What is your Designation",
            "Answers": ["Developer", "Management", "Senior Management"],
            "Type": "Radio"
        }
    ]
}

这是我在空间中的 JSON 文件。我使用简单的 JSON 将其转换为 obj,如下所示。

 package puzzle2;

import java.io.FileReader;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 * Servlet implementation class Puzzle2Servlet
 */
@WebServlet("/Puzzle2Servlet")
public class Puzzle2Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Puzzle2Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        JSONParser parser = new JSONParser();

        try {
            Object obj = parser.parse(new FileReader("D:\\Puzzle2.json"));

            JSONObject jsonObject = (JSONObject) obj;
            // System.out.println(jsonObject);

            JSONArray form = (JSONArray) jsonObject.get("Form");
             request.setAttribute("form", form);
            for (int i = 0; i < form.size(); i++) {

                JSONObject typeJson = (JSONObject) form.get(i);

                System.out.println(typeJson.get("Question") + "?");

                JSONArray ans = (JSONArray) typeJson.get("Answers");

                for (int j = 0; j < ans.size(); j++) {
                    System.out.print(typeJson.get("Type") + ": " + ans.get(j) + " ");
                }
                System.out.println("\n ");
            }
            request.setAttribute("obj", jsonObject);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

我正在像这样在 java 中获取输出;

这是获取 json 值并转换为 obj 的 servlet 类。现在我如何将这些值传递给 JSP 页面并在那里创建一个 for 循环来创建一个像这样的输出的多项选择问题?

【问题讨论】:

    标签: java json jsp servlets mean-stack


    【解决方案1】:

    试试这个,我想这会对你有所帮助。

    hello.jsp

    <!DOCTYPE html>
    <% 
       JSONObject jsonObj = (JSONObject) request.getAttribute("obj");
       if (jsonObj == null)
          jsonObj = new JSONObject();
    %>
    <html lang="en" class="no-js">
        <head>
        <style>
           table {
               font-family: arial, sans-serif;
               border-collapse: collapse;
               width: 100%;
            }
    
            td, th {
               border: 1px solid #dddddd;
               text-align: left;
               padding: 8px;
            }
    
            tr:nth-child(even) {
               background-color: #dddddd;
            }
          </style>
        </head>
    <body>
    
      <h2>HTML Table</h2>
      <table>
      <% 
          JSONArray arr =  jsonObj.getJSONArray("Form");
          if (arr != null) {
             for (int i = 0, i <  jsonArray.length(); i++) {
                 JSONObject typeJson = (JSONObject) form.get(i);
                 JSONArray ans = (JSONArray) typeJson.get("Answers");
    
       %>
          <tr>
            <th>Question <%+i%></th>
         </tr>
         <tr>
            <th><%typeJson.get("Question") + "?"%></th>
         </tr>
         <tr>
            <%
                String type = (String) typeJson.get("Type");
                for (int j = 0, j <  ans.length(); ++) {
    
                   if ("Checkbox".equalsIgnoreCase(type)) { %>
                     <th><input type="checkbox" value="<%ans.get(j)%>"> <%ans.get(j)%></th>
                  <% } else if ("Radio".equalsIgnoreCase(type)) { %>
                     <th><input type="radio" value="<%ans.get(j)%>"> <%ans.get(j)%></th>
                    <% }
                }
            %>
         </tr>
       <%   
             }
          }
      %>
    

    控制器

    @WebServlet("/Puzzle2Servlet")
    public class Puzzle2Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Puzzle2Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        JSONParser parser = new JSONParser();
    
        try {
            Object obj = parser.parse(new FileReader("D:\\Puzzle2.json"));
    
            JSONObject jsonObject = (JSONObject) obj;
            // System.out.println(jsonObject);
    
            JSONArray form = (JSONArray) jsonObject.get("Form");
             request.setAttribute("form", form);
            for (int i = 0; i < form.size(); i++) {
    
                JSONObject typeJson = (JSONObject) form.get(i);
    
                System.out.println(typeJson.get("Question") + "?");
    
                JSONArray ans = (JSONArray) typeJson.get("Answers");
    
                for (int j = 0; j < ans.size(); j++) {
                    System.out.print(typeJson.get("Type") + ": " + ans.get(j) + " ");
                }
                System.out.println("\n ");
            }
            request.setAttribute("obj", jsonObject);
            callJsp("/WEB-INF/hello.jsp");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    }
    
    protected void callJSP(String jspPath) {
    
        RequestDispatcher dispatcher = null;
        dispatcher = getServletContext().getRequestDispatcher(jspPath);
        try {
            dispatcher.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    }

    【讨论】:

      【解决方案2】:

      您可以使用JSTLEL 执行此任务。应该替换 scriptlet(这些东西:&lt;% %&gt;)。 Scriptlet 已过时,自2003 以来我们已停止使用它们。如果你使用 JSTL+EL,它会让你更容易。看看这个:

      在您的 servlet 中:

         protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          List<Question> questions = new ArrayList<Question>(); //create list of Question objects
      
          JSONParser parser = new JSONParser();
      
          try {
              Object obj = parser.parse(new FileReader("D:\\Puzzle2.json"));
              JSONObject jsonObject = (JSONObject) obj;
      
          JSONArray form = (JSONArray) jsonObject.get("Form");
      
              for (int i = 0; i < form.size(); i++) {
                  Question question = new Question(); //create question object for each question
      
                  JSONObject typeJson = (JSONObject) form.get(i);
      
                  question.setQuestion(typeJson.get("Question").toString()); //add question to question object
                  System.out.println(typeJson.get("Question").toString());
                  question.setType(typeJson.get("Type").toString());  //add question to question object
                  System.out.println(typeJson.get("Type").toString());
                  JSONArray ans = (JSONArray) typeJson.get("Answers");
                  ArrayList<String> answers = new ArrayList<String>(); //create arraylist to store answers of this question
                  for (int j = 0; j < ans.size(); j++) {
                      String answer = ans.get(j).toString();
                       System.out.println(answer);
                      answers.add(answer); //add answer to answers arraylist
                  }
                 question.setAnswer(answers); //add answers to question object
      
      
                 questions.add(question); //add question object to list of question objects
              }
          } catch (org.json.simple.parser.ParseException e) {
              e.printStackTrace();
          }
      
          request.setAttribute("json", questions); //this is the name we will get in our jsp 'json'
      
      
          RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/view.jsp");
          dispatcher.forward(request, response);
      
      }
      

      问题对象类:

      public class Question {
      
          String question;
          ArrayList<String> answer;
          String type;
      
      
          public String getQuestion() {
              return question;
          }
          public void setQuestion(String question) {
              this.question = question;
          }
          public ArrayList<String> getAnswer() {
              return answer;
          }
          public void setAnswer(ArrayList<String> answer) {
              this.answer = answer;
          }
          public String getType() {
              return type;
          }
          public void setType(String type) {
              this.type = type;
          }
      
      }
      

      view.jsp:

      <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
      <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
      
      
      <!DOCTYPE html>
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>JSTL + EL EXAMPLE</title>
      </head>
      <body>
      
      
      <c:forEach items="${json}" var="item" varStatus="count">
      <p>Question${count.count}<p> 
      <p>${item.question}?</p>
      
      <c:if test="${item.type eq 'Checkbox'}">
      <c:forEach items="${item.answer}" var="checks">
      <label><input type="checkbox">${checks}</label>
      </c:forEach>
      </c:if>
      
      <c:if test="${item.type eq 'Radio'}">
      <c:forEach items="${item.answer}" var="radios">
      <label><input type="radio">${radios}</label>
      </c:forEach>
      </c:if>
      
      <hr>
      </c:forEach>
      
      
      </body>
      </html>
      

      输出:

      希望这有意义并有所帮助,如果您有任何疑问或问题,请告诉我!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多