Pagination issue with JSP - java

I am able to display a table when a user clicks a search button. But now I want to split the table into chunks of 20 rows where the user can click next or previous to go forward and backward through all of the data. I am not allowed to use JavaScript for this assignment. Only JSP, Java, HTML.
The two debugging out.print() calls are not showing up. A different page is being loaded after one of the buttons is clicked, but the two debugging out.print calls are not displaying any HTML. I have checked out How to know which button is clicked on jsp this post but had no luck.
<form method="GET">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
try {
if ("Previous".equals(val1)) { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if ("Next".equals(val2)) { // Get next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
I also have a follow up question. If the user clicks next or previous button, will my current table on the page be overwritten by the new one? That is my intent but I don't know if it will work that way.
I WAS ABLE TO FIX IT BY DOING THIS:
<form method="POST">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");

you should add name with value for button after that you can get by parameter click value.
`<input type="hidden" name="myprevious" value="previous"/>
<input type="hidden" name="mynext" value="next" />
<%
String val1 = request.getParameter("myprevious");
String val2 = request.getParameter("mynext");
try {
if (val1 == "previous") { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if (val2 == "next") { // Go next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
`
I hope it will help you.
Thanks.

Try to use the subList() method of a List<>().
As explained here.
HOW TO IMPLEMENT IT ##
you can put an hidden input in your form to give you the last index for your list like :
<input type="hiden" value="${last_index_of_your_list + 1}" name="index">
Then in your servlet part you put like this :
int index = Interger.ParseInt(request.getParameter("index"));
if(index <= 0){
datalist = datalist(0, 19>datalist.size()? datalist.size() : 19);
}else{
if(clicked_on_next){
datalist = datalist(index, index+19>datalist.size()? datalist.size() : index+19 );
}else{
datalist = datalist(index - 40, index-20>datalist.size()? datalist.size() : index-20 );
}
}

You are using hidden fields but you need to use submit button for next and previous.
<input type="submit" name="myprevious" value="previous"/>
<input type="submit" name="mynext" value="next" />
Make sure both are define in form. when we submit form after that you will get button value in parameter.same my previous answer. because we can not get parameter value without submit form.
Thanks.

Related

Passing localstorage value to Server (Java, JSP)

im currently creating a canvas Javascript game and im passing localstorage variable to my database which is the Score. Score being 'elapsed'. When i was debugging i saw that the localstorage value is there. But it just doesnt seem to store into the database. Preferably without the use of Ajax?
function drawElapsedTime(){
var elapsed=parseInt((new Date() - startTime)/1000);
g.save();
g.beginPath();
g.fillStyle="#008000";
g.font="14px Verdana"
// draw the running time at half opacity
g.globalAlpha=0.50;
g.fillText(elapsed+" secs",canvas.width-75,25);
localStorage.setItem("score",elapsed);
g.restore();
}
var storedTime = localStorage.getItem("score");
<form action="UserActionServlet" method="post">
<input type="submit" value="scoreObj" class="submit" />
</form>
Command:
String xscore = request.getParameter("score");
int score = 0;
if (xscore != null) {
score = Integer.parseInt(xscore);
}
System.out.println(xscore);
You are not passing the score variable as a parameter in your form post.
<form action="UserActionServlet" method="post" onSubmit="submitForm(this.form)">
<input type = "hidden" name = "score"/>
<input type="submit" value="scoreObj" class="submit" />
</form>
<script>
function submitForm(f){
f.score.value = storedTime ;
f.submit();
}
</script>

Validate the checkbox limit to 5

<html>
<head>
<title>HTML Checkbox</title>
</head>
<body>
enter code here
<h2> Pick your most favorite fruits: </h2>
<form name="fruitcheckbox" action="fruits.php" method="POST">
<input type="checkbox" name="fruit[]" value="orange"> Orange
<input type="checkbox" name="fruit[]" value="apple"> Apple
<input type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit
<input type="checkbox" name="fruit[]" value="banana"> Banana
<input type="checkbox" name="fruit[]" value="watermelon"> Watermelon
<br>
<input type="submit" value="Save" name="btnsave">
</form>
Anyone can give me an idea how to validate this checkobox array.
if(isset($_POST['btnsave']))
{ $fruit = $_POST['fruit'];
$values = array();
foreach($chkbox as $selection )
{ if(in_array($selection, $fruit))
{ $values[ $selection ] = 1; }
else
{ $values[ $selection ] = 0; }
}
this is part of my code. I want to limit the checked checkbox to 5. Thanks. I need it badly :|
Try this. You can limit in javascript itself. So you can limit user in client side no need to go server side. It will limit you for 4 items. You can change the number in the script to increase the value
<script type="text/javascript">
function validateitem(){
var items = document.forms['fruitcheckbox'];
var inc = 0;
var i;
for (i = 0; i < items.length; i++) {
if (items[i].checked) {
inc++;
}
}
if(inc == 0) {
document.getElementById("limitmsg").innerHTML = 'Select atleast 1 item.';
return false;
} else if(inc>4){
document.getElementById("limitmsg").innerHTML = 'You can select only 4 items.';
return false;
}
}
</script>
<h2>Pick your most favorite fruits:</h2>
<form name="fruitcheckbox" action="fruits.php" method="POST"
onsubmit="return validateitem();">
<input type="checkbox" name="fruit[]" value="orange"> Orange <input
type="checkbox" name="fruit[]" value="apple"> Apple <input
type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit <input
type="checkbox" name="fruit[]" value="banana"> Banana <input
type="checkbox" name="fruit[]" value="watermelon"> Watermelon <br> <span
style="color: red" id="limitmsg"></span><input type="submit"
value="Save" name="btnsave">
</form>
Do you need something like this?
if (isset($_POST['btnsave'])) {
$fruits = $_POST['fruit'];
$count = count($fruits);
if ($count > 5) {
// Error; Only 5 checks allowed
} else {
// Save the data
}
}
When you submit fields with brackets like in your example. name="fruit[]" it will be an array when it is received in the backend in php.
You could then just use this:
if(isset($_POST['fruit']) && count($_POST['fruit']) > 5) {
// add your error message
} else {
// Everything is fine as long as you dont have to select atleast one of them
}
If my understanding is not wrong you have more then 5 checkboxes and you want user to restrict to check only 5 checkboxes.
If this is the case then below code might help you.
$("input[name='fruit[]']").change(function(e) {
if($('input[name="fruit[]"]:checked').length==5) {
$("input[name='fruit[]']:not(:checked)").attr("disabled", true);
} else {
$("input[name='fruit[]']:not(:checked)").attr("disabled", false);
}
});
Above code will allow you to check only 5 check boxes, whenever user check the 5th checkbox it will disable the remaining unchecked checkboxes. whenever user uncheck any of the 5 checkboxes then it will enable all the checkboxes.

Creating Multiple textboxes dynamically

I am making a web application in which I pass a Int value from a servlet to next jsp page like this :
request.setAttribute("n",n);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/sharingfilesselection.jsp");
dispatcher.forward(request, response);
Now on the next page i.e sharingfilesselection.jsp I want that n textboxes are created dynamically each with a different id as i need to store the values of these textboxes in my database.
The N is obtained on next jsp page by this :
Object N=request.getAttribute("n");
How this can be done using javascript ?Please help
You can do this using JSTL:
<c:forEach var="i" begin="1" end="${n}">
Input ${i}: <input type="text" name="txtDynamic_${i}" id="txtDynamic_${i}" />
<br />
</c:forEach>
Try this in your
.javascript
<%String n=(String)request.getAttribute("n");%>
var n=<%=n%>;
for(var i=0;i<n;i++{
$(".exac").append("<input type="text" id='textbox"+i+"'></input>");
}
}
.html
<div class="exac">
</div>
Working sample here
html
<div id="container"><input type="button" onclick="createTextBox(5)" value="create textbox">
JS
function createTextBox(n) {
for (var i = 0; i < n; i++) {
var textBox = document.createElement("input");
textBox.setAttribute("id", "text_" + i);
document.getElementById("container").appendChild(textBox);
}}

Object into array JSP

I am new to programming and this problem is bothering me for 3 days straight...
I have a post form on .jsp site for gathering name, surname, mail,... and all this info is saved in object USER. I want to save users in array and display them on the same site. But everytime I use submit button in form new session is created and on array output info is only one user.
What should I do to solve this problem?
ps: on this stage i can't use sql because it's school projects
<% Uporabnik uporabnik = new Uporabnik(); //user
uporabnik.setIme(request.getParameter("ime"));
uporabnik.setPriimek(request.getParameter("priimek"));
uporabnik.setEmail(request.getParameter("email"));
uporabnik.setKraj(request.getParameter("kraj"));
uporabnik.setPostnaStevilka(request.getParameter("postnaStevilka"));
ArrayList<Uporabnik> seznamUporabnikov = new ArrayList<Uporabnik>(); //array with i want to display
seznamUporabnikov.add(uporabnik);
session.setAttribute("seznamUporabnikov", seznamUporabnikov); %>
<form method="post" action="Registracija.jsp">
Ime: <input type="text" name="ime"/> <br/>
Priimek: <input type="text" name="priimek"/> <br/>
Email: <input type="text" name="email"/> <br/>
Kraj: <input type="text" name="kraj"/> <br/>
Postna stevilka: <input type="text" name="postnaStevilka"/> <br/>
<input type="submit" name="potrdi" value="Vnesi">
<input type="reset" name="tabelaReset" value="Izbrisi iz tabele">
<input type="submit" name="resetiraj" value="Izbrisi podatke">
</form>
<br/> Seja: <%=session.getAttribute("Oseba")%> <hr/>
<% if (request.getParameter("potrdi")!=null) {
session.setAttribute("Oseba", uporabnik);
} %>
<% if (request.getParameter("resetiraj")!=null) {
session.setAttribute("Oseba", null);
} %>
change these lines:
...
ArrayList seznamUporabnikov = new ArrayList(); //array with i want to display
seznamUporabnikov.add(uporabnik);
session.setAttribute("seznamUporabnikov", seznamUporabnikov);
...
to
...
ArrayList seznamUporabnikov=session.getAttribute("seznamUporabnikov");
if(seznamUporabnikov == null) { //check if already in session before creating.
ArrayList seznamUporabnikov = new ArrayList(); //array with i want to display
}
seznamUporabnikov.add(uporabnik);
session.setAttribute("seznamUporabnikov", seznamUporabnikov);
...
create a class and create a static user list under that class and add all users in that list
this list will be available throughout your application lifecycle.
Okay after 4 days this stuff works now!!! I am so happy :) anyway.. thank you guys for getting me on the right track...
ArrayList<Uporabnik> seznamUporabnikov=null;
//check if already in session before creating.
if(session.getAttribute("seznamUporabnikov") == null) {
seznamUporabnikov = new ArrayList<Uporabnik>();
//array which I want to display
session.setAttribute("seznamUporabnikov", seznamUporabnikov);
} else {
seznamUporabnikov =
(ArrayList<Uporabnik>)session.getAttribute("seznamUporabnikov");
}
if (request.getParameter("potrdi") != null) {
seznamUporabnikov.add(uporabnik);
}
session.setAttribute("seznamUporabnikov", seznamUporabnikov);

Dynamically adding duplicate (unique ID) form Div elements using javascript

I have a form having fields like:
<div class="row">
<div class="field">
<input class="" type="text" name="college" id="college"/>
</div>
<div class="field">
<input class="" type="text" name="city" id="city"/>
</div>
<div class="field">
<input class="" type="text" name="zip" id="zip"/>
</div>
</div>
<input type="button" class="buttonWidth" id="btnAddressAdd" value="Add Worksite Addressess"/>
I have a Add extra address button that add's another copy of div "row" to the page. I need to send all data from the page as a request to the Controller. How do I write a script that add's extra div copy onclick of the button and also appends a unique id to each of the new fields?
See working example in Dojo: http://jsfiddle.net/phusick/PeQCN/
And the same code in plain vanilla JavaScript: http://jsfiddle.net/phusick/Rceua/
The Dojo version employs dojo/_base/lang::clone as #Peter Rader mentioned:
// var lang = require("dojo/_base/lang");
// var array = require("dojo/_base/array");
// var query = require("dojo/query");
// var domAttr = require("dojo/dom-attr");
var counter = 0;
function duplicate(/*Node*/sourceNode, /*Array*/attributesToBump) {
counter++;
var out = lang.clone(sourceNode);
if (domAttr.has(out, "id")) { out.id = bump(out.id); }
query("*", out).forEach(function(node) {
array.forEach(attributesToBump, function(attribute) {
if (domAttr.has(node, attribute)) {
domAttr.set(node, attribute, bump(domAttr.get(node, attribute)));
}
})
});
function bump(/*String*/str) {
return str + "_" + counter;
}
return out;
}
How to use the aforementioned duplicate function:
// var dom = require("dojo/dom");
// var domConstruct = require("dojo/dom-construct");
var sourceNode = dom.byId("fieldset");
var node = duplicate(sourceNode, ["id", "name", "placeholder"]);
domConstruct.place(node, sourceNode, "after");
I have written code to achieve this.
Logic:
1) get the innerHTML of desired parent
2) replace id in the text
3) Insert the new html
See a working code
Pardon me for bad style of coding on JS part. I am not use to coding directly on DOM. I prefer JQuery.
Try
to use this snipplet (see usage)
http://dojotoolkit.org/reference-guide/1.8/dojo/_base/lang.html#dojo-base-lang-clone

Categories