I have an int variable in that gets passed into a jsp file from a java class. I now want to pass this int value from the jsp to a javascript file I have. I am stuck with a coming up with a solution. I have tried the following but still does not work:
javascript:
jQuery(document).ready(function() {
jQuery('div.awsmp-hero-featureSwap').each(function() {
jQuery(this).find('div.hero-featureSwap').each(function() {
var width = 0;
var height = 0;
var count = 1;
var perpage = "${products_per_page}"; // ***** this is the value I want from the jsp*****
var totalcarousel = jQuery('.hero').length;
jQuery(this).find('div').each(function() {
width += jQuery(this).width();
count = count + 1;
if (jQuery(this).height() > height) {
height = jQuery(this).height();
}
});
jQuery(this).width(((width / count) * perpage + 1) + (perpage * 12) + 60 + 'px');
jQuery(this).height(height + 'px');
});
});
JSP:
<c:set var="products_per_page" value="3" />
<c:if test="${not null model.listSize}">
<c:set var="products_per_page" value="${model.listSize}" />
</c:if>
I just want to pass the the "products_per_page" value to the javascript. should be very simple...
you can put your <c:set> block into an HTML element as its value then get the value easily using Javascript or jQuery
example :
<input id="ppp" type="text" value="<c:set var='products_per_page' value='3' />"/>
js:
var products_per_page = document.getElementById("ppp").value;
You can use this, is not very recommendable.... but works..
Hard-coding the value into the html file like this:
<body>
.....
var x = <%= some_value %>;
.....
</body>
I passed the request argument to my onclick handler in js the following way:
<s:submit name="kurierButton" onclick="openKurierWindow('%{#attr.OUTBOUND_KURIER_URL}');" value="%{#attr.OUTBOUND_KURIER}"/>
Try doing it this way->
servlet_file.java
HttpSession session = request.getSession();
session.setAttribute("idList", idList);
.jsp file
<%
HttpSession session1 = request.getSession();
ArrayList<Integer> idList = (ArrayList<Integer>) session1.getAttribute("idList");
%>
.js file
alert("${idList}");
Related
I have create a simple application on jsp..
In my global function jsp file, I have created functions as follows:
<%! public double calcB(double w, double h){
double B = 0;
return B = (w / (h * h));
}
public String calcClassif(double B){
String classifi = null;
if(B >= 30)
classif = "Obese";
else if(B >= 25)
classif = "Overweight";
else if(B >= 18.5)
classif = "Normal";
else
classif = "Underweight";
return classif;
}
%>
Now in my my index.jsp file, I have written the following:
<%#include file = "globalFunctions.jsp" %>
<% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
double we = 0, he = 0;
if(submitted){
weight = Double.parseDouble(request.getParameter("w"));
height = Double.parseDouble(request.getParameter("h"));
}
%>
<h3>BMI Calculator</h3>
<form action = "index.jsp" method = "post">
<input type ="hidden" name = "isSubmitted" value = "true">
Weight: <input type = "text" name = "w"> <br> <br>
Height: <input type = "text" name = "h"> <br> <br>
<input type = "submit" value = "Compute"> <br> <br>
BMI: <%= calcBMI(we, he) %> <br> <br>
Classification: <%= classification %>
</form>
When I execute the application, the classification is not working.. How do I call the method to display me the correct classification ?
Please help.. Thanks
You are never assign a value into classification. You may try this:
<%#include file = "globalFunctions.jsp" %>
<% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
double we = 0, he = 0;
if(submitted){
weight = Double.parseDouble(request.getParameter("w"));
height = Double.parseDouble(request.getParameter("h"));
bmi = calcBMI(we, he);
classification = calcClassif(bmi);
}
%>
<h3>BMI Calculator</h3>
<form action = "index.jsp" method = "post">
<input type ="hidden" name = "isSubmitted" value = "true">
Weight: <input type = "text" name = "w"> <br> <br>
Height: <input type = "text" name = "h"> <br> <br>
<input type = "submit" value = "Compute"> <br> <br>
BMI: <%= bmi %> <br> <br>
Classification: <%= classification %>
</form>
Whenever your JSP is compiled by your servlet container, it is compiled under different names every time. This makes it hard to use a JSP page function in another JSP page. I would recommend you to start using servlets and POJOs for your data processing needs.
Anyway, you don't have any variable named classification (index.jsp:21), therefore it is not displayed and the server logs an error to the console, and not to the client like PHP.
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);
}}
If I run my web project, in the first call I get the right Parameter (request.getParamter(userid)),
but if I do more then one call, the request.getParamter Method always returns null.
I don't know why, and I have tried many things.
Thank you for your help.
in jsp I have this:
function addPersonToDatabase(userID){
var check = 0;
for (var zaehler = 0; zaehler < (document.getElementsByName("notinProject[]").length);
zaehler++) {
if (document.getElementsByName("notinProject[]")[zaehler].checked) {
location.href='<%=request.getContextPath()%>/administration/persons
action=addfrompersons&comingfrom=' + location.href + '&username=' + userID;
check++;
}
}
<form name='setcheckbox' id='setcheckbox' action='PersonControllerServlet' method='post' >
<input type="checkbox" name="notinProject[]" value="" onclick='javascript:addPersonToDatabase("
<%=lobjPerson.userName%)'><br> </td>
in servlet I have this:
String lstrUserName=request.getParameter("username");
try:
onclick='javascript:addPersonToDatabase("<%=lobjPerson.userName%>")'>
Is there any alternative mechanism creating dynamic rows in JSP/Servlets instead of javascript.
JS Code:-
var table = document.getElementById('table1');
var tr = document.createElement('TR');
var td1 = document.createElement('TD');
var td2 = document.createElement('TD');
var td3 = document.createElement('TD');
var td4 = document.createElement('TD');
var inp1 = document.createElement('INPUT');
var inp2 = document.createElement('INPUT');
var inp3 = document.createElement('INPUT');
inp1.setAttribute("Name", "purpose");
inp1.setAttribute("id", purpose"+reclength);
inp2.setAttribute("Name", "Amount");
inp2.setAttribute("id", "Amount"+reclength);
inp3.setAttribute("Name", "dt");
inp3.setAttribute("id", "dt"+reclength);
var deleteIcon = document.createElement('IMG');
deleteIcon.setAttribute('src', '<%=basePath%>images/cancelIcon.gif');
deleteIcon.onclick = function(){
removeWthDrwls(tr);
}
table.appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
td1.appendChild(inp1);
td2.appendChild(inp2);
td3.appendChild(inp3);
td3.appendChild(space2);
td3.appendChild(deleteIcon);
but if user has disabled javascript.So what are best ways to provide alternative solution to him/her in java web applications?
ofcourse you can do the same in jsp refer JSP: Creating Dynamic Tables
here example is given how you can create a table in the jsp same way you can create dynamic rows..
Ten columns can be added for each row by nesting another for loop within the TR tag as follows:
<TABLE>
<% for(int row=1; row <= 5; row++) { %>
<TR>
<% for(int col=1; col<=10; col++) { %>
<TD> (<%=col%>, <%=row%>)
</TD>
<% } %>
</TR>
<% } %>
</TABLE>
Each cell contains its row and column numbers as the tuple (col, row).
I am currently learning jsp/servlet, and trying to make an online bookstore. Using jquery, I was able to send the GET request to the servlet. Upon success, it will reload the browseBookArea div with browseBookArea.jsp. What I don't understand is, this procedure causes infinite loop on my glashfish servet (it happens within the BrowseBookTag.java. I put a System.out.println there to check it).
Is there another way to get the data returned from servlet to Jquery, so I can do it properly? Setting variables in session is not a good way for this I think. I saw the example with jquery.get where we can get the response data.
var currentCat = "all";
$(document).ready(function(){
$(".categoryItem").click(function(event){
$("#browseBookArea").fadeToggle(100);
currentCat = $(this).attr("id");
$.get("GetBookFromCategoryServlet",{selectedCat:currentCat, currentPage:1}); });
$("#browseBookArea").ajaxSuccess(function(){
$(this).show(300);
$(this).load("Components/browseBookArea.jsp");
});
$(".pagination").click(function(event){
$("#browseBookArea").fadeToggle(100);
var page = $(this).attr("id");
alert(currentCat);
$.get("GetBookFromCategoryServlet",{selectedCat:currentCat, currentPage:page});
});
});
Here is my browseBookArea.jsp:
<div id="browseBookArea" class="span-15 last">
<%System.out.println("Back from servlet");
Collection c = (Collection) request.getAttribute("booksFromCat");
if (c == null) {
Collection c1 = (Collection) session.getAttribute("booksFromCat");
if (c1 == null) System.out.println("Books are null");
}
%>
<myJavaTags:BrowseBookTag books="${booksFromCat}" pageSize="${pageSize}" >
<c:if test="${not empty book1 }">
<div class="span-7">
<center>
<img width="115px" height="115px" src='${book1.photoPath}.jpg'/>
<p>${book1.price}<br/><a>${book1.title}</a> <br/>${book1.authorName}<p>
</center>
</div>
</c:if>
<c:if test="${not empty book2 }">
<div class="push-1 span-7 last">
<center>
<img width="115px" height="115px" src='${book2.photoPath}.jpg'/>
<p>${book2.price}<br/><a>${book2.title}</a> <br/>${book2.authorName}<p>
</center>
</div>
</c:if>
<hr class="space">
</myJavaTags:BrowseBookTag>
<hr class="space"/>
</div>
My BrowseBookTag:
public void doTag() throws JspException, IOException{
// if (books ==null){
// admin = AdminBeanFactory.getAdminInstance();
// books = admin.browseBook(cat);
// }
Iterator bookIt = books.iterator();
JspContext jsp = getJspContext();
int i = 0, count = 0;
System.out.println("Total book size in browse tag: "+books.size());
while (bookIt.hasNext() && i < pageSize){
BookDTO b = (BookDTO) bookIt.next();
if (count == 0){
jsp.setAttribute("book1", b);
if ((i+1) == pageSize){
jsp.setAttribute("book2", null);
getJspBody().invoke(null);
}
count++;
}else{
jsp.setAttribute("book2", b);
getJspBody().invoke(null);
count = 0;
}
i++;
}
}
I found the culprit. It is:
$("#browseBookArea").ajaxSuccess(function(){
$(this).show(300);
$(this).load("Components/browseBookArea.jsp");
});
Bad, bad, bad. This demonstrates that I didn't know the meaning of success method call. I've just realized that if I let the #browseBookArea div to load every time, it causes a successful operation, and then it will perform again which ultimately leads to recursion. Finally I got out of this pitfall. The correct thing should be:
$(".categoryItem").click(function(event){
$("#browseBookArea").fadeToggle(100);
var currentId = $(this).attr("id");
$.get("GetBookFromCategoryServlet",{selectedCat:currentId, currentPage:1}, function(data){
$("#browseBookArea").fadeIn(300);
$("#browseBookArea").load("Components/browseBookArea.jsp");
});
});
I just need to define a successful handler after the GET request, and the successful handler must not be the div which invokes the operation.