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);
Related
I want to send the identificator of a product to the shoppingcard page and then display the product on the shoppingcart page
I used both request.set attribute and session.setattribute and it doesn't work. If I use session.getattribute or request.getattribute.toString() the page is white nothing is displayed. If I only use request.getAttribute (without toString) the line "ok" is not displayed on the result which means that purchased is null.
ProductStore is a map containing the products we have. Same for shoppingcardStore. ProductBean is the class of the products
products page:
<h2><%=ptp.getName()%></h2>
<div class="product-btns">
<form method="GET" action="<%="WhishList.jsp"%>">
<button class="main-btn icon-btn" name="id" value="<%=ptp.getId()%>"><i class="fa fa-heart"></i></button>
</form>
<button class="main-btn icon-btn"><i class="fa fa-exchange"></i></button>
<form action="shoppingcard.jsp" method="get">
<p> <%= ptp.getId() %> </p>
<%Object product=ptp;
request.setAttribute("purchase", ptp.getId());
%>
<input type="submit" value="add to cart">
<button class="primary-btn add-to-cart"><i class="fa fa-shopping-cart"></i> Add to Cart</button>
</form>
</div>
shoppingcard page
ProductStore products = new ProductStore();
Map<String,ProductBean> prodList = products.getProducts();
ShoppingcardStore db = new ShoppingcardStore();
Map<String,ProductBean> list = db.getShoppingcard();
Object purchased = request.getAttribute("purchase").toString();
if(purchased!=null){
out.println("<h1>Ok</h1>");
//ProductBean x = (ProductBean) purchased;
String x=(String) purchased;
db.Purchase(x);
//TODO confirm product has been added to the shoppingcart.
}%>
<!-- Product Slick -->
<div class="col-md-9 col-sm-6 col-xs-6">
<div class="row">
<div id="product-slick-1" class="product-slick">
<% if(list != null){
Object[] Shoppingcardlist = list.values().toArray();
ProductBean ptp;
for(int i = 0; i<Shoppingcardlist.length; i++){
ptp = (ProductBean)Shoppingcardlist[i];
// TODO display the info of the current wish list.
%>
of course it is just a part of my code, if you need to see something more tell me.
When you are doing setAttribute(), its scope is limited to the request when the main page is loading and hence will not be available on the next page as it will be a new request.
<%Object product=ptp;
request.setAttribute("purchase", ptp.getId());
%>
What you can do is, submit this value in URL param as GET or in a form (get/ post) to fetch it on next JSP using request.getParameter().
Or you can use session scope by session.setAttribute()
Hope it helps
Getting List values in jsp as request.getParameter("") from another jsp
a.jsp
List<String> abc =
(ArrayList<String>)request.getAttribute("studentsrollno");// got
studentsrollno from servlet by request.setAttribute();
<form action="b.jsp" method="post">
<input type="hidden" name="rollno" value="<%=abc%>"/>
<input type="submit">
</form>
b.jsp
<%
List<String> a2 = (ArrayList<String>) request.getParameter("rollno");//
getting error string cannot be converted to ArrayList<String> // How can I
display data rollno here ?
// Iterator<String> itr = a2.iterator();
%>
Many thanks in advance
You can retrieve the values as an array:
String[] vals = request.getParameterValues("rollno");
The values should be emitted as separate form parameters:
<c:foreach items="${abc}" var="item">
<input type="hidden" name="rollno" value="${fn:escapeXml(item)}" />
</c:foreach>
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.
<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.
I am currently developing a web site (Part of a university assignment)
I just put some input validation, although when I redirect due to an error from validation,
For example:
var x = document.getElementById("age").checked;
var y = document.getElementById("agreement").checked;
var z = document.getElementById("sex").value;
if(x != true & y != true & z == null)
{
response.sendRedirect("Register.jsp");
}
I was looking to have some sort of error message appear above the form, to tell the user that they have created an error within the form. (For example, if they did not enter their Gender or did not agree to either of the checkboxes). Also noted, I will change the validation code slightly to be more specific to the error in which the person has made.
Form:
<h3>Register as user</h3>
<form method="POST" action="Register">
<ul>
<li>First Name: <input type="text" name ="firstName"></li>
<li>Last Name: <input type = "text" name = "lastName"></li>
<li>Email Address: <input type = "email" name = "email"></li>
<li>Gender: Male <input type ="radio" name ="sex" value="male">
Female <input type ="radio" name ="sex" value="female"></li>
<li>User Name <input type="text" name="username"></li>
<li>Password <input type="password" name="password"></li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12: <input type = "checkbox" name="age"></li>
<li>Please check this box to agree to the Terms and Conditions <input type ="checkbox" name="agreement"></li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
Thank you for any help or advice you can give me, I really appreciate it as I am rather new to web development and I want to improve and understand techniques that web developers use.
var validate = function(form) {
var errors = [];
if (!form.sex[0].checked && !form.sex[1].checked) {
errors.push('Please select a gender');
}
if (!form.agreement.checked) {
errors.push('Please agree to T&C');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
};
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" onsubmit="return validate(this);">
<ul>
<li>First Name:
<input type="text" name="firstName">
</li>
<li>Last Name:
<input type="text" name="lastName">
</li>
<li>Email Address:
<input type="email" name="email">
</li>
<li>Gender: Male
<input type="radio" name="sex" value="male">Female
<input type="radio" name="sex" value="female">
</li>
<li>User Name
<input type="text" name="username">
</li>
<li>Password
<input type="password" name="password">
</li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12:
<input type="checkbox" name="age">
</li>
<li>Please check this box to agree to the Terms and Conditions
<input type="checkbox" name="agreement">
</li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
I did something like this. I have an html element which is hidden by default.
It is red and take the whole width of the div I put into.
And I've a function to manage errors :
var manageError = function(message) {
$("#element").val(message); // or $("#element").html(message) I guess
$("#element").clearQueue();
$("#element")slideDown(200).delay(10000).slideUp(200);
};
Does it help ?
use jQuery to do this. since you are learning..it will be more helpful for you.
first thing I noticed there, you have used response.sendRedirect(...); in side your javascript which is a wrong approach.
And in your form, don't use un-ordered list like approach, simply use div tags.
I will give a simple example:
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" id="formId">
First Name:
<input type="text" name="firstName">Last Name:
<input type="text" name="lastName">
<div id="errMsg"></div>
<input type="button" value="submit" id="submtBtn">
</form>
and in your javascript file, use it with jQuery:
< !DOCTYPE html >
< html >
< head >
< script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > < /script>
</head >
< script >
$("submtBtn").click(function({
var errorMsg = "";
if ($("firstName").val === '' || $("lastName").val === '') {
errorMsg = "<b>firstName and LastName can not be empty!<b>";
$("errMsg").html(errMsg);
return;
}
$("#formId").submit();
});
< /script>
you can follow above approach.... if you're using Servlets, you could follow jQuery Ajax to submit your values. try and see...hope it will give you an idea..!
First put the validation code in a function and call that function.
function validate(){
..........write your validation code
}
Call this from submit button via onclick or onchange or onblur attribute of input tag.
You can always use HTML 5. With the required action. They can never leave anything blank if this is in. Be aware that it might work with a space in it or something.
Try this:
<li>First Name: <input type="text" name ="firstName" required></li>