//通过查询ID得到新闻的点击率
public long getHitsByNewsID(long id) {

long hits = 0;
try {
Session session = HibernateUtil.currentSession();
HibernateUtil.beginTransaction();
News news = (News) session.load(News.class, id);
hits = news.getHits()+1;
news.setHits(hits);

session.saveOrUpdate(news);
//session.flush();
HibernateUtil.commitTransaction();
//HibernateUtil.closeSession();

}catch(HibernateException e) {
log.fatal(e);
}
return hits;
}

解决方案 »

  1.   

    //在Struts中调用上面的方法
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) throws IOException {
                       //通过newsId查找新闻内容
    long newsid = Long.parseLong(request.getParameter("newsid"));
    News n = DAOFactory.getNewsDAOInstance().getNewsByID(newsid);
    //得到新闻标题
    String title= n.getTitle();
    //得到新闻内容
    String body = n.getBody();
    //得到点击率
    long hits = DAOFactory.getNewsDAOInstance().getHitsByNewsID(newsid);
    System.out.println(hits);
    //得到作者
    String author = n.getAuthor();
    //得到添加的时间
    Date addDate = n.getAdddate();
    //定制时间显示格式yyyy年MM月dd日
    GetDate g = new GetDate();
    String adddate = g.getDate(addDate);
    if(body!=null)
    {
    //将新闻信息各组成保存在属性中
    request.getSession().setAttribute("body", body);
    request.getSession().setAttribute("author", author);
    request.getSession().setAttribute("title", title);
    request.getSession().setAttribute("newsid", newsid);
    request.getSession().setAttribute("adddate", adddate);
    request.getSession().setAttribute("hits", hits);
    }

    return mapping.findForward("suc");

    }
      

  2.   

    症状是:TOMCAT启动后,第一次点到某条新闻,能正常刷新点击率,但是再点击到另外一条新闻后,就不会更新点击率,说是Session is closed!
    望知道的朋友指点下,谢谢
      

  3.   

    http://www.cjsdn.net/post/view?bid=2&id=125970&age=0
    http://www.80diy.com/home/20050823/15/4226381.html
      

  4.   

    //取得Session我是这样写的,楼上的好像不可行
    public static Session currentSession() {

    Session session=(Session)tLocalsess.get();

    /**打开一个新的Session,如果当前的为空置或没有打开*/
    try {
    if(session == null || !session.isOpen()) {
    session=openSession();
    //把Hibernate的session放入tLocalsess变量中保存
    tLocalsess.set(session);
    }
    } catch(HibernateException e) {

    //抛出HibernateException异常
    e.printStackTrace();
    }
    return session;
    }
      

  5.   

    我把事务提交那个方法中的 tLocaltx.set(null);去掉的话,就不会报这个异常了,但是数据库中不会更新了,比如我刷新下页面,页面上的点击率是在跳,但是数据库中的数据还是原来那个没有增加