WCF Data list always displays null

Anonymous
2022-05-09T05:53:29.06+00:00

IDatabaseDAO

public interface IDatabaseDAO {
public void connect();

public void add(String input);  

public String call(int id);  

public ArrayList<String> callALl();  

public void close();  

}

------------------------------------------------------------------

DatabaseDAO

public class DatabaseDAO implements IDatabaseDAO {
private Connection con;

public void connect() {  
    try {  
        // Verbindung zum DBMS aufbauen  
        this.con = DriverManager.getConnection("jdbc:h2:\~/test", "sa", "");  

        // Statement erzeugen  
        Statement statement = con.createStatement();  
        String sql = "CREATE TABLE school " +  
                "(id INTEGER not NULL, " +  
                "date VARCHAR(19) not NULL," +  
                "entrytype VARCHAR(255) not NULL," +  
                "entrytext VARCHAR(255) not NULL," +  
                "teacher VARCHAR(255) not NULL)";  

        // Statement ausführen  
        statement.execute(sql);  

        // Aufräumarbeiten  
        statement.close(); // Statement schließen  
    } catch (SQLException e) {  
        e.printStackTrace();  
    }  
}  

public void add(String input) {  
    String[] ar = input.split(";");  
    try {  
        Statement statement = con.createStatement();  
        String sql = "INSERT INTO school " + "VALUES (" + Integer.parseInt(ar[0]) + "," + ar[1] + "," + ar[2] + "," + ar[3] + "," + ar[4] + ");";  
        statement.execute(sql);  
        statement.close();  
    } catch (SQLException e) {  
        e.printStackTrace();  
    }  
}  

@Override  
public String call(int id) {  
    String help = "";  
    try {  
        Statement statement = con.createStatement();  
        String sql = "SELECT * FROM school WHERE ID=" + id + ";";  
        statement.close();  
        ResultSet resultSet = statement.executeQuery(sql);  
        help = resultSet.getString(id);  
    } catch (SQLException e) {  
        e.printStackTrace();  
    }  
    return help;  
}  

@Override  
public ArrayList<String> callALl() {  
    ArrayList<String> ar = new ArrayList<>();  
    try {  
        Statement statement = con.createStatement();  
        String sql = "SELECT * FROM school";  
        ResultSet resultSet = statement.executeQuery(sql);  
        while (resultSet.next()) {  
            ar.add(String.valueOf(resultSet.getInt("id")));  
            ar.add(resultSet.getString("date"));  
            ar.add(resultSet.getString("entrytype"));  
            ar.add(resultSet.getString("entrytext"));  
            ar.add(resultSet.getString("teacher"));  
        }  
        statement.close();  
    } catch (SQLException e) {  
        e.printStackTrace();  
    }  
    return ar;  
}  

public void close() {  
    try {  
        Statement statement = con.createStatement();  
        statement.execute("DROP TABLE school");  

        statement.close();  
        con.close();  
    } catch (SQLException e) {  
        e.printStackTrace();  
    }  
}  

}

------------------------------------------------------------------

DATA

public class DataStore {
private static DataStore instance;
private Set<Pupil> pupils = new HashSet<>();

private DataStore() {  
}  

public static DataStore getInstance() {  
    if (instance == null) {  
        instance = new DataStore();  
    }  
    return instance;  
}  

public void setPupils(Set<Pupil> pupils) {  
    this.pupils.addAll(pupils);  
}  

public Set<Pupil> getPupils() {  
    return pupils;  
}  

public Pupil getPupilById(UUID id) {  
    for (Pupil pupil : pupils) {  
        if (pupil.getId().equals(id)) {  
            return pupil;  
        }  
    }  
    return null;  
}  

}

------------------------------------------------------------------

Interfaces

@mutia keyza ("/importData")
public interface IImportData {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Set<Pupil> importDataFromJSON(Set<Pupil> pupils);
}

@mutia keyza ("/pupil")
public interface IResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@mutia keyza ("/{pupil_id}/absence")
Absence newAbsence(@PathParam("pupil_id") String id,
Absence absence);

@GET  
@Produces(MediaType.APPLICATION_JSON)  
@Path("/{pupil_id}/absence/{absence_id}")  
Absence getAbsenceById(@PathParam("pupil_id") String stId,  
                       @PathParam("absence_id") String abId);  

@PUT  
@Consumes(MediaType.APPLICATION_JSON)  
@Produces(MediaType.APPLICATION_JSON)  
@Path("/{pupil_id}/absence/{absence_id}/excuse")  
boolean excuseAbsence(@PathParam("pupil_id") String stId,  
                   @PathParam("absence_id") String abId);  

}

------------------------------------------------------------------

Resource.java

public class Resource implements IResource {
@Override
public Absence newAbsence(String id, Absence absence) {
DataStore.getInstance().getPupilById(UUID.fromString(id)).addAbsence(absence);
return DataStore.getInstance().getPupilById(UUID.fromString(id)).getAbsenceById(absence.getId());
}

@Override  
public Absence getAbsenceById(String stId, String abId) {  
    return DataStore.getInstance().getPupilById(UUID.fromString(stId)).getAbsenceById(UUID.fromString(abId));  
}  

@Override  
public boolean excuseAbsence(String stId, String abId) {  
    DataStore.getInstance().getPupilById(UUID.fromString(stId)).getAbsenceById(UUID.fromString(abId)).setExcused(true);  
    return DataStore.getInstance().getPupilById(UUID.fromString(stId)).getAbsenceById(UUID.fromString(abId)).isExcused();  
}  

}

------------------------------------------------------------------

ImportData.java

public class ImportData implements IImportData {
@Override
public Set<Pupil> importDataFromJSON(Set<Pupil> pupils) {
DataStore.getInstance().setPupils(pupils);
return DataStore.getInstance().getPupils();
}
}

------------------------------------------------------------------

index.jsp

<body>
<h1><%= "Hello World!" %>
</h1>
<br/>
<a href="${pageContext.request.contextPath}/PupilListServlet">Pupil list</a>
</body>

------------------------------------------------------------------

dropdownList.jsp

<%@ page import="com.example.test.model.Pupil" %>
<%@ page import="com.example.test.data.DataStore" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="pupils" class="com.example.test.PupilsBean" scope="request"/>
<html>
<head>
<title>Pupil list</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/AbsenceServlet" method="get">
<select name="pupilselect">
<% for (Pupil pupil : pupils.getPupils()) {%>
<option value="<%=pupil.getId()%>"><%=pupil.getFirstName() + " " + pupil.getLastName()%></option>
<%}%>
</select>
<input type="submit" name="Submit">
</form>
</body>
</html>

absenceList.jsp

<%@ page import="com.example.test.model.Pupil" %>
<%@ page import="com.example.test.model.Absence" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="a" class="com.example.test.model.Pupil" scope="request"/>
<html>
<head>
<title>Absence List</title>
</head>
<body>
<table>
<% for (Absence absence : a.getAbsences()) {%>
<tr>
<td><%=absence.toString()%>
</td>
</tr>
<%}%>
</table>
</body>
</html>

------------------------------------------------------------------

PupilListServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    request.setAttribute("pupils", new PupilsBean(DataStore.getInstance().getPupils()));  
    request.getRequestDispatcher("dropdownList.jsp").forward(request, response);  
}  

AbsenceServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    String s = request.getParameter("pupilselect");  
    request.setAttribute("a", DataStore.instance.getPupilById(UUID.fromString(s)));  
    request.getRequestDispatcher("absenceList.jsp").forward(request, response);  
}  

------------------------------------------------------------------

HTTP Test

Add import data

POST http://localhost:8080/{<!-- -->{deployment_name}}/api/importData
Content-Type: application/json

< testdata.json

{%
client.test("Request executed successfully", function() {
client.assert(response.status === 204, "Response status is not 200")
});
%}

Add new absence

POST http://localhost:8080/{<!-- -->{deployment_name}}/api/pupil/0cb39981-442e-4e57-89e2-6c0128bf055b/absence
Content-Type: application/json

{
"excused": false,
"from": "2022-05-09",
"reason": "Exam anxiety",
"to": "2022-05-09"
}

{%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200")
client.assert(response.body.hasOwnProperty("id"), "Cannot find 'id' option in response");
client.global.set("new_absence_id", response.body.id);
});
%}

Get added absence

GET http://localhost:8080/{<!-- -->{deployment_name}}/api/pupil/0cb39981-442e-4e57-89e2-6c0128bf055b/absence/{<!-- -->{new_absence_id}}
Accept: application/json

{%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200");
client.assert(response.body.reason === "Exam anxiety", "Response JSON content not correct");
});
%}

Get added pupil

PUT http://localhost:8080/{<!-- -->{deployment_name}}/api/pupil/0cb39981-442e-4e57-89e2-6c0128bf055b/absence/{<!-- -->{new_absence_id}}/excuse
Accept: application/json

{%
client.test("Request executed successfully", function() {
client.assert(response.status === 204, "Response status is not 200, for excuse action");
});
%}

Get updated absence

GET http://localhost:8080/{<!-- -->{deployment_name}}/api/pupil/0cb39981-442e-4e57-89e2-6c0128bf055b/absence/{<!-- -->{new_absence_id}}
Accept: application/json

{%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200");
client.assert(response.body.excused === true, "Absence not correctly excused");
});
%}

Microclient, add to servlet:

ITest itest = RestClientBuilder.newBuilder().baseUri(URI.create("http://localhost:8080/rest-1.0-SNAPSHOT/api")).followRedirects(true).build(ITest.class);

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,412 questions
0 comments No comments
{count} votes

Accepted answer
  1. ElChefe 76 Reputation points
    2022-06-20T05:53:58.377+00:00

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <jsp:useBean id="absenceList" type="java.util.ArrayList<model.Absence>" scope="request"></jsp:useBean>
    <html>
    <style>
    table, th, td {
    border:1px solid black;
    }
    </style>
    <head>
    <title>Title</title>
    </head>
    <body>
    <table>
    <tr>
    <th>UUID</th>
    <th>to</th>
    <th>from</th>
    <th>reason</th>
    <th>excused</th>
    </tr>
    <%
    for (Absence absence : absenceList) {
    String s = " <tr>\n" +
    " <td>" + absence.getId() + "</td>\n" +
    " <td>" + absence.getTo() + "</td>\n" +
    " <td>" + absence.getFrom() + "</td>\n" +
    " <td>" + absence.getReason() + "</td>\n" +
    " <td>" + absence.isExcused() + "</td>\n" +
    " </tr>";
    out.println(s);
    }
    %>

    </table>
    </body>
    </html>

    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. ElChefe 76 Reputation points
    2022-06-20T05:53:32.007+00:00

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <jsp:useBean id="pupilList" type="java.util.ArrayList<model.Pupil>" scope="session"></jsp:useBean>
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>

    <form action="${pageContext.request.contextPath}/GetAllAbsencesServlet" method="post">
    <label for="pupil">Choose a pupil:</label>
    <select id="pupil" name="pupil">
    <%
    for(Pupil pupil : pupilList){
    out.println("<option value=" + pupil.getId() + ">" + pupil.getFirstName() + " " + pupil.getLastName() + "</option>");
    }
    %>

    </select>  
    <input type="submit">  
    

    </form>
    </body>
    </html>

    0 comments No comments

  2. ElChefe 76 Reputation points
    2022-05-23T05:55:08.57+00:00

    <jsp:useBean id="pupilList" type="java.util.ArrayList<model.Pupil>" scope="session"></jsp:useBean>

    <form action="${pageContext.request.contextPath}/GetAllAbsencesServlet" method="post">
    <label for="pupil">Choose a pupil:</label>
    <select id="pupil" name="pupil">
    <%
    for(Pupil pupil : pupilList){
    out.println("<option value=" + pupil.getId() + ">" + pupil.getFirstName() + " " + pupil.getLastName() + "</option>");
    }
    %>

    </select>
    <input type="submit">
    

    </form>

    private static DataStore instance;
    private Set<Pupil> pupils = new HashSet<>();

    private DataStore() {}
    
    public static DataStore getInstance() {
        if (instance == null) {
            instance = new DataStore();
        }
        return instance;
    }
    
    public Set<Pupil> getPupils(){
        return pupils;
    }
    
    public Optional<Pupil> getPupilById(UUID id) {
        return pupils.stream()
                .filter(pupil -> pupil.getId().equals(id))
                .findFirst();
    }
    

    IEmployeeResource client = RestClientBuilder.newBuilder().baseUri(URI.create("http://localhost:8080/Uebung_11-1.0-SNAPSHOT/api")).followRedirects(true).build(IEmployeeResource.class);

    private static DataStore dataStore;
    private List<Pupil> pupils = new ArrayList<>();

    public static DataStore getInstance() {
        if(dataStore == null) {
            dataStore = new DataStore();
        }
        return dataStore;
    }
    

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    DataStore dataStore = DataStore.getInstance();
    String pupilUUID = request.getParameter("pupil");
    Pupil pupil = dataStore.getSpecificPupil(pupilUUID);
    List<Absence> absenceList = pupil.getAbsences();

        request.setAttribute("absenceList",absenceList);
    
        String url = "ListAllAbsences.jsp";
        request.getRequestDispatcher(url).forward(request,response);
    }
    

    <dependency>
    <groupId>org.eclipse.microprofile.rest.client</groupId>
    <artifactId>microprofile-rest-client-api</artifactId>
    <version>3.0</version>
    </dependency>

    0 comments No comments

  3. ElChefe 76 Reputation points
    2022-06-20T05:53:03.87+00:00

    <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <!DOCTYPE html>
    <html>
    <head>
    <title>Pupil Absences</title>
    </head>
    <body>
    <h1><%= "Pupil Absences" %>
    </h1>
    <br/>
    <form method="post">
    <button formaction="${pageContext.request.contextPath}/AbsenceServlet">
    Click me
    </button>
    </form>

    <a href="hello-servlet">Hello Servlet</a>
    </body>
    </html>

    0 comments No comments

  4. ElChefe 76 Reputation points
    2022-06-20T05:53:23.117+00:00

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }  
    
    @Override  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    
        DataStore dataStore = DataStore.getInstance();  
        List<Pupil> pupilList = dataStore.getPupils();  
    
        request.getSession().setAttribute("pupilList",pupilList);  
        String url = "ListPupils.jsp";  
        request.getRequestDispatcher(url).forward(request,response);  
    }
    
    0 comments No comments