Я пытался использовать Sessions, Cookies, Cache et c, но значение продолжает увеличиваться с каждым вызовом базы данных - см. ProfileServlet. java (соответствующая переменная с именем 'Counted' установлена в качестве атрибута сеанса ниже, и значение переменной извлекается из базы данных с использованием DBViewSchedules. java class)
//@MultipartConfig
@WebServlet("/ProfileServlet")
public class ProfileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
String scheduler;
String storedSched;
//Schedule
String chooseDate;
String selectTask;
String selectTask2;
String schedDate;
int taskNum;
String timeFrom;
String timeTo;
String name;
String notes;
String[] DBdate2;
String[] DBtimeFrom2;
String[] DBtimeTo2;
String[] DBname2;
String[] DBnotes2;
String[] DBstatus2;
String addTask;
String saveSched;
HttpSession session;
/**
* @see HttpServlet#HttpServlet()
*/
public ProfileServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@SuppressWarnings("deprecation")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
selectTask = request.getParameter("selectTask");
if(selectTask != null)
{
session = request.getSession();
try {
chooseDate = request.getParameter("chooseDate");
//DBViewSchedules
DBViewSchedules callMethod = DBViewSchedules.getValues(chooseDate);
session.setAttribute("Counted", callMethod.counted);
//Cookie cookie = new Cookie("Counted", String.valueOf(callMethod.counted));
//cookie.setMaxAge(0);
//cookie.setMaxAge(-1);
//response.addCookie(cookie);
//cookie.setValue("0");
request.setAttribute("DBdate2", callMethod.storeDate);
request.setAttribute("DBtimeFrom2", callMethod.storeTFrom);
request.setAttribute("DBtimeTo2", callMethod.storeTTo);
request.setAttribute("DBname2", callMethod.storeName);
request.setAttribute("DBnotes2", callMethod.storeNotes);
request.setAttribute("DBstatus2", callMethod.storeStatus);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setHeader("Expires", "0");
response.setDateHeader("Expires",-1);
request.getRequestDispatcher("SchedulerWithData.jsp").forward(request, response);
session.invalidate();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Планировщик. jsp файл - обратите внимание, что ссылка на 'Countted' указана в функции addRow () (т. е. var number = "$ {Counted}"). Функция 'addRow ()' вызывается в методе 'onload' тега body этой страницы. Ссылка на функцию addData () указана в теге кнопки с id = "selectTask" ниже.
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<title>Insert title here</title>
<link rel="StyleSheet" href="Images/StyleSheet.css">
</head>
<body onload = "addRow()">
<%
//clear cache
response.setHeader("Expires", "0");
response.setHeader("Cache-Control","no-cache, no-store, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
//cookies
Cookie cookies[] = request.getCookies();
String str = null;
for(Cookie c : cookies)
{
if(c.getName().equals("Counted"))
{
c.setMaxAge(0);
c.setValue("0");
str = c.getValue();
System.out.println(" ");
System.out.println("Cookie(Counted1) from Scheduler = " +Integer.valueOf(str));
System.out.println(" ");
}
else
{
System.out.println(" ");
System.out.println("No Cookie from Scheduler.");
System.out.println(" ");
}
}
//session
//if(session.getAttribute("Counted")==null)
//{
//response.sendRedirect("Main.jsp");
//}
//System.out.println("Session number from Scheduler: " +session.getAttribute("Counted"));
%>
<h1 style="text-align: center; padding-top: 50px; font-size: 50px;">Scheduler</h1>
<section class = "section1">
<form action="ProfileServlet" class="container4" enctype="multipart/form-data" id = "formTest">
<label class="lbl2" style="text-align: center;">Search for an existing schedule:</label><br><br>
<input type="date" name="chooseDate" id = "chooseDate"></input>
<button type="submit" class="btn7" name="selectTask" id="selectTask" onClick = "addData()">Search</button><br><br>
</form>
</section>
<section class = "section1">
<form action="ProfileServlet" class="container4">
<label class="lbl2" style="float:middle;";>Create a new Schedule: </label><br><br>
<!--<input type="date" name="date2" id = "date2" style="float:left;"></input>
<button type="submit" class="btn6" name="select" id="select">Search</button><br> -->
<button type="submit" class="btn3" name="save" id="save">Save</button><br>
<table name="table1" id="table1"><br>
<thead>
<tr>
<th>
<label class="lbl2"></label>
</th>
<!--<th>
<label class="lbl2">Task#</label>
</th>-->
<th>
<label class="lbl2">Date</label>
</th>
<th colspan = "2">
<label class="lbl2">Time</label>
</th>
<th>
<label class="lbl2">Task</label>
</th>
<th>
<label class="lbl2">Notes</label>
</th>
<th>
<label class="lbl2">Status</label><br>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" name="checkTask" id = "checkTask">
</td>
<!--<td style = "padding-left: 15px;">
<textarea name="taskNum" id = "taskNum" rows="1" cols="2">${DBtaskNum}</textarea>
</td>-->
<td>
<input type="date" name="date" id = "date" style="float:left;" required = "true" value="${DBdate}"></input>
</td>
<td>
<input type="time" name="from" id = "from" required = "true" value="${DBtimeFrom}"></input>
</td>
<td>
<input type="time" name="to" id = "to" required = "true" value="${DBtimeTo}"></input>
</td>
<td>
<textarea name="taskName" id = "taskName" rows="2" cols="25" value= "In Progress" required = "true" >${DBname}</textarea>
</td>
<td>
<textarea name="notes" id = "notes"rows="2" cols="25">${DBnotes}</textarea>
</td>
<td>
<select name="status" id="status" value = "${DBstatus}">
<OPTION value="Scheduled" name="scheduled" id="scheduled" ${DBstatus == 'Scheduled' ? 'selected': ''}>Scheduled</OPTION>
<OPTION value="In-Progress" name="in-Prog" id="in-Prog" ${DBstatus == 'In-Progress' ? 'selected' : ''}>In-Progress</OPTION>
<OPTION value="Complete" name="complete" id="complete" ${DBstatus == 'Complete' ? 'selected' : ''}>Complete</OPTION>
</select>
</td>
</tr>
</tbody>
</table>
</form>
</section>
<script>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
var number = "${Counted}";
var expires = "expires=Thu, 01 Jan 1977 00:00:00 UTC";
var rIndex, table = document.getElementById("table1");
function addData(){
if(window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var myArr = JSON.parse(xhttp.responseText);
//console.log(myArr);
addRow(myArr); // function to add data to table.
}
}
xhttp.open("POST","/ProfileServlet",true);
var formData = new FormData(document.getElementById('formTest'));
xhttp.send(formData);
}
else console.log('not working');
}
function addRow()
{
var number = "${Counted}";
var expires = "expires=Thu, 01 Jan 2005 00:00:00 UTC";
//var expires = "expires=" -1;
document.cookie = "The Cookie is=" + number + ";" + expires;
//document.cookie = "The Cookie is=" + number;
for(var i = 0; i < number; i++)
{
var dateLoad =
[<c:forEach var="DBdate" items="${DBdate2}">
["<c:out value="${DBdate}"/><br />"],
</c:forEach>
];
var timeFromLoad =
[<c:forEach var="DBtimeFrom" items="${DBtimeFrom2}">
["<c:out value="${DBtimeFrom}"/><br />"],
</c:forEach>
];
var timeToLoad =
[<c:forEach var="DBtimeTo" items="${DBtimeTo2}">
["<c:out value="${DBtimeTo}"/><br />"],
</c:forEach>
];
var nameLoad =
[<c:forEach var="DBname" items="${DBname2}">
["<c:out value="${DBname}"/><br />"],
</c:forEach>
];
var notesLoad =
[<c:forEach var="DBnotes" items="${DBnotes2}">
["<c:out value="${DBnotes}"/><br />"],
</c:forEach>
];
var statusLoad =
[<c:forEach var="DBstatus" items="${DBstatus2}">
["<c:out value="${DBstatus}"/><br />"],
</c:forEach>
];
/////////////////
rIndex = this.rowIndex;
var storedDate = '${storedDate}';
var newRow = table.insertRow(table.length);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
var cell5 = newRow.insertCell(4);
var cell6 = newRow.insertCell(5);
var cell7 = newRow.insertCell(6);
cell2.innerHTML = dateLoad[i];
cell3.innerHTML = timeFromLoad[i];
cell4.innerHTML = timeToLoad[i];
cell5.innerHTML = nameLoad[i];
cell6.innerHTML = notesLoad[i];
cell7.innerHTML = statusLoad[i];
selectedRow();
deleteItems();
}
}
function deleteItems() {
sessionStorage.clear();
localStorage.clear();
}
function selectedRow()
{
var check = document.getElementById("checkTask").value;
var date = document.getElementById("date").value;
var from = document.getElementById("from").value;
var to = document.getElementById("to").value;
var task = document.getElementById("taskName").value;
var notes = document.getElementById("notes").value;
var status = document.getElementById("status").value;
for(var i = 2; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
document.getElementById("checkTask").value = this.cells[0].innerHTML;
document.getElementById("date").value = this.cells[1].innerHTML;
document.getElementById("from").value = this.cells[2].innerHTML;
document.getElementById("to").value = this.cells[3].innerHTML;
document.getElementById("taskName").value = this.cells[4].innerHTML;
document.getElementById("notes").value = this.cells[5].innerHTML;
document.getElementById("status").value = this.cells[6].innerHTML;
}
}
}
selectedRow();
</script>
</body>
</html>
DBViewSchedules. java - файл java с Embedded SQL для извлечения значений из БД - значение для 'Countted' извлекается с помощью этого класса
package studyorganiser;
public class DBViewSchedules {
static Connection conn;
static Statement stmt1;
static PreparedStatement prpStmt1;
static ResultSet rs1;
static Statement stmt2;
static PreparedStatement prpStmt2;
static ResultSet rs2;
static ResultSetMetaData metaData;
static String[] date;
static String[] timeFrom;
static String[] timeTo;
static String[] name;
static String[] notes;
static String[] status;
static int[] ID;
static String[] storeDate;
static String[] storeTFrom;
static String[] storeTTo;
static String[] storeName;
static String[] storeNotes;
static String[] storeStatus;
static int[] storeID;
static String dateRetrieve;
static String dateSet;
static String store;
static int counted = 0;
static int totalValues = 0;
static boolean value = false;
static int i = 0;
static int j = 0;
static int id2;
public DBViewSchedules(int counted2, String[] date2, String[] timeFrom2, String[] timeTo2, String[] name2, String[] notes2, String[] status2, int[] ID2) throws ClassNotFoundException
{
DBViewSchedules.counted = counted2;
for(int k = 0; k<= storeDate.length; k++)
{
this.storeDate[k] = date2[k];
this.storeTFrom[k] = timeFrom2[k];
this.storeTTo[k] = timeTo2[k];
this.storeName[k] = name2[k];
this.storeNotes[k] = notes2[k];
this.storeStatus[k] = status2[k];
this.storeID[k] = ID2[k];
}
}
public static DBViewSchedules getValues(String a) throws ClassNotFoundException, IOException, ServletException //can include the selected drop-down (date) as the input field when ready
{
dateRetrieve = a;
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/sample;create=true","App","user");
String query1 = "Select * from TESTTABLE2 WHERE SCHED_DATE = ?";
prpStmt1 = conn.prepareStatement(query1);
prpStmt1.setString(1, a);
rs1 = prpStmt1.executeQuery();
prpStmt2 = conn.prepareStatement(query1);
prpStmt2.setString(1, a);
rs2 = prpStmt2.executeQuery();
while(rs1.next() && rs1.getString(1).equals(a))
{
//value = true;
dateSet = rs1.getString(1);
System.out.println("Date from DB equals: " +dateSet);
totalValues++;
counted = totalValues;
}
//conn.close();
System.out.println("counted from DB equals: " +counted);
date = new String[counted];
timeFrom = new String[counted];
timeTo = new String[counted];
name = new String[counted];
notes = new String[counted];
status = new String[counted];
ID = new int[counted];
storeDate = new String[counted];
storeTFrom = new String[counted];
storeTTo = new String[counted];
storeName = new String[counted];
storeNotes = new String[counted];
storeStatus = new String[counted];
storeID = new int[counted];
while(rs2.next() && rs2.getString(1).equals(a))
{
i++;
date[i-1] = rs2.getString(1);
timeFrom[i-1] = rs2.getString(2);
timeTo[i-1] = rs2.getString(3);
name[i-1] = rs2.getString(4);
notes[i-1]= rs2.getString(5);
status[i-1] = rs2.getString(6);
ID[i-1] = rs2.getInt(7);
System.out.println("Date ## " +(i) +" = " +date[i-1]);
}
for(j = 0; j < counted; j++)
{
System.out.println("Date # " +(j+1) +" = " +date[j]);
storeDate[j] = date[j];
storeTFrom[j] = timeFrom[j];
storeTTo[j] = timeTo[j];
storeName[j] = name[j];
storeNotes[j] = notes[j];
storeStatus[j] = status[j];
storeID[j] = ID[j];
}
//counted = 0;
//i = 0;
//j = 0;
}catch(SQLException x)
{
System.out.println(x.getErrorCode());
x.printStackTrace();
}
return null;
}
}