Как передать объект в JSP и создать несколько DIV в цикле? - PullRequest
0 голосов
/ 03 июня 2018
{

    "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 следующим образом;

enter image description here Это класс сервлета, который получает значения json и конвертирует их в obj. Теперь я могу передать эти значения на страницу JSP и создать там цикл for.выход?enter image description here

Ответы [ 2 ]

0 голосов
/ 03 июня 2018

Вы можете использовать JSTL и EL для этой задачи.Который должен заменить скриптлеты (эти вещи: <% %>).Скриплеты устарели, мы перестали их использовать с 2003 .Вам будет намного легче, если вы используете JSTL + EL. Проверьте это:

В вашем сервлете:

   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>

Выход:

enter image description here

Надеюсь, что это имеет смысл и поможет, дайте мне знать, если у вас есть какие-либо вопросы или проблемы!

0 голосов
/ 03 июня 2018

попробуйте, я думаю, это вам поможет.

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();
    }
}

}

...