如果属性包含值数组,如何在 JSP 中导入 Bean 属性的值?
更新:我已经包含了整个代码以消除歧义。
这是我用于 getter 和 setter 方法的 CompileClass:
package user;
public class CompileClass {
public String date1;
public String date2;
public String p_code;
public CompileClass(){
}
public void setDate1( String name ) {
date1 = name;
}
public void setDate2( String name ) {
date2 = name;
}
public void setP_code( String name ) {
p_code = name;
}
public String getDate1() {
return date1;
}
public String getDate2() {
return date2;
}
public String getP_code() {
return p_code;
}
}
这是我的 BEAN重复记录.jsp:
package user;
import java.io.* ;
import java.sql.*;
import java.text.*;
import javax.servlet.*;//modified for JSP
import javax.servlet.http.*;//modified for JSP
import user.CompileClass;
/*to find duplicate records and their time stamps*/
public class duplicaterecords extends HttpServlet{//modified for JSP
public static void main(String[] args,HttpServletRequest request, HttpServletResponse response)//modified for JSP
{
int l,x=0,y=0,tow,i=0,tower1=0,t=0;
String p_code,date[],date1,date2,getdate,date3,tower,t_split;
String time2;
//tow=new int[1000];
date=new String[100];
CompileClass c=new CompileClass();//modified for JSP
//HttpServletRequest request;//modified for JSP
DecimalFormat df = new DecimalFormat("#.##");
try
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); //input buffer
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement stmt=con.createStatement();
String query1="select distinct(date) FROM `report_data` WHERE date>= ? and date<= ? "; //Query one for date input
PreparedStatement ps=con.prepareStatement(query1);
//System.out.println("Enter the 1st DATE"); //Date 1 is entered
date1 = c.getDate1();//modified for JSP
//System.out.println("Enter the 2nd DATE"); //Date 2 is entered
//date2=b.readLine();
date2 = c.getDate2();//modified for JSP
ps.setString(1,date1);
ps.setString(2,date2);
//System.out.println("enter the param_code"); // param_code is entered
//p_code= b.readLine();
p_code=c.getP_code();//modified for JSP
ResultSet result=ps.executeQuery();
//System.out.print("Tow_id");
while(result.next() )
{
getdate=result.getString("date");
//System.out.print("\t"+getdate);
request.setAttribute("dates", getdate);//modified for JSP
date3='%'+getdate+'%';
date[x]=date3;
x++;
}
l=x;
String query2="SELECT distinct(tow_id) FROM `tower_data` WHERE TIME_STAMP LIKE ? "; //query 2 for finding tower-id
PreparedStatement ps1=con.prepareStatement(query2);
ps1.setString(1,date[0]);
ResultSet result1=ps1.executeQuery();
while(result1.next())
{
//System.out.println("");
tower=result1.getString("tow_id");
tower1= Integer.parseInt(tower);
t=y;
//System.out.print(tower1);
request.setAttribute("towers", tower1);//modified for JSP
int count=0;
x=0;
while(count<l)
{
String query3="SELECT time_stamp FROM tower_data WHERE `TIME_STAMP` LIKE ? AND `PARAM_CODE` = ? AND `TOW_ID`=? GROUP BY time_stamp HAVING count( * ) >1";
//Query 3 for finding time stamps with duplicate data
PreparedStatement ps2=con.prepareStatement(query3);
ps2.setString(2,p_code);
ps2.setString(1,date[x]);
ps2.setInt(3,tower1);
ResultSet result2=ps2.executeQuery();
int row=0;
while(result2.next())
{
t_split=result2.getString("time_stamp");
String[] parts= t_split.split(" "); //splitting time_stamp to extract only time without date
time2=parts[1]; //time stored in time2
//System.out.println("\t"+time2);
request.setAttribute("times", time2);//modified for JSP
row++;
}
if(row==0)
{
//System.out.println("\t"+"no duplicate");
}
// System.out.print("\t"+"\t");
x++;
count++;
}
}
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
这是我的 Result.jsp:
<%@ page import="java.net.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="java.util.ArrayList"%>
<jsp:useBean id="user" scope="session" class="user.duplicaterecords" />
<jsp:setProperty property="*" name="user"/>
<html>
<body>
Dates:<BR>
<%--<%= request.getAttribute("dates") %><br/>--%>
<%--Email: <%= user.getMail() %><BR>--%>
<%-- Age: <%= user.getAge() %><BR> --%>
<c:forEach items="${sessionScope.dates}" var="item">
<c:out value="${item}"/>
</c:forEach>
</body>
</html>
从代码中可以清楚地看出
s.setAttribute("日期", getdate);
getdate 将包含一个字符串值数组。
现在我想在我的 JSP 中这样调用它:
<%= request.getAttribute("dates") %>
但调用该值会返回 null。所以我想知道如何以数组形式访问 getdate 属性并打印所有值。帮助?
UPDATED: I have included the whole code to clear the ambiguity.
This is the CompileClass that I am using for getter and setter methods:
package user;
public class CompileClass {
public String date1;
public String date2;
public String p_code;
public CompileClass(){
}
public void setDate1( String name ) {
date1 = name;
}
public void setDate2( String name ) {
date2 = name;
}
public void setP_code( String name ) {
p_code = name;
}
public String getDate1() {
return date1;
}
public String getDate2() {
return date2;
}
public String getP_code() {
return p_code;
}
}
And this is my BEAN duplicaterecords.jsp:
package user;
import java.io.* ;
import java.sql.*;
import java.text.*;
import javax.servlet.*;//modified for JSP
import javax.servlet.http.*;//modified for JSP
import user.CompileClass;
/*to find duplicate records and their time stamps*/
public class duplicaterecords extends HttpServlet{//modified for JSP
public static void main(String[] args,HttpServletRequest request, HttpServletResponse response)//modified for JSP
{
int l,x=0,y=0,tow,i=0,tower1=0,t=0;
String p_code,date[],date1,date2,getdate,date3,tower,t_split;
String time2;
//tow=new int[1000];
date=new String[100];
CompileClass c=new CompileClass();//modified for JSP
//HttpServletRequest request;//modified for JSP
DecimalFormat df = new DecimalFormat("#.##");
try
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); //input buffer
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement stmt=con.createStatement();
String query1="select distinct(date) FROM `report_data` WHERE date>= ? and date<= ? "; //Query one for date input
PreparedStatement ps=con.prepareStatement(query1);
//System.out.println("Enter the 1st DATE"); //Date 1 is entered
date1 = c.getDate1();//modified for JSP
//System.out.println("Enter the 2nd DATE"); //Date 2 is entered
//date2=b.readLine();
date2 = c.getDate2();//modified for JSP
ps.setString(1,date1);
ps.setString(2,date2);
//System.out.println("enter the param_code"); // param_code is entered
//p_code= b.readLine();
p_code=c.getP_code();//modified for JSP
ResultSet result=ps.executeQuery();
//System.out.print("Tow_id");
while(result.next() )
{
getdate=result.getString("date");
//System.out.print("\t"+getdate);
request.setAttribute("dates", getdate);//modified for JSP
date3='%'+getdate+'%';
date[x]=date3;
x++;
}
l=x;
String query2="SELECT distinct(tow_id) FROM `tower_data` WHERE TIME_STAMP LIKE ? "; //query 2 for finding tower-id
PreparedStatement ps1=con.prepareStatement(query2);
ps1.setString(1,date[0]);
ResultSet result1=ps1.executeQuery();
while(result1.next())
{
//System.out.println("");
tower=result1.getString("tow_id");
tower1= Integer.parseInt(tower);
t=y;
//System.out.print(tower1);
request.setAttribute("towers", tower1);//modified for JSP
int count=0;
x=0;
while(count<l)
{
String query3="SELECT time_stamp FROM tower_data WHERE `TIME_STAMP` LIKE ? AND `PARAM_CODE` = ? AND `TOW_ID`=? GROUP BY time_stamp HAVING count( * ) >1";
//Query 3 for finding time stamps with duplicate data
PreparedStatement ps2=con.prepareStatement(query3);
ps2.setString(2,p_code);
ps2.setString(1,date[x]);
ps2.setInt(3,tower1);
ResultSet result2=ps2.executeQuery();
int row=0;
while(result2.next())
{
t_split=result2.getString("time_stamp");
String[] parts= t_split.split(" "); //splitting time_stamp to extract only time without date
time2=parts[1]; //time stored in time2
//System.out.println("\t"+time2);
request.setAttribute("times", time2);//modified for JSP
row++;
}
if(row==0)
{
//System.out.println("\t"+"no duplicate");
}
// System.out.print("\t"+"\t");
x++;
count++;
}
}
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This is my Result.jsp:
<%@ page import="java.net.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="java.util.ArrayList"%>
<jsp:useBean id="user" scope="session" class="user.duplicaterecords" />
<jsp:setProperty property="*" name="user"/>
<html>
<body>
Dates:<BR>
<%--<%= request.getAttribute("dates") %><br/>--%>
<%--Email: <%= user.getMail() %><BR>--%>
<%-- Age: <%= user.getAge() %><BR> --%>
<c:forEach items="${sessionScope.dates}" var="item">
<c:out value="${item}"/>
</c:forEach>
</body>
</html>
As clear from the code
s.setAttribute("dates", getdate);
getdate will contain an array of string values.
Now I want to call it in my JSP like this:
<%= request.getAttribute("dates") %>
But calling the value like is returning null. So I wanted to know how can I access getdate attribute as an array and print all the values. Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果它不起作用,则意味着 bean 中的
s
与 JSP 中的request
实例不是同一个HttpServletRequest
实例。尽管代码远非自文档化,但字母s
表明它是HttpSession
而不是HttpServletRequest
。相应地修复它。与具体问题无关,这种方法既奇怪又笨拙。不仅
while
循环很奇怪,每次都会用每行的数据覆盖属性值,而且作为实体的健康 javabean 不应该有任何javax.servlet
导入行。只需向 bean 添加一个 getter
并在页面中按如下方式访问它
那就更好了,但是通常您使用
HttpServlet
类根据数据库中的数据创建和填充 bean 。更新:根据您的问题更新。您混合了几个概念,该设置存在严重缺陷。
CompileClass
类是一个 bean(尽管类名远非自文档化)。duplicaterecords
类是一个 servlet,而不是一个 bean(尽管正确的 servlet 方法没有被重写)。当您使用jsp:useBean
构造 bean 时,根本不会调用main()
方法。 JDBC 代码混合在 servlet 类中。ResultSet
上的while
循环也尝试覆盖每个循环上的请求属性。错误太多,不可能发布一句话答案来解决具体问题。我现在也没有心情为你重写这一切。所以我建议把这一切放在一边并根据一些基本的 hello world 示例重新启动。以下是一些入门链接:
在阅读了上面的内容并尝试了基本示例以掌握基本概念之后,然后按如下方式重写整个内容:
具有代表单个报告的必要属性的报告
。list(Date start, Date end)
方法的 DAO 类,该方法使用 JDBC 从数据库返回一个List
,其中包含给定日期之间的报告。
的reports.jsp
页面,用于显示报告。/reports
并在doPost()
方法中执行以下操作:列表<报告>
。request.setAttribute("reports", reports); 将其放入请求范围
request.getRequestDispatcher("reports.jsp").forward(request, response); 转发到结果 JSP;
If it doesn't work, then it means that the
s
in your bean is not the sameHttpServletRequest
instance asrequest
in your JSP. Even though the code is far from self-documenting, the letters
suggests that it's aHttpSession
instead of aHttpServletRequest
. Fix it accordingly.Unrelated to the concrete problem, the approach is odd and clumsy. Not only the
while
loop is odd, you're overwriting the attribute value everytime with data from each row, but also a healthy javabean intented as an entity shouldn't have anyjavax.servlet
import lines.Just add a getter to the bean
and access it as follows in your page
That's better, but normally you use a
HttpServlet
class to create and populate the bean based on data from DB.Update: as per your question update. You're mixing several concepts, the setup is heavily flawed. The
CompileClass
class is a bean (albeit the classname is far from self-documenting). Theduplicaterecords
class is a servlet, not a bean (albeit the right servlet methods are not been overriden). Themain()
method is not invoked at all when you construct a bean usingjsp:useBean
. The JDBC code is mingled in a servlet class. Thewhile
loop onResultSet
is also attempting to overwrite the request attribute on every loop. There is too much wrong that it's impossible to post a single-sentence answer to fix the concrete problem.I am right now also not in a mood to rewrite it all for you. So I'd suggest to put this all aside and restart based on some basic hello world examples. Here are some links to get started:
After you have read the above pages and played around with basic examples in order to grasp the basic concepts, then rewrite the whole fluff as follows:
Report
with the necessary properties which represents a single report.list(Date start, Date end)
method which uses JDBC to return aList<Report>
from the DB with reports between the given dates.search.jsp
page with a<form action="reports" method="post">
with necessary input fields.reports.jsp
page with a<c:forEach items="${reports}" var="report">
which displays the reports./reports
and does the following indoPost()
method:List<Report>
based on start and end dates.request.setAttribute("reports", reports);
request.getRequestDispatcher("reports.jsp").forward(request, response);
如果您从 HttpSession 调用 setAttribute,则会将对象/值添加到会话上下文,因此您应该询问会话范围有关属性的信息,而不是
jstl 中的请求范围:
已编辑
现在您已经更改了代码,并且日期已进入请求范围。您的 Servlet 实现非常不正确 - 有 main() 方法?!,更改它 - 这就是您实际上不将日期放入请求范围的原因
If you call setAttribute from HttpSession you add object/value to session context so you should ask session scope about your attribute not request scope
in jstl:
edited
Now you've changed the code and dates is into request scope. Your Servlet implementation is very incorrect - has main() method?!, change it - this is the reason why you in reality don't put dates into request scope