How to pass one JSP to another JSP? - java

I am creating small web apps and I am facing the following problem. I have 2 JSPs and when I click the submit button, it repeats the value every time. What I want is that when I click on the submit button it should give only the corresponding value.
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.io.*,java.util.*" %>
<!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">
<title>Class Video</title>
</head>
<body>
<form action="second.jsp" method="post">
<table>
<%
File f=new File("C:/Users/SHAKTI/Desktop/video");
File[] list=f.listFiles();
if(list.length!=0){
String s[]=new String[list.length];
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
%>
<tr><td><%=fi %></td>
<td><input type="text" name="file" value="<%=s[i] %>">
</td>
<td><input type="submit" name="play" value="Play"></td>
</tr>
<%}}
else{
%>
<tr>
<td>There is no any files in the database...</td>
</tr>
<%
}
%>
</table>
</form>
</body>
</html>
second.jsp
<form action="" method="post">
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
String id=request.getParameter("file");
out.println("id = "+id);
%>
<input type="submit" name="submit" value="submit>
</form>

First Jsp : Set Value in First Page
request.setAttribute("name",somevalue);
Second Jsp : Retrieve it in Second page
request.getAttribute("name")

use queryString
URl: http://myaddress.com/xyz?name=jill&sex=f
String someName = request.getParameter("name") ;
String sex = request.getParameter("sex") ;

One way is to use session as described by javaBeginner.
you can also create a from on the fly and submit it.
write a function similar to this one and use it in your success:
function submitValues(url, params) {
var form = [ '<form method="POST" action="', url, '">' ];
for(var key in params)
form.push('<input type="hidden" name="', key, '" value="', params[key], '"/>');
form.push('</form>');
jQuery(form.join('')).appendTo('body')[0].submit();
}

There are many options to pass a value from one jsp to another, Here are some
1) Adding that as a hidden variable and specifying the value
<input name="file" type="hidden" value=""/>
2)Adding it to the session and retrieving the session variable
session.setAttribute("file", value);
3)Passing that as a queryParameter
http://......one.jsp?file=""

It is beacause you are iterating the loop here,
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
so it will print the last element from the loop, to get the name u clicked on the button try this .. Change this line as
<input type="text" name="file" value="<%=s[i] %>">
as,
<td><input type="button" class="btn" data-reqno=value="<%=s[i] %>" value="file name">
And handle it using jQuery like this , so that you can pass the value to next JSP,
<script type="text/javascript">
$(document).ready(function () {
$(".btn").click(
function() {
var selectedFileName = $(this).attr("data-reqno");
var urlToApprove = "/yourApp/req/filename?name=" + selectedFileName;
}
);
});
</script>
And also try to avoid Scriptlets in JSP , you can use JSTL or El for the same purpose .
Hope it helps !!

there are many method to pass variable such as
session.setAttribute()
session.getAttribute
action "xxx.jsp?variable=1"

Related

text field name should be unique

I am working on a project where the client's requirement is to add a dynamic text box. I made the dynamic text box but I'm not getting the unique name of the text box.
Here is my code:
<script type="text/javascript">
function addfieldset() {
var namefieldset = document.getElementById("name").cloneNode(true);
document.getElementById("names").appendChild(namefieldset);
}
function deletefieldset(e) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild(namefieldset);
}
</script>
<body>
<%! public static int i = 1;%>
<% if (i > 0) { %>
<div id="names"><div id="name"><% out.print(i);%>Name: <input name="namefield<%= i%>" type="text"/>delete</div></div>
<input id="addnamebtn" type="button" value="Add Name" onclick="addfieldset()"/>
<% i++;
}%>
</body>
You are mixing two different codes. The key is to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is sent to the browser) and Javascript in the browser, after the browser receives the already generated response.
I.e. you have to change the name of the new text field in the addfieldset() function (which means you have to have a counter, how many text fields there already is).
The java code in scriptlet is executed on the server side. Hence, cloning it again through Javascript will not execute the scriptlet again.
An another approach of what you are trying to achieve will be to store the count variable in javascript.
var count = 1;
function addfieldset() {
count++;
var namefieldset = document.getElementById("name").cloneNode(true);
var textField = namefieldset.getElementsByTagName('input')[0];
textField.setAttribute("name", "namefield" + count);
textField.value = "";
document.getElementById("names").appendChild(namefieldset);
}
function deletefieldset(e) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild(namefieldset);
}
<body>
<div id="names">
<div id="name">
<span>Name:</span>
<input name="namefield1" type="text" />
delete
</div>
</div>
<input id="addnamebtn" type="button" value="Add Name" onclick="addfieldset()" />
</body>
try this JavaScript and HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
var i = 0;
function generateRow() {
i++;
var d = document.getElementById("div");
d.name = "food";
d.innerHTML += "<p>name"+i+" :<input type='text' name='name" + i + "' /> <a href='#' onclick='deletefieldset(this)'>delete</a></p>";
}
function deletefieldset(e) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild(namefieldset);
}
function onLoad() {
generateRow();
}
window.onload = onLoad;
</script>
<body>
<div id="div"></div>
<p>
<input type="button" id="addnamebtn" value="Add Name" onclick="generateRow()" />
</p>
</body>
</html>

Hyperlink in JSP to add item to basket

I am trying to add products (in viewProduct.jsp) to a basket (basket.jsp).
I'm pretty new to JSP. I know it's done by using an appropriate hyperlink to basket.jsp in viewProduct.jsp. I've written a long line in <p> tags in viewProduct.jsp where I'd like the hyperlink to be. Thanks
viewProduct.jsp
<%# page import="shop.Product"%>
<jsp:useBean id='db'
scope='session'
class='shop.ShopDB' />
<html>
<head>
<title>My Shop</title>
</head>
<body>
<%
String pid = request.getParameter("pid");
Product product = db.getProduct(pid);
// out.println("pid = " + pid);
if (product == null) {
// do something sensible!!!
out.println( product );
}
else {
%>
<div align="center">
<h2> <%= product.title %> by <%= product.artist %> </h2>
<img src="<%= product.fullimage %>" />
<p> <%= product.description %> </p>
<p> -------------------------- link goes here -------------------</p>
</div>
<%
}
%>
</body>
</html>
basket.jsp
<%# page import="java.util.Collection,
java.util.Iterator"%>
<jsp:useBean id='basket'
scope='session'
class='shop.Basket'
/>
<%
String empty = request.getParameter("emptyBasket");
if (empty!=null) {
basket.clearBasket();
}
String item = request.getParameter("addItem");
basket.addItem(item);
%>
<html>
<body>
<% Collection items = basket.getItems();
for (Iterator i = items.iterator(); i.hasNext(); ) {
out.println( "<p>" + i.next() + "</p>" );
}
%>
<p> Order total = <%= basket.getTotalString() %>
<%
if ( basket.getTotal() > 0) {
%>
<form action="order.jsp" method="post">
<input type="text" name="name" size="20">
<input type="submit" value="Place Order" />
</form>
<form action="basket.jsp" method="get">
<input type="hidden" name="emptyBasket" value="yes">
<input type="submit" value="Empty Basket" />
</form>
<%
}
%>
</body>
</html>
As you can see from your basket.jsp if you have a parameter called addItem, then it will be added to the basket
so how about
<p> <%= product.description %> </p>
<!-- use pid -->
<a href="basket.jsp?additem="<%=pid%>><%= product.description %></a>
Although use of JSTL tags would be nicer.
See http://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm

validating jstl sql datasource using javascript

I am trying to retrieve data from SQL query executed and validate the result with input I am making within form. I keep getting no return, in other words, it just returns empty value. Could you please help me with this matter or if this not the correct solution then how can I retrieve this value to perform validation.
My validation should match the inputed user with database user.
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<!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=US-ASCII">
<title>Insert title here</title>
<script>
function validateForm() {
var x = document.forms["input"]["user"].value;
var y = document.forms["input"]["pwd"].value;
if (x == null || x == "" && y==null || y=="" ) {
alert("Username and Password must be filled out");
return false;
}
}
function validateUser() {
var x = document.forms["input"]["user"].value;
var variableFromServer = "${names.FIRST_NAME}";
document.write('<p>'+variableFromServer+'</p>');
if (x != variableFromServer) {
alert("Username is not right"+variableFromServer);
return false;
}
}
</script>
</head>
<body>
<sql:setDataSource var="db" driver="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:********" user="******" password="******"/>
Connected
<sql:query dataSource="${db}" var="query_select">
Select * from User_Details
</sql:query>
<c:forEach var="names" items="${query_select.rows}" >
inside loop : <p>${names.FIRST_NAME}</p>
</c:forEach>
<form action= "/BilalWebtier/login.jsp" name="input" action="demo_form_action.asp" method="post" onsubmit="return validateForm() & validateUser();">
Username: <input type="text" name="user">
Password: <input type="password" name="pwd">
<input type="submit" value="Login">
<br/>
<br/>
</form>
<button type="button">Password Reset</button>
</body>
</html>
You should change it to the click event
<form action= "/BilalWebtier/login.jsp" name="input" action="demo_form_action.jsp" method="post" >
Username: <input type="text" name="user">
Password: <input type="password" name="pwd">
<input type="submit" value="Login" onclick="return validateForm() && validateUser();">
<br/>
<br/>
</form>

How to get index of nested JSTL c:forEach from JSP to JS

I've a JSP, where I display elements through JSTL c:forEach loop. This is a nested loop as shown below:
<c:forEach items="${auditBudgetData.auditBudgetTierOneList}" var="auditBudgetTierOne" varStatus="tierOneCount">
** Some Code **
<c:forEach items="${auditBudgetTierOne.auditBudgetTierTwoList}" var="auditBudgetTierTwo" varStatus="tierTwoCount">
** Some Code **
<c:forEach items="${auditBudgetTierTwo.auditBudgetItemList}" var="auditBudgetItem" varStatus="budgetItemCount">
<input type="hidden" name="tierOneIndex" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" value="${budgetItemCount.count}">
**Element rows displayed here**
Now, when the user selects any of the element row in the inner most loop, I've to fetch the values in JS. As you can see I'm trying to get the count of each nested loop like this:
<input type="hidden" name="tierOneIndex" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" value="${budgetItemCount.count}">
And trying to fetch the value of input field in JS as below:
var tierOneIndex = $('input[name="tierOneIndex"]').val();
var tierTwoIndex = $('input[name="tierTwoIndex"]').val();
var budgetItemIndex = $('input[name="budgetItemIndex"]').val();
But whatever element I select, I'm always getting:
tierOneIndex = 0
tierTwoIndex = 0
budgetItemIndex = 0
Any ideas how I can fetch the count values.
In your html you can do like this
<table>
<c:forEach items="${auditBudgetData.auditBudgetTierOneList}" var="auditBudgetTierOne" varStatus="tierOneCount">
** Some Code **
<c:forEach items="${auditBudgetTierOne.auditBudgetTierTwoList}" var="auditBudgetTierTwo" varStatus="tierTwoCount">
** Some Code **
<c:forEach items="${auditBudgetTierTwo.auditBudgetItemList}" var="auditBudgetItem" varStatus="budgetItemCount">
<input type="hidden" name="tierOneIndex" id="tierOneIndex_${budgetItemCount.index}" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" id="tierTwoIndex_${budgetItemCount.index}" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" id ="budgetItemIndex_${budgetItemCount.index}" value="${budgetItemCount.count}">
<tr class="rows" id="${budgetItemCount.index}"><td>click Here</td></tr>
</table>
and in javascript you can do like this
$(document).ready(function(){
$("tr.rows").click(function() {
var rowid=this.id;
var tierOneIndex = $('#tierOneIndex_'+rowid).val();
var tierTwoIndex = $('#tierTwoIndex_'+rowid).val();
var budgetItemIndex = $('#budgetItemIndex_'+rowid).val();
console.log("tierOneIndex:"+tierOneIndex);
console.log("tierTwoIndex:"+tierTwoIndex);
console.log("budgetItemIndex:"+budgetItemIndex);
});
});
Note:
${tierOneCount.index} starts counting at 0
${tierOneCount.count} starts counting at 1
i created one sample fiddle also for you
http://jsfiddle.net/9CHEb/33/
Similar Approach
You will find an approach in this StackOverflow Q&A link.
Solution
In detail, I would go for something like this (JSP)
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<script src="/*link to jQuery*/"></script>
<script>
$(document).ready(function() {
$("td").click(function(event) {
var dtoItemIdx = $(this).attr("data");
//alert("Selected idx: " + dtoItemIdx);
console.info("Selected idx: " + dtoItemIdx);
});
});
</script>
<%-- Get the size of collection --%>
<c:set var="size" scope="page" value="${fn:length(dto.items)}" />
<c:out value="There are ${size} elements in the list." />
<table>
<c:forEach items="${dto.items}" var="item" varStatus="row">
<tr><td data="${row.index}">
<%-- Get the current index in the loop --%>
<c:out value="Your content i.e [row idx: ${row.index}]." />
</td></tr>
</c:forEach>
</table>
Extensions
Instead of only one loop you can obviously nest several loops. The different index could be stored in a CSV-like structrue:
...<td data="${row.index};${product.index};${properties.index}">...
Please leave a comment if this does not solve your problem.

Variable in JSP is not increasing

I have a JSP page with a form which calls the same page after the submit button is pressed. In the page I define a variable x, initially with the value of 1 and hence it fetches the data from DB corresponding to 1. Now when submit is pressed the value of x increases to 2 and the data should be fetched from DB corresponding to the new value. My problem is that the value increases but data is not fetched.Please tell me why?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.io.*" %>
<%# page import="java.sql.*" %>
<%# page import="java.util.*" %>
<jsp:useBean id="Student" scope="session" class="StudentBean.StudentLoginBean"></jsp:useBean>
<%int x=1; %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>welcome <jsp:getProperty property="login" name="Student" />
</title>
</head>
<body>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
String URL="jdbc:mysql://localhost:3306/OnTest";
Connection con=null;
con=DriverManager.getConnection(URL,"root","root");
PreparedStatement stat=con.prepareStatement("select * from questions where qnNo="+x);
x+=1;
ResultSet rs=stat.executeQuery();
while(rs.next()) {
out.println(x);
out.println(rs.getString(1));%>
<form action="sucess.jsp">
<br><input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(2));%>
<input type ="radio" name ="answer" value="b">
<%
out.println(rs.getString(3));%>
<input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(4));%>
<input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(5));%>
<input type="submit" value="submit" name="submit">
</form>
<%
//System.out.println(rs.getString("name"));
//System.out.println(" "+rs.getString("password"));
//v.addElement(rs.getString("name"));
//v.addElement(rs.getString("name"));
}
if(!con.isClosed()) {
out.println("success");
}
}
catch(Exception e)
{
out.println(e);
}
%>
<h1><h1><h1>i am inside sucess</h1></h1></h1>
</body>
</html>
change this code - <%int x=1; %> to this <%!int x=1; %>.
Problem is : your x declaration is at local scope, which re-initializes for every call to .jsp (jsp_servlet).
by using <%! ... %> your x can be defined globlally.
Would be a good thing if you separe logic from view.
Anyway after pressing submit it will reload the page, setting the x variable again at 1.
A solution could be to send the x parameter with the post data and increment it then.
<input type="text" name="x" value="${x}" /> <!-- If you're using EL -->
<input type="text" name="x" value="<%=x%>" />
And
<%
int x = request.getParameter("x");
if(x == null){
x = 1;
}
%>
By separate logic from view i mean that you should use Servlets, you will find a lot of documentation online :)
while(rs.next())
{
out.println(x);
<form action="sucess.jsp">
out.println(rs.getString(1));%>
<br><input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(2));%>
<input type ="radio" name ="answer" value="b">
<%
out.println(rs.getString(3));%>
<input type ="radio" name ="answer" value="c">
<%
out.println(rs.getString(4));%>
<input type ="radio" name ="answer" value="d">
<%
out.println(rs.getString(5));%>
<input type ="radio" name ="answer" value="e">
<input type="submit" value="submit" name="submit">
</form>
<%
//System.out.println(rs.getString("name"));
//System.out.println(" "+rs.getString("password"));
//v.addElement(rs.getString("name"));
//v.addElement(rs.getString("name"));
}
Change these values and you will get the solution. Actually, you were not doing the first inside the Form method so it was behaving differently.

Categories

Resources