---
title: "Struts 入门与提高 ( 转 )"
author: "蒋瑾珂"
date: "2010-05-22T15:08:13Z"
tags: ["JSP", "Struts", "Web", "XML", "log4j"]
categories: ["企业架构"]
slug: "struts"
draft: false
lastmod: "2010-05-22T15:12:53Z"
id: 672672
url: "https://jiangjinke.iteye.com/blog/672672"
---

\[b]一．Java的开发环境及开发过程\[/b]1. java的开发环境: http://www.cvshome.org cvs代码的版本控制 window 2000 eclipse3.0.1: http://eclipse.openwebeng.com/downloads/drops/R-3.0.1-200409161125/index.php tomcatv3Plugin: http://www.sysdeo.com/eclipse/tomcatPlugin.html tomcat: http://www.apache.org/dist/jakarta/ jdk: http://java.sun.com/j2se/1.4.2/download.html struts 1.2.4 : http://www.apache.org/dist/jakarta/struts/ \[b]2.安装过程\[/b] 安装： jdk –&gt; tomcat –&gt;eclipse 把 tomcatv3Plugin解压到 eclipse目录中 cvs ， eclipse 连接 常见问题： \[b]3.开发过程 （一）详细的步骤\[/b] （1．启动eclipse 并建立一个java Project (teststruts) 并在其下建立一个如下目录结构: src(source Folder) 当前项目私用内容(如action 及不可以被其他项目公用的部份) web(Folder) 当前项目的页面显示内容 (是tomcat 的web root path) 必须包括WEB-INF 及其下的 lib ,classes目录 TUtil(source Folder) 通用功能模块：可以被其他的项目录再调用 TStruts(source Folder) 本项目的struts中的 扩展模块, 扩展了struts中的框架内容 OtherSrc(source Folder) 本项目中用到的lib包的中源代码, 可以用于提高开发速度 ，和生成javadoc的作用(struts-1.2.4-src， jdk-src……) Test(source Folder) junit 的测试内容 可建一个doc project这样的可以把所有的 文档在一起了 把 struts-lib包内容拷到 /web/WEB-INF/lib中 （2．为project -&gt; properties a. tomcat context name: /teststruts web application root: /web b.java build path ： (a. Libraries-&gt; add jars -&gt; 把/web/WEB-INF/lib中的jar 全加入列表中 (b. Libraries-&gt; add Extend jars -&gt; 把 tomcat 下的 comom/lib/servlet.jar加入 (c. Default out folder : teststruts/web/WEB-INF/classes (3..为struts 1.2.4 class 增加 src中的内容 方法: 在查看class内容时有一个 add source 按钮 (4. 增加 web.xml ，struts-config.xml web.xml内容： action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml debug 2 2 action \*.do index.jsp struts-bean /WEB-INF/lib/struts-bean.tld struts-html /WEB-INF/lib/struts-html.tld struts-logic /WEB-INF/lib/struts-logic.tld struts-nested /WEB-INF/lib/struts-nested.tld struts-tiles /WEB-INF/lib/struts-tiles.tld struts-validator /WEB-INF/lib/struts-html.tld html-self /WEB-INF/lib/html-self.tld struts-config.xml (5.增加 action , 并在struts-config.xml增加记录 (一 struts-config.xml a. form-beans记录 b.global-forwards c. action-mappings \[b] 直接转向\[/b] 写法一： 写法二： \[b] 登陆动作 \[/b] \[b]注意点： \[/b] input的作用 可通过mapping.getInputForward()获得 forward的作用 可通过mapping.findForward(“Login”) DynaActionForm可以不用实现对应的actionForm调用时直接调用 dyform.get(“username”) 和 dyform.set(“username”,”me”) \[b](二．增加LoginAction.java及login.jsp \[/b] \[b]（二）常见的错误: \[/b] 安装过程，把 （1 在增加web.xml 以前，简单jsp 可以显示，当增加了web.xml后就出现错误 错误类似：说明此web.xml有误 type Status report message /teststruts/index.jsp descrīption The requested resource (/teststruts/index.jsp) is not available. 常见的是如下web.xml内容, 在struts的早期版本中struts-template.tld 但在 struts1.2.4中就没有了，所以当我们还是原来的内容时就会出错， 解决：删除此内容(重启tomcat) struts-template /WEB-INF/lib/struts-template.tld \[b] （2．页面中文乱码问题: \[/b] 解决: 增加&lt;%@ page contentType = "text/html;charset=gb2312" %&gt; (3. \[b]二. 开发主题:\[/b]1.建立自已的标签： 为什么要增加： 如当我们用 &lt; a href=”/login.goto.do”&gt;登陆 而tomcat中 1.0 1.1 htmlsf http://struts.apache.org/tags-html cp com.lxw.tag.ContextPathTag \[b](2.实现com.lxw.tag.ContextPathTag 内容:\[/b] public class ContextPathTag extends TagSupport { protected static MessageResources messages = MessageResources.getMessageResources(Constants.Package + ".LocalStrings"); public int doStartTag() throws JspException { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); String baseTag= request.getContextPath(); JspWriter ōut = pageContext.getOut(); try { out.write(baseTag); } catch (IOException e) { pageContext.setAttribute(Globals.EXCEPTION\_KEY, e, PageContext.REQUEST\_SCOPE); throw new JspException(messages.getMessage("common.io", e.toString())); } return EVAL\_BODY\_INCLUDE; } } \[b](3.调用方法\[/b] a. 在web.xml中增加内容 html-self /WEB-INF/lib/html-self.tld \[b]b.在要调用的页面中增加 \[/b] &lt;%@ taglib uri="html-self" prefix = "htmlsf" %&gt; 调用 [登陆](%3Chtmlsf:cp/%3E/login.do) \[b]2.多国语言的处理\[/b] 请参考：http://dev.csdn.net/develop/article/43/43698.shtm http://dev.csdn.net/develop/article/42/42897.shtm用struts框架尝试国际化程序实现 出错提示: (1. 在struts-config.xml中增加 注：如果放在WEB-INF/classes 下就没有必要声明 (2. 增加ApplicationResources\_zh\_CN.native 文件 内容如下 # ================prompt in jsp page =================== login.jsp.title= 登陆titlecn login.jsp.page.heading=登陆headingcn login.jsp.prompt.username=用户名 login.jsp.prompt.password=密码 login.jsp.prompt.submit=提交验证 login.jsp.prompt.reset=重新填写 #==================error========= id={0} error.detail={0} \[b](3. 生成ApplicationResources\_zh\_CN.properties 文件\[/b] jdk/bin下有 native2ascii.exe 最后设置环境变量 path 内容 …jdk/bin 就可以用native2ascii -encoding GBK ApplicationResources\_zh\_CN.native ApplicationResources\_zh\_CN.properties 生 成 \[b](4. 页面上调用\[/b] &lt;%@ page contentType="text/html; charset=UTF-8" %&gt; &lt;%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %&gt; &lt;%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %&gt; 调用方法: \[b](5. 测试方法\[/b] 打开IE的“工具”-&gt;“Internet选项”菜单，“常规”选项卡，点击其中的“语言”按钮，添加“英语(美国)-\[en-us]”语言，将其他的语言删除，重新启动IE后,你会发现内容已经变成英文； 常见错误:(1). org.apache.jasper.JasperException: Cannot find message resources under key org.apache.struts.action.MESSAGE 请在struts-config.xml中增加 (2).org.apache.jasper.JasperException: Missing message for key "logon.jsp.title" 请确认包写对了 3.多模块独立开发 http://www.yesky.com/SoftChannel/72342371961929728/20021203/1642663\_1.shtml http://dev.csdn.net/article/18/article/28/28207.shtm 我们查看一下，struts1.2.4 自带的多模块的文件组成结构: 模块 upload,validator,exercise 三个目录, 根目录放着 upload,validator,exercise及其中jsp页面. 还有 WEB-INF 其中放 upload,validator,exercise及他们的struts-config.xml 配置代码放在一起 我们现在要做的是独立处理各模块的情况： \[b]web.xml中处理:\[/b] action org.apache.struts.action.ActionServlet debug 2 config /WEB-INF/struts-config.xml,/WEB-INF/struts-config-organization.xml,/WEB-INF/struts-config-doc.xml,/WEB-INF/struts-config-product.xml,/WEB-INF/struts-config-right.xml, /WEB-INF/struts-config-log.xml,/WEB-INF/struts-config-print.xml 2 开发时处理: 可以一个开发模块一个xml文件 \[b]jbuilder 的处理:\[/b]多模块共同开发—分多模块（业务之间耦合小的模块,分为业务层,页面层,） + 通用的模块内容 + 一般的规化: 每个人一个业务层模块,同时负责对应的页面模块的调用. 如果采用DAO,那就必须要 如果是jbuilder 可以多个jpx 同时建一个工程组 \[b]4.页面安全\[/b] \[b]5.文件上传\[/b](1. 中增加 struts-config.xml （2． 增加UploadAction.java DynaActionForm dyForm= (DynaActionForm)form; FormFile upFile=(FormFile)dyForm.get("upfile"); OutputStream bos = new FileOutputStream("d:/houseUpload/"+upFile.getFileName()); bos.write(upFile.getFileData()); bos.close(); \[b](3. 增加jsp \[/b] file: 上传 \[b]6.日志处理\[/b]http://www-900.ibm.com/developerWorks/cn/java/l-log4j/index.shtml http://zooo.51.net/heavyz\_cs/notebook/log4j.html 请参考 采用log4j 进行日志记录: (1. 建立log4j.xml放于WEB-INF/classes下  (2. 引入log4j包于libraries中 (3. 在要增加日志记录的包内容调用 protected Log log = LogFactory.getLog(LoginAction.class); log.debug("ttttttttttttt"); \[b]7.权限控制\[/b] 一．通过Filter 来判断 \[b] 1. 配置 web.xml\[/b] Set Character Encoding syd.insur.was.struts.struts.filters.SetCharacterEncodingFilter encoding GB2312 ignore true checkRightFilter syd.insur.was.right.filters.checkRightFilter Set Character Encoding action checkRightFilter \*.do \[b]8.数据库处理\[/b]public void testdb(){ Connection conn = null; Statement mystat=null; try { DriverManager.registerDriver( (java.sql.Driver) Class.forName( "oracle.jdbc.driver.OracleDriver").newInstance()); //Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@172.16.3.107:1521:padb","painsure","pamanager"); Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@172.16.3.107:1521:padb", "painsure", "pamanager"); int i = 0; ResultSet rs = null; Statement mystat = conn.createStatement(); //mystat.executeUpdate( "update sql"); rs=mystat.executeQuery("select 1 from dual"); if(rs.next()) { int iresult=rs.getInt(1); } } catch (Exception ex) { ex.printStackTrace(); }finally{ try{ if(mystat!=null)mystat.close(); if(conn!=null)conn.close(); }catch(Exception ex){ ex.printStackTrace(); } } \[b]注意：\[/b]1.调用Statement及Connection及PraparedStatement 都要注意及时的关闭,最好放于finally中保证在函数不论是有Exception时还是其他原因都能及时关闭 2.常见的错误： (1. ResultSet 必须要next()后才能getString()等获得对应的内容，同时ResultSet 也要及时关闭. 要点: 尽量多的使用PreparedStatement，同时有尽量多的使用clearBath();addBath(); executeBath() 批处理,但是不要把只查询一次及只更新一次等更新或查询很少的 Satement写成 PreparedStatement 这样 9.分页处理 /\** *

Title: 大容量数据的查询的分页，针对数据库为oracle

\*

Descrīption: \[b] * 好处：\[/b] * (1. 不用每个模块都要一个session 范围的变量,来保存相关查询结果集.所有的分页只要用一个page变量就可以， * 即减少了内存的使用 * (2. 采用sql 只查询出指定的数据结果集，可以增加系统的处理速度 * (3. 把相关的内容封装到此类中可以减少写重复代码 及减少程序复杂度 * * 注：只针对oracle数据库 * 调用方法: 最好每个用户只用一个javaBean（session范围）也就是session.setAttribute("page",page); * 调用前请初始化：initPage

\*

Copyright: Copyright (c) 2004

\*

Company:

\* @author 林宣武 * @version 1.0 \*/ public class PageManageBean { private int iCurPage = -1; private java.util.Vector vCurPage; //当前页//当前要显示的页的内容 private String strSql=null;//当前用的查询sql private int iPageSize=-1;//当前页的最大记录数 private String strError=null;//出错内容 private int iSumPages=-1;//总页数:初始化时获得 private int iSumRecords=-1;//总记录数 private Object ōbjIn = null;// 传入有用的参数 private String rsToVectorType =null;// 把resultSet 转为 Vector的所调用的函数 /* @作用：刚进来时必须要初始化页面 @参数:sqlIn 查询页的sql; iInitPageIn 查询的页码 ; iPageSizeIn 查询的页的记录数 @返回值： 成功true ， 可通过getAryLstCurPage() 获得页面要显示的内容 失败为false ，并且有strError信息，可通过 getErrMsg()获得 \*/ public boolean initPage(String sqlIn, int iInitPageIn, int iPageSizeIn, Object objIn,String rsToVType){ try{ //判断 if(iInitPageIn &lt;1) throw new Exception("所选要显示页码错误, 必须&gt;=1"); if(iPageSizeIn &lt;1) throw new Exception("所选的页最大记录数出错，必须要&gt;=1"); if(rsToVType==null || rsToVType.equals("")) throw new Exception("查询出错，必须要选择输出类型"); //初始化数据变量 this.objIn = objIn; strSql = sqlIn; iPageSize = iPageSizeIn; iCurPage = iInitPageIn; iSumPages = querySumPages(sqlIn,iPageSizeIn); rsToVectorType = rsToVType; //获得对应的页内容 // lxw 20041111 vCurPage = queryPage(sqlIn, iInitPageIn, iPageSizeIn); }catch(Exception ex){ strError = "初始化页面出错,具体错误：" + ex.getMessage(); return false; } return true; } //获得总页数 public int getISumPages() { return this.iSumPages; } //获得当前页 public int getICurPage() { return this.iCurPage; } //作用：获得当前页的内容 注：最后一列为rownum(此次查询的rownum) //调用方法: public java.util.Vector getCurPageVector() { return this.vCurPage; } /* @作用：取下一页面 @参数: @返回值： 成功true ， 可通过getAryLstCurPage() 获得页面要显示的内容 失败为false ，并且有strError信息，可通过 getErrMsg()获得 \*/ public boolean nextPage() { //判断 if(iCurPage&gt;= iSumPages) { strError = "已到最后一页"; return false; } //获得页面内容 try { iCurPage =iCurPage + 1; vCurPage = queryPage(strSql, iCurPage, iPageSize); } catch (Exception ex) { strError = "取下一页出错，具体内容" + ex.getMessage(); return false; } return true; } /* @作用：取上一页面 @参数: @返回值： 成功true ， 可通过getAryLstCurPage() 获得页面要显示的内容 失败为false ，并且有strError信息，可通过 getErrMsg()获得 \*/ public boolean prePage() { //判断 if(iCurPage&lt;=1) { strError = "已到第一页"; return false; } //获得页面内容 try { iCurPage = iCurPage -1; vCurPage = queryPage(strSql, iCurPage, iPageSize); } catch (Exception ex) { strError = "取上一页出错，具体内容" + ex.getMessage(); return false; } return true; } /* @作用：取最后一页面 @参数: @返回值： 成功true ， 可通过getAryLstCurPage() 获得页面要显示的内容 失败为false ，并且有strError信息，可通过 getErrMsg()获得 \*/ public boolean lastPage() { //获得页面内容 try { iCurPage = iSumPages; vCurPage = queryPage(strSql, iCurPage, iPageSize); } catch (Exception ex) { strError = "取最后一页面出错，具体内容" + ex.getMessage(); return false; } return true; } /* @作用：取第一页面 @参数: @返回值： 成功true ， 可通过getAryLstCurPage() 获得页面要显示的内容 失败为false ，并且有strError信息，可通过 getErrMsg()获得 \*/ public boolean firstPage() { //获得页面内容 try { iCurPage = 1; vCurPage = queryPage(strSql, iCurPage, iPageSize); } catch (Exception ex) { strError = "取第一页面，具体内容" + ex.getMessage(); return false; } return true; } /* @作用：获得出错的 原文：http://sns.linuxpk.com/space-13259-do-blog-id-2194.html