Struts + Hibernate分页显示 v1.0

Maven搭建Spring+Struts2+Hibernate项目详解 前言        这篇主要采用Maven搭建Spring+Struts2+Hibernate的整合项目,复习一下SSH框架,虽然spring提供自己的MVC框架,但是Spring也提供和其他框架的无缝整合,采用组件形式对个框架进行管理,项目实例是按照真实企业里面的开发搭建,也是web的最后一片了。数据库使用mysql,连接池使用的是Druid数据源(这些都无关紧要,可以随时的替换),下面就将详 阅读详情

Struts + Hibernate分页显示 v1.0

2007年8月5日更新:
这篇写于2年前的拙文,没想到现在还有很多的访问量,感谢大家的支持,很多朋友来信询问HibernateDAO的代码,实际上HibernateDAO是Hibernate应用的一种很流行的模式,在网上很容易就查到,所以我就没有列到文章里,但为了方便大家,我提供一个链接供参考:
http://www.javaeye.com/article/122

这篇文章是hibernate 2.0的版本,对于现在3.0版本改动不多,只需改一下包名:org.hibernate
题外话:关于hibernate, spring, struts等等j2ee开发框架,个人建议如果有时间的话,大家可以研究一下jboss  seam这个下一代JavaEE开发框架,非常的值得

另外我的blog已经全部迁至javaeye, http://jeffreyhsu.javaeye.com  这里不做更新
欢迎大家访问

这是我学习Struts半个月以来,在开发第一个留言簿的时候,参考了网上很多的方案,然后做的一套Web分页机制,使用Struts的MVC方式,利用Hibernate的分段查询的机制来实现,JSP页面干净不含Java代码,逻辑结构清晰,易于扩展。是一个比较好的完整的分页解决方案。

 

目前为第一个版本,以后会逐步完善,在这里希望能起到一个抛砖引玉的作用

大家有什么好的建议可以与我联系:

jeffreyxu@gmail.com

 

阅读门槛:

Java基础知识

Struts基础知识

对Hibernate有一定了解

 

一、         开发环境

Tomcat 5.5.7

Eclipse 3.0.2

SQLServer2000

Hibernate

二、         开发思路

 

分页的步骤:

按照Struts 的MVC处理方式,对于显示数据的请求要先提交至相应的Action(这里是DisplayAction)进行处理,查询数据库,根据数据总数初始化分页信息,然后从数据库取得第一页所要显示的数据(这里并没有全部一次查询所有数据,效率较高),然后转交至相应的显示页面显示。

 

三、         源码部分

1)        Hibernate 部分:

 

HibernateUtil  Hibernate实用类,负责Session的取得和关闭

 

/*

 * @(#)HibernateUtil.java    2005-4-26

 *

 * Copyright (c) 2005, Jeffrey Hsu

 */

import net.sf.hibernate.*;

import net.sf.hibernate.cfg.*;

 

 

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

 

    static {

        try {

            sessionFactory = new Configuration().configure()

                                                .buildSessionFactory();

        } catch (HibernateException ex) {

            throw new RuntimeException("Exception building SessionFactory: " +

                ex.getMessage(), ex);

        }

    }

 

    public static final ThreadLocal session = new ThreadLocal();

 

    public static Session currentSession() throws HibernateException {

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

 

        //Open a new Session, if this Thread has none yet

        if (s == null) {

            s = sessionFactory.openSession();

            session.set(s);

        }

 

        return s;

    }

 

    public static void closeSession() throws HibernateException {

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

        session.set(null);

 

        if (s != null) {

            s.close();

        }

    }

 

 

}

 

Paras     查询参数

ParasList  查询参数集合

HQuery   封装了查询参数的查询信息类

HibernateDAO 根据传递进来的HQuery进行数据库的查询

有关以上三个类的具体细节,请参考我收藏的文章:Hibernate查询解决方案

 

 

 

2)        Pager 包含了分页信息的类,包括页面总数,记录总数,当前第几页

 

/*

 * @(#)Pager.java    2005-5-3

 *

 * Copyright (c) 2005, Jeffrey Hsu

 */

package com.jeffrey.messagelove;

 

 

/**

 *  Pager holds the page info.

 */

public class Pager {

    private int totalRows = 0; // 记录总数

    private int totalPages = 0; // 总页数

    private int pageSize = 10; // 每页显示数据条数,默认为10条记录

    private int currentPage = 1; // 当前页数

    private boolean hasPrevious = false; // 是否有上一页

    private boolean hasNext = false; // 是否有下一页

 

    public Pager() {

    }

 

    /**

     * Initialize Pager

     * @param totalRows total record rows

     * @param pageSize total record is hold by every page

     */

    public void init(int totalRows, int pageSize) {

        this.totalRows = totalRows;

        this.pageSize = pageSize;

        totalPages = ((totalRows + pageSize) - 1) / pageSize;

        refresh(); // 刷新当前页面信息

    }

 

    /**

     * @return Returns the currentPage.

     */

    public int getCurrentPage() {

        return currentPage;

    }

 

    /**

     * @param currentPage current page

     */

    public void setCurrentPage(int currentPage) {

        this.currentPage = currentPage;

        refresh();

    }

 

    /**

     * @return Returns the pageSize.

     */

    public int getPageSize() {

        return pageSize;

    }

 

    /**

     * @param pageSize The pageSize to set.

     */

    public void setPageSize(int pageSize) {

        this.pageSize = pageSize;

        refresh();

    }

 

    /**

     * @return Returns the totalPages.

     */

    public int getTotalPages() {

        return totalPages;

    }

 

    /**

     * @param totalPages The totalPages to set.

     */

    public void setTotalPages(int totalPages) {

        this.totalPages = totalPages;

        refresh();

    }

 

    /**

     * @return Returns the totalRows.

     */

    public int getTotalRows() {

        return totalRows;

    }

 

    /**

     * @param totalRows The totalRows to set.

     */

    public void setTotalRows(int totalRows) {

        this.totalRows = totalRows;

        refresh();

    }

 

       // 跳到第一页

    public void first() {

        currentPage = 1;

        this.setHasPrevious(false);

        refresh();

    }

 

       // 取得上一页(重新设定当前页面即可)

    public void previous() {

        currentPage--;

        refresh();

    }

 

       // 取得下一页

    public void next() {

        System.out.println("next: totalPages: " + totalPages +

            " currentPage : " + currentPage);

 

        if (currentPage < totalPages) {

            currentPage++;

        }

        refresh();

    }

 

       // 跳到最后一页

    public void last() {

        currentPage = totalPages;

        this.setHasNext(false);

        refresh();

    }

 

    public boolean isHasNext() {

        return hasNext;

    }

 

    /**

     * @param hasNext The hasNext to set.

     */

    public void setHasNext(boolean hasNext) {

        this.hasNext = hasNext;

    }

 

    public boolean isHasPrevious() {

        return hasPrevious;

    }

 

    /**

     * @param hasPrevious The hasPrevious to set.

     */

    public void setHasPrevious(boolean hasPrevious) {

        this.hasPrevious = hasPrevious;

    }

 

       // 刷新当前页面信息

    public void refresh() {

        if (totalPages <= 1) {

            hasPrevious = false;

            hasNext = false;

        } else if (currentPage == 1) {

            hasPrevious = false;

            hasNext = true;

        } else if (currentPage == totalPages) {

            hasPrevious = true;

            hasNext = false;

        } else {

            hasPrevious = true;

            hasNext = true;

        }

    }

}


 

3)        Action:

 

DisplayAllAction   显示数据页面控制器

package com.jeffrey.messagelove;

 

import com.jeffrey.messagelove.*;

import com.jeffrey.messagelove.Pager;

import com.jeffrey.messagelove.hibernate.*;

 

/*

 * @(#)DisplayAction.java    2005-5-2

 *

 * Copyright (c) 2005, Jeffrey Xu

 */

import org.apache.struts.action.*;

 

import java.util.*;

 

import javax.servlet.http.*;

 

 

/**

 *   显示页面控制器

 */

public class DisplayAllAction extends Action {

    private HibernateDAO hibernateDAO = new HibernateDAO();

    private Pager pager = new Pager();

 

    public ActionForward execute(ActionMapping mapping, ActionForm form,

        HttpServletRequest request, HttpServletResponse response)

        throws Exception {

        HttpSession session = request.getSession();

 

        List messageList = null;

        HQuery hquery = new HQuery();

        int totalRows = 0;

        int startRow = 0;

 

        try {

            totalRows = hibernateDAO.getRows("select count(*) from Message");

                     // 初始化页面信息

            pager.init(totalRows, Constants.RECORD_PER_PAGE);

        } catch (Exception ex) {

            ex.printStackTrace();

        }

 

        hquery.setQueryString("From Message order by m_sendDate desc");

 

        String viewPage = (String) request.getParameter("viewPage");

        String action = (String) request.getParameter("action");

             

              // 跳转至相应页面

        if (viewPage != null && !viewPage.equals("")) {

            try {

                pager.setCurrentPage(Integer.parseInt(viewPage));

            } catch (NumberFormatException e) {

                e.printStackTrace();

            }

        }

      

        if (action != null) {

                     // 根据传递进来的参数控制页面的前进后退

            if (action.equalsIgnoreCase("previous")) {

                pager.previous();

            } else if (action.equalsIgnoreCase("next")) {

                pager.next();

            } else if (action.equalsIgnoreCase("first")) {

                pager.first();

            } else if (action.equalsIgnoreCase("last")) {

                pager.last();

            }

        }

        try {

            hquery.setPageStartNo(pager.getCurrentPage());

            messageList = hibernateDAO.find(hquery);

        } catch (Exception ex) {

            ex.printStackTrace();

        }

 

        request.setAttribute("list", messageList);

        session.setAttribute("pager", pager);

 

        return mapping.findForward("display");

    }

}

 

 

 

4)        JSP页面 分页导航代码:

  <%-- 分页导航 --%>

  <table border="0" width="780" class="pageInfo">

    <tr>

      <td width="250">

        共 <bean:write name="pager" property="totalRows"/><span class="pageInfo">条记录&nbsp;</span>

        第 <bean:write name="pager" property="currentPage"/>/<bean:write name="pager" property="totalPages"/>页

      </td>

      <td align="right" width="60">

        <html:link page="/Displayall.do?viewPage=&action=first">首页</html:link>

      </td>

      <td align="right" width="60"> 

        <logic:equal name="pager" property="hasPrevious" value="true">

          <html:link page="/Displayall.do?viewPage=&action=previous">上一页</html:link>

        </logic:equal>

        <logic:equal name="pager" property="hasPrevious" value="false">

          <span class="invalidLink">上一页</span>

        </logic:equal>

      </td>

      <td align="center" width="4">

        |

      </td>

      <td align="left" width="60">

        <logic:equal name="pager" property="hasNext" value="true" >

          <html:link page="/Displayall.do?viewPage=&action=next">下一页</html:link>

        </logic:equal>

        <logic:equal name="pager" property="hasNext" value="false">

          <span class="invalidLink">下一页</span>

        </logic:equal>

      </td>

      <td width="60">

        <html:link page="/Displayall.do?viewPage=&action=last">末页</html:link>

      </td>

      <td width="160" align="rigth">

       

        <%-- 跳转相应页面,参见下文页面跳转部分 --%>

        <html:form action="/ViewPage.do">

          跳转到

          <html:text property="targetPage" size="3" maxlength="3"/>

          <html:submit value="GO"/>

        </html:form>

      </td>

      <td>

      </td>

    </tr>

  </table>

  <%-- 分页导航结束 --%>

 

5)      页面跳转部分:

Form:

 

ViewPageForm

/*

 * @(#)ViewPageForm.java    2005-5-9

 *

 * Copyright (c) 2005, Jeffrey Xu

 */

package com.jeffrey.messagelove;

 

import org.apache.struts.action.*;

 

public class ViewPageForm extends ActionForm {

       // 欲跳转的目标页面

    private String targetPage;

 

    /**

     * @return Returns the tagetPage.

     */

    public String getTargetPage() {

        return targetPage;

    }

 

    /**

     * @param tagetPage The tagetPage to set.

     */

    public void setTargetPage(String targetPage) {

        this.targetPage = targetPage;

    }

 

}

 

 

 

Action:

根据Form传递进来的目标页面信息跳转之相应的页面

如果输入的数字合法,则跳转至相应的页面,否则跳转至当前页面(在用户看来页面没有变化)

 

/*

 * @(#)ViewPageAction.java    2005-5-9

 *

 * Copyright (c) 2005, Jeffrey Xu

 */

package com.jeffrey.messagelove;

 

import org.apache.struts.action.*;

 

import javax.servlet.http.*;

 

public class ViewPageAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,

        HttpServletRequest request, HttpServletResponse response)

        throws Exception {

        String targetPage = ((ViewPageForm) form).getTargetPage();

        HttpSession session = request.getSession();

        Pager pager = (Pager) session.getAttribute("pager");

 

        try {

// 判断是否超出页面范围

            if ((Integer.parseInt(targetPage) > pager.getTotalPages()) ||

                    (Integer.parseInt(targetPage) < 1)) {

                targetPage = String.valueOf(pager.getCurrentPage());

            }

 

                     // 如果输入的不是数字,也就是抛出NumberFormatException异常,

        } catch (NumberFormatException e) {

            e.printStackTrace();

            targetPage = String.valueOf(pager.getCurrentPage());

        }

 

        request.removeAttribute(mapping.getAttribute());

 

        return (new ActionForward("/Displayall.do?viewPage=" + targetPage));

    }

}

 

四、         相关配置

    <form-beans>

            <form-bean name="ViewPageForm" type="com.jeffrey.messagelove.ViewPageForm"/>

    </form-beans>

    <global-forwards>

        <!-- Default forward to "Welcome" action -->

        <!-- Demonstrates using index.jsp to forward -->

        <forward

            name="displayall"

            path="/Displayall.do?viewPage=1"/>

    </global-forwards>

 

 

<!-- =========================================== Action Mapping Definitions -->

 

    <action-mappings>

            <!-- Default "Welcome" action -->

            <!-- Forwards to Welcome.jsp -->

       

       

        <action

            path="/Displayall"

            type="com.jeffrey.messagelove.DisplayAllAction"

            scope="request"

            validate="false"

        >

        </action>

       

        <action

            path="/ViewPage"

            type="com.jeffrey.messagelove.ViewPageAction"

            name="ViewPageForm"

            scope="request"

            validate="false"

        >

            <forward name="viewPage" path="/displayall.do?viewPage="/>

        </action>

       

    </action-mappings>

 

五、         结束:

代码已经全部结束,但是总觉得JSP页面的代码太多,期待有更好的解决办法,比如封装成自定义JSP标签Tag,复用度更高。

还有就是页面跳转部分我想做成下拉列表的方式,根据总页数来动态生成下拉列表,这样更方便一些,并且可以避免用户的错误输入,但我不知该如何根据总页数来动态生成下拉列表,希望哪位朋友能够给出一个解决办法。

 

水平有限,难免有不妥的地方,如果您有好的意见或建议请回复或与我联系,在下感激不尽!

jeffreyxu@gmail.com

 

深度学习笔记——Transformer 本文详细介绍面试过程中可能遇到的Transformer知识点。 阅读详情

相关推荐

仓储控制系统(WCS)设计

WCS系统设计方法

cetclyb的博客 2万+

Struts + Hibernate分页显示

Struts + Hibernate分页显示 v1.0这是我学习Struts半个月以来,在开发第一个留言簿的时候,参考了网上很多的方案,然后做的一套Web分页机制,使用Struts的MVC方式,利用Hibernate的分段查询的机制来实现,JSP页面干净不含Java代码,逻辑结构清晰,易于扩展。是一个比较好的完整的分页解决方案。 目前为第一个版本,以后会逐步完善,在这里希望能起到一

漠海林峰 968

NVIDIA DGX Spark实战指南:从开箱到部署200B参数大模型

本文详细介绍了NVIDIA DGX Spark桌面AI超级计算机的开箱体验与实战部署指南。文章深入解析了其Grace Blackwell架构与128GB统一内存的核心优势,并逐步演示了从系统初始化、运行200B参数大模型到进行QLoRA微调的全过程。该设备将高达1 PetaFLOP的AI算力浓缩于桌面,为开发者和研究团队提供了本地化、高性能的AI开发与部署一体化解决方案。

weixin_29274969的博客 2284

分页显示图片

前言   商城项目图片分页显示必不可少,整理一个实例,以便理解和应用。 实现 1、配置SSH环境   ①创建web项目。   ②引入jar包和配置文件。   ③配置基本信息。包括:web.xml、applicationContext.xml、jdbc.properties、log4j.properties、struts.xml。 web-app xmlns:xsi=&quot;h

习惯成自然 3007

Ubuntu docker镜像中下载安装 DPABI(DPARSF)

在Ubuntu服务器的docker镜像中用MATLAB运行DPABI(以及使用DPARSF的功能)。

Pandako's Blog 1732

Apollo Planning决策规划算法代码详细解析 (1):Scenario选择

本文重点讲解Apollo代码中怎样配置Scenario以及选择当前Scenario,Scenario决策是Apollo规划算法的第一步,本文会对代码进行详细解析,也会梳理整个决策流程,码字不易,喜欢的朋友们麻烦点个关注与赞。 在本文你将学到下面这些内容: 规划器planer的种类; 规划器planer的主要函数及逻辑; 场景管理类ScenarioManager的运行机制; 场景注册方法; 场景决策流程,如何选择当前场景 详细的apollo决策规划代码分析 代码具体过程如下: 1、Scenar

自动驾驶Player的博客 1万+

pager-taglib分页方案一

pager-taglib的使用

李达 1723

【机器学习】推理时计算优化——思维链(Chain-of-Thought)与慢思考范式 第一章:基础理论与认知框架 第二章:计算优化技术与前沿方法

过程监督在数学推理中展现出显著优势,因其能够定位错误发生的具体步骤,而非仅在最终答案处提供稀疏反馈。然而,高质量过程标注的获取成本高昂,这催生了基于自动验证器的近似方法。

VectorShift的博客 84

hibernate struts2 分页 经我亲自测试通过

1). 针对网上一些 struts2分页的例子 不完整 ,代码混乱繁琐 ,我特意写了一个分页的小例子,供大家参考,如果程序有什么纰漏, 请指出。开发环境:eclipse3.2 + myeclipse5.5mysql5.0tomcat5.5Dreamweaver20042)建库,并导入脚本这里给大家介绍一个mysql客户端工具 -- SQLyog ,非常好用。

lshln的专栏 838

LPDDR6 技术标准详解(JESD209-6)

是继 LPDDR5/5X 之后的新一代低功耗 DRAM 标准,专为满足移动终端、AI、边缘计算等高带宽、低功耗场景而设计。该标准通过全新架构、动态功耗控制机制和增强型数据完整性机制,实现性能、能效与可靠性的全面升级。LPDDR6 并非仅是速度升级,更是内存架构设计思路的演进,围绕“低功耗 + 高带宽 + 强安全”的三维目标,构建下一代 SoC 平台关键基础。✅ 高带宽:支持 32B/64B 动态突发✅ 低功耗:动态电压、通道切换✅ 高可靠性:ECC + 自测试 + 安全区。

weixin_43199439的博客 2653

GeoXCP:可解释人工智能中空间解释的不确定性量化

GeoXCP: uncertainty quantification of spatial explanations in explainable AI提出基于保形预测(conformal prediction)的不确定性量化框架——地理空间解释保形预测(GeoXCP),将空间依赖纳入建模过程,生成具有校准不确定性估计的空间自适应解释。通过大量模拟实验和真实世界数据集验证,GeoXCP在不同地理空间场景中能提供可靠解释并有效量化不确定性,推动可解释地理空间机器学习的发展,帮助决策者评估模型驱动洞察的可信度。

May the Force be with you 248

Struts2 + Hibernate 分页程序实例

转载自:http://hi.baidu.com/wakin175/blog/item/4d26fef28faf9d14b17ec54e.html 1). 针对网上一些 struts2分页的例子 不完整 ,代码混乱繁琐 ,我特意写了一个分页的小例子,供大家参考,如果程序有什么纰漏, 请指出。开发环境:eclipse3.2 + myeclipse5.5mysql5.0tomcat5.5

cumt168的专栏 1301

“反激电源”是AC/DC隔离电源还是DC/DC隔离电源?

所以在一些场景,我们的输入电压是一个DC,但是我们仍然需要隔离电源的需求,我们就会只采用图9.2的右半部分。在这个场景下“反激电源”是DC/DC。所以此AC/DC的本质是将AC变成高压的DC之后,用带隔离变压器的反激式开关电源产生一个隔离的、稳定的直流电压。一般在讲述各种电源的拓扑的文章和书籍都是在讲述AC/DC的电源拓扑分类的时候,讲述Flyback。反激式开关电源是指使用反激高频变压器隔离输入输出回路的开关电源,反激式隔离变压器开关电源重点表述的是开关电源包含变压器的拓扑结构。

qq_43416206的博客 1317

Myeclipse10下搭建SSH框架(图解)Struts2.1+Spring3.0+Hibernate3.3

本博客仅为个人转载收藏,无其他目的。。 Myeclipse10下搭建SSH框架(图解)Struts2.1+Spring3.0+Hibernate3.3 11Apr 一、建立一个Web Project ①点击File→New→Web Project 新建一个Web工程。   ②在Project Name中输入项目名ssh,在J2EE Specification Leve

qingniaofy的专栏 3274

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

从零开始创建基于struts1.2 + Hibernate3.0 Web工程

从零开始创建基于struts1.2 + Hibernate3.0 Web工程(第一部分) 时间:2005-11-15 作者:phoenixatsh 浏览次数: 5737 本文关键字: 1. 环境说明 2. 例子工程说明 3. 建立工程 3.1 创建新的Web Project 3.2 加载Struts

爱莎可实验室 2157

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

MyEclipse下Spring、Hibernate、Struts结合

时下流行的开发模式:Spring+Hibernate+Struts,在这里我介绍一下Spring+Hibernate的结合,加入Struts表示层那是非常简单的事情了。话不多说,让我们现在开始:数据库准备:数据库名称:AT_SMS表名称:admin字段如下:sid bigint 从1开始自动增加,步长为1,单独做表的主键name varchar(50) password varchar(50)

human_zx 1663

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Struts1.2+Spring2.0+Hibernate3.1整合总结 MyEclipse5.5

Struts1.2+Spring2.0+Hibernate3.1整合总结这个版本框架打架环境必须采用MyEclipse5.5,因只有5.5上版本支持spring2.0,能够添加spring2.0支持。正确添加ssh支持,建好applicationContext.xml下数据源dataSource和sessionFactory后部署到tomcat下启动报错,原因可能是搭建过程中添加jar包冲

jiaoxueli的专栏 997

开发基础框架:mybatis-3.2.8 +hibernate4.0+spring3.0+struts2.3

一:项目下载地址(点击Sourcecode(zip))https://github.com/fzxblgong/frame_2014-12-15/releases版本:v1.2大小:20M二:ssm(mybatis-3.2.8+hibernate4.0+spring3.0+struts2.3)versionv1.3功能新增:+8.框架在支持mybatis-3.2.8基础上...

204

Hibernate+Struts2

Hibernate+Struts2 这里采用Maven项目进行整合 pom.xml文件添加相关依赖 <?xml version="1.0" encoding="UTF-8"?> <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSc

weixin_55850954的博客 1458

Struts+Spring+Hibernate整合入门详解

Java 5.0 Struts 2.0.9Spring 2.0.6Hibernate 3.2.4                                              作者:  Liu Liu 转载请注明出处基本概念和典型实用例子。一、基本概念       Struts:作为基于 MVC 模式的 Web 应用最经典框架,两个项目Struts 和web

小吹的专栏 5万+

创建基于struts1.2 + Hibernate3.0 Web工程

创建基于struts1.2 + Hibernate3.0 Web工程1. 环境说明  安装Eclipse和安装MyEclipse组件的过程在这里不进行介绍。可以参考其它资料完成Eclipse环境的安装与资源的配置。  接下来的篇幅将给出一个在MyEclipse开发环境下的一个Web工程实例。说明在MyEclipse的集成开发环境下,如何利用Struts进行Web工程开发。例子工

811

struts2+spring4+hibernate5整合实例

struts2作为一个很传统的mvc框架,在一些项目中,仍然发挥着重要的作用,另外hibernate和spring的结合也是很常见的,这里介绍struts2+hibernate5+spring4的整合,因为struts2支持最高的spring是4版本,所以这里采用的是spring4。整合的思路比较简单,可以从struts2+spring整合,然后接着整合hibernate+spring。也可以反过...

feinifi的博客 1781

用spring、Hibernate、Struts组建轻量级架构

轻量级J2EE架构版本0.1版权 © 2005 成湘均文中肯定有错误和理解不正确的地方,欢迎给我指正。我的邮箱:chengxiangjun@sina.com 目录前言 1. 整体框架 1.1. UI层 1.2. 业务层 1.3. 数据持久层 1.4. 域对象层2. Struts 2.1. 概述 2.2. 快速入门 2.3. ActionForm 2.4. Action 2.5. 客户端验证3. s

cxjlt的专栏 3498

Struts2.0+Spring2.0+Hibernate3.1整合

1、新建一个工程 myweb2、导入Spring2.0的Jar包:        Spring 2.0 AOP Libraries        Spring 2.0 Persistence Core Libraries        Spring 2.0 Persistence JDBC Libraries        Spring 2.0 J2EE Libraries        Spri

gaotianle的专栏 1646

第29章 J2EE SSH基础学习-Struts2-基于Hibernate的组合查询和分页技术实现

本章主要借助于StudentQueryHelper类对象进行了条件组合查询的基础实现,其基本思路就是将各种条件封装在QueryHelper类里面,然后调用Hibernate的DetachedCriteria将组合条件进行拆解并组合。最后执行查询请求。分页技术基本上借助了Page这个类对象完成了页面的分页功能。就是将查询到的信息放到page里面替代我们原来的直接使用List记录集,从而实现了页面的分...

下雨天@博客 325

Hibernate分页应用层和jsp页面技术

/*  * Generated by MyEclipse Struts  * Template path: templates/java/JavaClass.vtl  */ package com.StrutsLoginDemo.struts.action; import java.util.List; import javax.servlet.http.*; import mana

lifei2199 794
上一篇: 深深爱你,不变不悔……
下一篇: [转载]Hibernate查询解决方案 -------Jplateau
leafxx
博客等级 码龄24年 11粉丝 14原创
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值