[英]How to pass one JSP to another JSP?
我正在創建小型Web應用程序,並且遇到以下問題。 我有2個JSP,當我單擊Submit按鈕時,它每次都會重復該值。 我想要的是,當我單擊“提交”按鈕時,它應該僅提供相應的值。
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:在第一頁中設置值
request.setAttribute("name",somevalue);
第二個Jsp:在第二頁中檢索它
request.getAttribute("name")
使用queryString
URl: http://myaddress.com/xyz?name=jill&sex=f
String someName = request.getParameter("name") ;
String sex = request.getParameter("sex") ;
一種方法是使用javaBeginner描述的會話。
您也可以即時創建一個並提交。
編寫一個與此函數類似的函數並在成功中使用它:
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();
}
有很多選項可以將值從一個jsp傳遞到另一個,這是一些
1)將其添加為隱藏變量並指定值
<input name="file" type="hidden" value=""/>
2)將其添加到會話中並獲取會話變量
session.setAttribute("file", value);
3)將其作為查詢參數傳遞
http://......one.jsp?file=""
因為您要在這里循環,
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
因此它將打印循環中的最后一個元素,以獲取您在按鈕上單擊的名稱。
<input type="text" name="file" value="<%=s[i] %>">
如,
<td><input type="button" class="btn" data-reqno=value="<%=s[i] %>" value="file name">
並使用jQuery這樣處理它,以便您可以將值傳遞給下一個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>
而且,還嘗試避免在JSP中使用Scriptlet,可以出於相同目的使用JSTL或El。 希望能幫助到你 !!
有很多方法可以傳遞變量,例如
session.setAttribute()
session.getAttribute
action "xxx.jsp?variable=1"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.