如何在jsp中迭代以下代码?

时间:2014-02-21 08:54:43

标签: java hibernate jsp mapping

我在Daoimpl中编写了一个方法,并将列表返回给我的jsp。任何人都可以告诉我如何在我的jsp ???

中迭代和打印列表的值

错误:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.bdisys.promorphics.domain.Blog

Dao方法:在这个dao方法中,我正在编写查询并将结果返回给jsp,有人告诉我如何打印这些值吗?

    public Map<String, Date> getTopBlogsQuesByDate()throws Exception {
             List<Blog> blogs = new ArrayList<Blog>(0);
             Map<String, Date> map = new HashMap<String, Date>();
             try{



                    String sql = "select title , date from (select blog_title as title ,created_date as date from  blog  union select ask_question as title , created_on as date from askquestions ) as aa order by date desc";
                    SQLQuery query = getSession().createSQLQuery(sql);
                    query.setResultTransformer(AliasToBeanResultTransformer); 


                    List l =query.list();
                    System.out.println("Total Number Of Records : "+l.size());
                    Iterator it = l.iterator();

                    while(it.hasNext())
                    {
                        Object o = (Object) it.next();
                        Blog b = (Blog)o;
                        b.setBlogTitle(b.getBlogTitle());
                        b.setCreatedDate(b.getCreatedDate());
                        map.put(b.getBlogTitle(), b.getCreatedDate());
                        System.out.println("Blog title Name : "+b.getBlogTitle());
                        System.out.println("Blog Date : "+b.getCreatedDate());

                        Askquestions a = (Askquestions)o;
                        a.setAskQuestion(a.getAskQuestion());
                        a.setCreatedQuesOn(a.getCreatedQuesOn());
                        System.out.println("Question title Name : "+a.getAskQuestion());
                        System.out.println("Question Date : "+a.getCreatedQuesOn());


                        map.put(a.getAskQuestion(), a.getCreatedQuesOn());

                        System.out.println("Unsorted HashMap: " + map);
                        TreeMap<String, Date> sortedHashMap = new TreeMap(map);     
                        System.out.println("Sorted HashMap: " + sortedHashMap); 

                    }        


             }
  catch(Exception e){
                e.printStackTrace();
            }finally{
                closeSession();
            }
         return map;
    }

2 个答案:

答案 0 :(得分:1)

要在jsp中打印hashMap,您可以使用JSTL forEach

<c:forEach items="${myMap}" var="entry">
    Key : <c:out value="${entry.key}"/>  Value: <c:out value="${entry.value}"/> <br />
</c:forEach>

迭代hashmap,并返回EntrySet。然后,您可以使用其getKey()和getValue()方法

注意:

  1. 将jstl库添加到类路径
  2. 在您的jsp顶部添加<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

答案 1 :(得分:0)

您尚未将课程传递给AliasToBeanResultTransformer

更改

query.setResultTransformer(AliasToBeanResultTransformer);

query.setResultTransformer(new AliasToBeanResultTransformer(Blog.class));

另见