I want to create a small quiz app in jsp which will ask the questions which are stored in the array. It should ask the ask until the last index of array. Here answer is also stored in the array. What I have done so far is:
Main Servlet
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {
session = request.getSession(true);
Quiz quiz = new Quiz();
if (session.isNew()) {
quiz.setTotalCorrectAnswers(0);
quiz.setCounter(0);
question = quiz.getNextQuestion(0);
answer = quiz.getAnswer(0);
}
session.setAttribute("quizes", quiz);
request.setAttribute("quiz", quiz);
request.setAttribute("currentQuestion", question);
request.setAttribute("error", false);
RequestDispatcher view = request.getRequestDispatcher("quiz.jsp");
view.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {
String userAnswer = request.getParameter("txtAnswer");
Quiz quiz = (Quiz) session.getAttribute("quizes");
boolean error = false;
if (userAnswer.equals(quiz.getAnswer(quiz.getCounter()))) {
totalQuestions++;
quiz.setTotalCorrectAnswers(totalQuestions);
quiz.setCounter(quiz.getCounter() + 1);
session.setAttribute("nextQuestion", quiz.getCounter() + 1);
} else {
quiz.setTotalCorrectAnswers(totalQuestions);
quiz.setCounter(quiz.getCounter());
error = true;
}
session.setAttribute("quizes", quiz);
if(quiz.getTotalCorrectAnswers()>=5){
session.invalidate();
generateQuizOverPage(out);
}else{
request.setAttribute("quiz", quiz);
request.setAttribute("currentQuestion", quiz.getNextQuestion(quiz.getCounter()));
request.setAttribute("error", error);
RequestDispatcher view = request.getRequestDispatcher("quiz.jsp");view.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
The Quiz model
String[] numberSeries = {
"3, 1, 4, 1, 5, ",
"1, 1, 2, 3, 5, ",
"1, 4, 9, 16, 25, ",
"2, 3, 5, 7, 11, ",
"1, 2, 4, 8, 16, "
};
String[] answer = {"9", "8", "36", "13", "32"};
private int counter;
private boolean isCorrect;
private int totalCorrectAnswers;
public Quiz() {
counter = 0;
isCorrect = false;
totalCorrectAnswers = 0;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public boolean isIsCorrect() {
return isCorrect;
}
public void setIsCorrect(boolean isCorrect) {
this.isCorrect = isCorrect;
}
public int getTotalCorrectAnswers() {
return totalCorrectAnswers;
}
public void setTotalCorrectAnswers(int totalCorrectAnswers) {
this.totalCorrectAnswers = totalCorrectAnswers;
}
public String getNextQuestion(int index) {
return numberSeries[index];
}
public String getAnswer(int index) {
return answer[index];
}
and the quiz.jsp file:
<%#page import="com.app.numberquiz.models.Quiz"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
Quiz quiz = (Quiz) request.getAttribute("quiz");
String currQuest = (String) request.getAttribute("currentQuestion");
Boolean error = (Boolean) request.getAttribute("error");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form method='post'>
<h3>Have fun with NumberQuiz!</h3>
<p>Your current score is:
<% out.print(quiz.getTotalCorrectAnswers()); %> </br></br>
<p>Guess the next number in the sequence! </p>
<p>["<% out.print(currQuest); %><span style='color:red'>?</span>"]</p>
<p>Your answer:<input type='text' name='txtAnswer' value='' /></p>
<% if (error) { %>
<p style='color:red'>Your last answer was not correct! Please try again</p>
<% } %>
<p><input type='submit' name='btnNext' value='Next' /></p>
</form>
</body>
</html>
In the first run it shows the view correctly but when I reload the page it start to show null in the currQues in the view is it a problem in session if yes then where i have done wrong can anyone please explain it to me thank you!!
When you reload the page doGet method will work, you are setting question if the session is newly created and you put it in request. So when you reload your page session is not newly created and your currentQuestion is not set. You schould add an else case and assign the question or you should put these variables also in your session and retrieve it from the session in your jsp.
Related
i am developing a servlet app that show the table in jsp and than insert a value of the that table in other table (inserting a id from table to another table) as i checked with debugger there is no problem to read a value from first table and insert it to scound table but when i clicked on insert button after some moment i have this error(java.lang.StackOverflowError) also when i check mysql table i see, i have the value more than the time that i insert it like a infinite loop.about the table that i am reading a data i can say (name of the table :class,id( type:int(primary),null:no,default:none,Extra:AUTO_INCREMENT),name(type:
varchar,null:yes,default:current_timestamp)) and the table i am inserting a value is(table name test,id(type:int(index),null:yes,default:null))
i want to say it again that beside of the error i have more insertion that i click on jsp in sql table(like 100 times more)
// servlet class
public class add_course extends HttpServlet {
private dbutil dbutil;
#Resource(name="jdbc/web_student_tracker")
private DataSource dataSource;
#Override
public void init() throws ServletException {
//dbutil= new dbutil(dataSource);
super.init();
try {
dbutil=new dbutil(dataSource);
}
catch(Exception exc) {
throw new ServletException(exc);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// List<student> student;
// try {
// student = dbutil.getcourse();
// request.setAttribute("select",student);
// RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
// dispatcher.forward(request,response);
// } catch (Exception e) { // TODO Auto-generated catch block
// e.printStackTrace();
// }
try {
String thecommand=request.getParameter("command");
if(thecommand==null) {
thecommand="LIST";
}
switch(thecommand) {
case"LIST":
listcourse(request,response);
break;
case"insert":
insertcourse(request,response);
break;
}
}
catch(Exception exc) {
throw new ServletException(exc);
}
}
private void insertcourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
int courseid = Integer.parseInt(request.getParameter("courseid"));
student thestudent=new student(courseid);
dbutil.insetcourse(thestudent);
insertcourse(request,response);
}
private void listcourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<student> student=dbutil.getcourse();
request.setAttribute("select",student);
RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
dispatcher.forward(request,response);
}
}
// db class
public List <student> getcourse() throws Exception{
List<student> course=new ArrayList<>();
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
try {
myConn=dataSource.getConnection();
String sql="select id from class";
myStmt=myConn.createStatement();
myRs=myStmt.executeQuery(sql);
while (myRs.next()) {
int id = myRs.getInt("id");
student tempstudent = new student(id);
course.add(tempstudent);
}
return course;
}
finally {
// close JDBC objects
close(myConn, myStmt, myRs);
}
}
public void insetcourse(student thestudent)throws SQLException {
Connection myConn = null;
PreparedStatement myStmt=null;
/////////
try {
myConn = dataSource.getConnection();
String sql="insert into test"+"(id)"+"value(?)";
myStmt=myConn.prepareStatement(sql);
myStmt.setInt(1,thestudent.getId());
myStmt.execute();
}
finally {
close(myConn,myStmt,null);
}
}
}
//jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<c:forEach var="tempstudent" items="${select}">
<c:url var="insert" value="add_course">
<c:param name="command" value="insert"/>
<c:param name="courseid" value="${tempstudent.id}"/>
</c:url>
<tr>
<td>${tempstudent.id}</td>
<td>
<a href="${insert}"
onclick="if (!(confirm('Are you sure you want to insert this student?'))) return false">
insert</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
if you want to insert multiple records in a table why not use a for loop instead of recursive method.
private void insertcourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
// Assuming you are getting multiple courseid in your request,
Object[] courseid = request.getParameter("courseid");
for(Object obj : courseid)
{
student thestudent=new student(courseid);
dbutil.insetcourse(thestudent);
}
request.setAttribute("message", "Records loaded successfully");
RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
dispatcher.forward(request,response);
}
when the insertion is done, you dipatch result to forntend, so that user would be notified,
if you want to insert only one record just call insert onlyonce.
but looking at your jsp code, you are generating insert hyper link for every record, hence you will be inserting only one record at a time, in that case you can follow below code.
int courseid = Integer.parseInt(request.getParameter("courseid"));
student thestudent=new student(courseid);
dbutil.insetcourse(thestudent);
request.setAttribute("message", "Records loaded successfully");
RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
dispatcher.forward(request,response);
I am developing a Login with jsp, servlet and ajax. When I enter the password incorrectly it shows the error message, but when I enter the correct key loads welcome.jsp into the div reserved for the error message.
From servlet I send the message as response and with javascript adding this message to the div id="text" content.
Code JSP:
<body>
<script>
$(document).ready(function () {
$('#submitLogin').click(function (event) {
var nombreVar = $('#txtUsuario').val();
var apellidoVar = $('#txtPassword').val();
$.post('ServletLoguin', {
nombre: nombreVar,
apellido: apellidoVar
}, function (responseText) {
$('#texto').html(responseText);
});
});
});
</script>
<form id="formLogin" >
<label>ingrese usuario</label>
<input type="text" id="txtUsuario"><br> <br>
<label>ingrese clave</label>
<input type="password" id="txtPassword"><br><br>
<input type="button" id="submitLogin" value="Iniciar Sesion">
</form>
<div id="tabla">
<p id="texto" style="color:red;"></p>
</div>
</body>
Code Java servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String usuario = request.getParameter("nombre");
String password = request.getParameter("apellido");
try {
CallableStatement cl = Conexion.getConexion().prepareCall("{call SGVC_Login(?,?)}");
cl.setString(1, usuario);
cl.setString(2, password);
ResultSet rs = cl.executeQuery();
if (rs.next()) {
HttpSession sesionLoguin = request.getSession();
sesionLoguin.setAttribute("perfil", rs.getString(12));
sesionLoguin.setAttribute("nom", rs.getString(5));
sesionLoguin.setAttribute("apePaterno", rs.getString(3));
sesionLoguin.setAttribute("apeMaterno", rs.getString(4));
sesionLoguin.setAttribute("codUser", rs.getString(1));
if (sesionLoguin.getAttribute("perfil").equals("TVENTA") || sesionLoguin.getAttribute("perfil").equals("TCOBRANZA")) {
//request.getRequestDispatcher("principal1.jsp").forward(request, response);
response.sendRedirect("principal1.jsp");
//request.getRequestDispatcher("ServletRegistrarVenta.java").forward(request, response);
} else {
//request.getRequestDispatcher("principal2.jsp").forward(request, response);
response.sendRedirect("principal2.jsp");
}
} else {
response.setContentType("text/html; charset=iso-8859-1");
out.println("error");
}
} catch (Exception e) {
System.err.println("error " + e);
}
}
Since you are using ajax, it will not reload your page. So either you can use form.submit() or from your ajax call back method use window.location.href = '<your_page>.jsp' after passing success as response like
if(reponseText == 'principal1')
window.location.href = 'principal1.jsp';
else if(reponseText == 'principal2')
window.location.href = 'principal2.jsp';
else
$('#texto').html(responseText);
>
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String usuario = request.getParameter("nombre");
String password = request.getParameter("apellido");
try {
CallableStatement cl = Conexion.getConexion().prepareCall("{call SGVC_Login(?,?)}");
cl.setString(1, usuario);
cl.setString(2, password);
ResultSet rs = cl.executeQuery();
if (rs.next()) {
HttpSession sesionLoguin = request.getSession();
sesionLoguin.setAttribute("perfil", rs.getString(12));
sesionLoguin.setAttribute("nom", rs.getString(5));
sesionLoguin.setAttribute("apePaterno", rs.getString(3));
sesionLoguin.setAttribute("apeMaterno", rs.getString(4));
sesionLoguin.setAttribute("codUser", rs.getString(1));
if (sesionLoguin.getAttribute("perfil").equals("TVENTA") || sesionLoguin.getAttribute("perfil").equals("TCOBRANZA")) {
response.setContentType("text/html; charset=iso-8859-1");
out.write("principal1");
} else {
response.setContentType("text/html; charset=iso-8859-1");
out.write("principal2");
}
} else {
response.setContentType("text/html; charset=iso-8859-1");
out.write("error");
}
} catch (Exception e) {
System.err.println("error " + e);
}
}
I'm new on ajax and want to get data from action class to jsp.
File : getRole.jsp
<head>
<script type="text/javascript">
var request;
function loaddata()
{
var id = document.getElementById("newRole").value;
alert("hi : "+ id);
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("display_info").innerHTML = this.responseText;
}
};
xhttp.open("GET", "loadData?id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<label for="focusedInput" id="abc"><h4>Enter Id : </h4></label>
<input type="text" class="form-control" name="newRole" id="newRole" onkeyup="loaddata();">
<div id="display_info" ></div>
</div>
<div class="col-sm-2"></div>
</div>
</body>
File : loadData.java
public class loadData extends ActionSupport implements ServletRequestAware, ServletResponseAware{
private static final long serialVersionUID = 1L;
String url = "jdbc:mysql://localhost:3306/struts";
String user = "username";
String pass = "password";
HttpServletRequest request;
HttpServletResponse response;
#Override
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
this.request = request;
}
public HttpServletRequest getServletRequest() {
return request;
}
#Override
public void setServletResponse(HttpServletResponse response) {
// TODO Auto-generated method stub
this.response = response;
}
public HttpServletResponse getServletResponse()
{
return response;
}
public String execute()
{
try{
String id = request.getParameter("id");
String name = "null.";
System.out.println("in servlet : " + id);
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =DriverManager.getConnection(url, user, pass);
String s = "select * from tempemp where id="+id;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(s);
while(rs.next())
{
name = rs.getString("role");
System.out.println(name);
}
PrintWriter out = response.getWriter();
out.println("Name: "+name);
con.close();
}
catch(Exception e){
e.printStackTrace();
}
return SUCCESS;
}
}
I want to get Id from the user and then print role based on that Id.
I only want to use ajax not json. So please answer me only ajax code.
You have to return null in the action instead of success.
Returning null will do no further processing it will just send present response to the client.
Returning SUCCESS will search for specific jsp page defined for that result in struts.xml file.
this.responseText You will get your name.
For More reference https://struts.apache.org/docs/ajax.html
I have a simple login page. when logged it goes through javabean dao and servlets.. everything is fine with it... but Along with the logging in, I want to retrieve the data and save that data through out the application by using session. so I can display the username designation and usertype on the jsp header. for all the pages. below is my logindao and servlet page please help me.
LoginDao:
public class LoginDao {
public static String validate(String name, String pass) {
String Usertype="";
PreparedStatement pst = null;
ResultSet rs = null;
try{
Connection conn=ConnectionProvider.getConn();
pst = conn.prepareStatement("select * from employee where Emp_id=? and Pwd=?");
pst.setString(1, name);
pst.setString(2, pass);
rs = pst.executeQuery();
if(rs.next()){
Usertype=rs.getString("Usertype");
}
} catch (Exception e) {
System.out.println(e);
}
finally {
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return Usertype;
}
}
LoginServlet:
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("Emp_id");
String p=request.getParameter("Pwd");
String Usertype="";
Usertype=LoginDao.validate(n, p);
if (Usertype.trim()!="" && Usertype.length()>0) {
HttpSession session = request.getSession(true); // The session will be set only if there is a valid login
session.setAttribute("name", n);
session.setAttribute("Usertype",Usertype);
RequestDispatcher rd=request.getRequestDispatcher("/daywise.jsp");
rd.forward(request,response);
}
else{
out.print("<p style=\"color:red\">Sorry Employee ID or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");
rd.include(request,response);
}
out.close();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Bean Class User:
public class User {
private String Emp_id;
private String Pwd;
private String Emp_name;
private String Designation;
private String Emailid;
private String Phone;
private String Usertype;
// getter and setter methods}
resultg jsp page:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Employee name:<input type="text" value="<%=session.getAttribute("Emp_name")%>">
Employee Id:<input type="text" value="<%=session.getAttribute("Emp_id")%>">
Designation:<input type="text" value="<%=session.getAttribute("Designation")%>">
User Type:<input type="text" value="<%=session.getAttribute("Usertype")%>">
</body>
</html>
Try it please
request.getSession().setAttribute("name", n);
I'm using this.
Github LoginController
What I am trying to accomplish is not too complex, but I am having a bit of trouble as I am not well versed in AJAX.
When it is implemented, I will have a JSP that has a button which invokes an Asynchronous Servlet. The servlet will run a long running task and provide dynamic feedback to the user by adding rows to a table when parts of the task are completed.
Before I attempt to write the final version, I am doing a proof of concept to get an understanding of how this will work. However, I'm running into a snag. When I use an AJAX call upon clicking a button, the function works as expected when the call is to a regular synchronous servlet. However, as soon as I make the servlet asynchronous, the updates are not displayed.
Would anybody be able to provide some insight into what's going wrong?
My JSP looks like this:
<html>
<body>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#mybutton').click(function() {
$.get('someservlet', function(responseJson) {
$.each(responseJson, function(index, item) {
$('<ul>').appendTo('#somediv');
$('<li>').text(item.row1).appendTo('#somediv');
$('<li>').text(item.row2).appendTo('#somediv');
$('<li>').text(item.row3).appendTo('#somediv');
$('<li>').text(item.row4).appendTo('#somediv');
});
});
});
});
</script>
<p><button id="mybutton">Click to add things</button></p>
<div id="somediv"></div>
</body>
</html>
My Asynchronous Servlet doGet() method looks like this:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
final AsyncContext asyncContext = request.startAsync();
final PrintWriter writer = response.getWriter();
asyncContext.setTimeout(10000);
asyncContext.start(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
List<Row> rows = new ArrayList<Row>();
rows.add(new Row(i, i + 1, i + 2, i + 3));
String json = new Gson().toJson(rows);
writer.write(json);
writer.flush();
log.info("Wrote to JSON: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
asyncContext.complete();
}
});
Any thoughts? It seems like my AJAX call that occurs when I click the button only accepts a response from the main servlet thread. Perhaps I need to call a JavaScript function from the asynchronous write() calls? I'm just not sure how to do this or if this would be the correct method of execution.
have a look at
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/async-servlet/async-servlets.html
OK!
So, I figured it out. It's not quite as fancy as I would have liked it to be, but it works. And, it's just a proof of concept for implementing what I am working on. If anyone can provide further insight, I've love to be able to implement this using server push instead of polling.
Thoughts?
My JSP looks like this:
<html>
<head>
<script src="jquery-1.7.1.min.js" type="text/javascript" ></script>
<script>
$(document).ready(function() {
var prevDataLength;
var nextLine = 0;
var pollTimer;
$('#abutton').click(function() {
$(function(){
var x = new $.ajaxSettings.xhr();
x.open("POST", "someservlet");
handleResponseCallback = function(){
handleResponse(x);
};
x.onreadystatechange = handleResponseCallback;
pollTimer = setInterval(handleResponseCallback, 100);
x.send(null);
});
});
function handleResponse(http) {
if (http.readyState != 4 && http.readyState != 3)
return;
if (http.readyState == 3 && http.status != 200)
return;
if (http.readyState == 4 && http.status != 200) {
clearInterval(pollTimer);
}
while (prevDataLength != http.responseText.length) {
if (http.readyState == 4 && prevDataLength == http.responseText.length)
break;
prevDataLength = http.responseText.length;
var response = http.responseText.substring(nextLine);
var lines = response.split('\n');
nextLine = nextLine + response.lastIndexOf(']') + 1;
if (response[response.length-1] != ']')
lines.pop();
for (var i = 0; i < lines.length; i++) {
var line = $.parseJSON(lines[i]);
addToTable(line);
}
}
if (http.readyState == 4 && prevDataLength == http.responseText.length)
clearInterval(pollTimer);
}
function addToTable(JSONitem) {
$.each(JSONitem, function(index, item) {
$('<tr>').appendTo('#sometablebody')
.append($('<td>').text(item.name))
.append($('<td>').text(item.message))
.append($('<td>').text(item.number))
.append($('<td>').append($('<a>').attr('href', item.link).text('link')));
});
}
});
</script>
<title>Async Test</title>
</head>
<body>
<p><button id="abutton">Click to add things</button></p>
<div id="somediv">
<table border="1">
<thead>
<tr>
<td>Name</td>
<td>Message</td>
<td>Number</td>
<td>Link</td>
</tr>
</thead>
<tbody id="sometablebody"></tbody>
</table>
</div>
</body>
</html>
My Asynchronous Servlet doGet() method looks like this:
request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
final AsyncContext asyncContext = request.startAsync();
final PrintWriter writer = response.getWriter();
asyncContext.setTimeout(60000);
asyncContext.start(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
List<Row> list = new ArrayList<Row>();
list.add(new Row("First", "This is the first", String.valueOf(i), "link" + i));
list.add(new Row("Second", "This is the second", String.valueOf(i), "link" + i));
list.add(new Row("Third", "This is the third", String.valueOf(i), "link" + i));
String json = new Gson().toJson(list);
asyncContext.getResponse().setContentType("application/json");
asyncContext.getResponse().setCharacterEncoding("UTF-8");
try {
asyncContext.getResponse().getWriter().write(json);
asyncContext.getResponse().getWriter().flush();
} catch (IOException ex) {
System.out.println("fail");
}
Thread.sleep(250);
} catch (InterruptedException ex) {
break;
}
}
asyncContext.complete();
}
});
Additionally, for this all to work, I implemented a simple Row class:
public class Row {
private String name;
private String message;
private String number;
private String link;
public Row(String name, String message, String number, String link) {
setName(name);
setMessage(message);
setNumber(number);
setLink(link);
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}