Struts 入门与提高 ( 转 )

一.Java的开发环境及开发过程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/  
2.安装过程
安装: jdk –> tomcat –>eclipse
把 tomcatv3Plugin解压到 eclipse目录中
cvs , eclipse 连接
常见问题:
3.开发过程
(一)详细的步骤

(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 -> properties
a. tomcat context name: /teststruts  web application root: /web                          
    b.java build path :
(a.     Libraries-> add jars -> 把/web/WEB-INF/lib中的jar 全加入列表中
(b.    Libraries-> add Extend jars -> 把 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内容:

    <?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

                         "http://java.sun.com/dtd/web-app_2_3.dtd">   

<web-app>

  <servlet>

    <servlet-name>action</servlet-name>

    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

    <init-param>

      <param-name>config</param-name>

      <param-value>/WEB-INF/struts-config.xml</param-value>

    </init-param>

    <init-param>

      <param-name>debug</param-name>

      <param-value>2</param-value>

    </init-param>

    <load-on-startup>2</load-on-startup>

</servlet>

<servlet-mapping>

    <servlet-name>action</servlet-name>

    <url-pattern>*.do</url-pattern>

</servlet-mapping> 

     <welcome-file-list>

        <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

        <taglib>

        <taglib-uri>struts-bean</taglib-uri>

        <taglib-location>/WEB-INF/lib/struts-bean.tld</taglib-location>

    </taglib>

    <taglib>

        <taglib-uri>struts-html</taglib-uri>

        <taglib-location>/WEB-INF/lib/struts-html.tld</taglib-location>

    </taglib>

    <taglib>

        <taglib-uri>struts-logic</taglib-uri>

        <taglib-location>/WEB-INF/lib/struts-logic.tld</taglib-location>

    </taglib>

    <taglib>

        <taglib-uri>struts-nested</taglib-uri>

        <taglib-location>/WEB-INF/lib/struts-nested.tld</taglib-location>

    </taglib>

    <taglib>

        <taglib-uri>struts-tiles</taglib-uri>

        <taglib-location>/WEB-INF/lib/struts-tiles.tld</taglib-location>

    </taglib>

    <taglib>

        <taglib-uri>struts-validator</taglib-uri>

        <taglib-location>/WEB-INF/lib/struts-html.tld</taglib-location>

    </taglib>

        <taglib>

       <taglib-uri>html-self</taglib-uri>

        <taglib-location>/WEB-INF/lib/html-self.tld</taglib-location>

    </taglib>        

</web-app> 

        struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"

                               "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

    <form-beans>    

    </form-beans>

    <global-forwards>

        <forward contextRelative="true" name="Login" path="/login.goto.do" redirect="false"/>

        <forward contextRelative="true" name="Message" path="/message.jsp" redirect="false"/>

    </global-forwards> 

    <action-mappings>

        <action path="/login" type="com.lxw.action.LoginAction" name="userForm" input="/user/login.jsp"/>

    </action-mappings>

     <message-resources parameter="com.lxw.struts.ApplicationResources"/>

</struts-config>

(5.增加 action , 并在struts-config.xml增加记录

(一 struts-config.xml

a. form-beans记录

    <form-bean name="userForm" type="org.apache.struts.action.DynaActionForm">

         <form-property name="username" type="java.lang.String"/>

            <form-property name="password" type="java.lang.String"/>    

    </form-bean>

b.global-forwards

         <forward contextRelative="true" name="Login" path="/login.goto.do" redirect="false"/>

c. action-mappings

直接转向

   写法一:   <action path="/login.goto" type="org.apache.struts.actions.ForwardAction" parameter="/user/login.jsp"/>

  写法二: <action path="/login.goto" forward="/user/login.jsp"/>  

  登陆动作
 

<action path="/login" type="com.lxw.action.LoginAction" name="userForm" input="/user/login.jsp"/>
 

注意点:

input的作用 可通过mapping.getInputForward()获得

forward的作用 可通过mapping.findForward(“Login”)

DynaActionForm可以不用实现对应的actionForm调用时直接调用

 

dyform.get(“username”) 和 dyform.set(“username”,”me”)

 

  

(二.增加LoginAction.java及login.jsp

 

(二)常见的错误:
   安装过程,把
(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)
    <taglib>

        <taglib-uri>struts-template</taglib-uri>        <taglib-location>/WEB-INF/lib/struts-template.tld</taglib-location>

</taglib>

(2.页面中文乱码问题:

解决: 增加<%@ page contentType = "text/html;charset=gb2312" %>
(3.
 

二. 开发主题:1.建立自已的标签:
为什么要增加:
如当我们用 < a href=”/login.goto.do”>登陆</a> 而tomcat中<Conext path = “/teststruts” 要正常显示必须
http://localhost:8080/tetstruts/login.goto.do
而上面的超链接点击后显示为: http://localhost:8080/login.goto.do
现在我们要增加一个标签: 目的--为超链接增加 http://localhost:8080/tetstruts
(1.增加一个tld文件/WEB-INF/lib/html-self.tld内容:
 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<jspversion>1.1</jspversion>

<shortname>htmlsf</shortname>

<uri>http://struts.apache.org/tags-html</uri>

<tag>

<name>cp</name>

<tagclass>com.lxw.tag.ContextPathTag</tagclass>

</tag>

</taglib>
(2.实现com.lxw.tag.ContextPathTag 内容:
   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;

    }

}
(3.调用方法
a. 在web.xml中增加内容

    </taglib>

        <taglib>

        <taglib-uri>html-self</taglib-uri>

        <taglib-location>/WEB-INF/lib/html-self.tld</taglib-location>

</taglib>

b.在要调用的页面中增加

<%@ taglib uri="html-self" prefix = "htmlsf" %>

调用

<a href="<htmlsf:cp/>/login.do"> 登陆 </a> 

2.多国语言的处理
请参考:http://dev.csdn.net/develop/article/43/43698.shtm
http://dev.csdn.net/develop/article/42/42897.shtm用struts框架尝试国际化程序实现
出错提示:
(1. 在struts-config.xml中增加
<message-resources parameter="com.lxw.struts.ApplicationResources"/>
注:如果放在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}
(3.    生成ApplicationResources_zh_CN.properties 文件
   jdk/bin下有 native2ascii.exe 最后设置环境变量 path    内容 …jdk/bin
   就可以用native2ascii -encoding GBK ApplicationResources_zh_CN.native
ApplicationResources_zh_CN.properties
生 成
(4.    页面上调用
    <%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
调用方法:
<bean:message key="login.jsp.title"/>
<html:submit><bean:message key="login.jsp.prompt.submit"/></html:submit>
(5.    测试方法
打开IE的“工具”->“Internet选项”菜单,“常规”选项卡,点击其中的“语言”按钮,添加“英语(美国)-[en-us]”语言,将其他的语言删除,重新启动IE后,你会发现内容已经变成英文; 
常见错误:(1). org.apache.jasper.JasperException: Cannot find message resources under key org.apache.struts.action.MESSAGE 请在struts-config.xml中增加     <message-resources parameter="com.lxw.struts.ApplicationResources"/>    (2).org.apache.jasper.JasperException: Missing message for key "logon.jsp.title" 请确认<message-resources parameter="com.lxw.struts.ApplicationResources"/>包写对了  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 配置代码放在一起
我们现在要做的是独立处理各模块的情况:
 

web.xml中处理:
<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>config</param-name>
      <param-value>/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</param-value>
   </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>
 

开发时处理: 可以一个开发模块一个xml文件
 

jbuilder 的处理:多模块共同开发—分多模块(业务之间耦合小的模块,分为业务层,页面层,)
+ 通用的模块内容 +   一般的规化: 每个人一个业务层模块,同时负责对应的页面模块的调用.
  如果采用DAO,那就必须要
如果是jbuilder 可以多个jpx 同时建一个工程组
4.页面安全
 

5.文件上传(1.    中增加  struts-config.xml

   <form-beanname="uploadForm" type="org.apache.struts.action.DynaActionForm">
         <form-property name="upfile" type="org.apache.struts.upload.FormFile"/>
</form-bean>
 

<action path="/upload.goto" forward="/upload/upload.jsp"/>
    <action path="/upload" type="com.lxw.action.UploadAction" name="uploadForm" input="/upload/upload.jsp"/>   
<controller maxFileSize="2M" inputForward="true" />

(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();
 

(3.    增加jsp

<html:form action="/upload.do" enctype="multipart/form-data" >
file: <html:file   property="upfile" />
<html:submit> 上传</html:submit>
</html:form>
 

6.日志处理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下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender class="org.apache.log4j.ConsoleAppender" name="STDOUT">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%t] %-5p (%c{1}.%M:%L) - %m%n"/>
        </layout>
    </appender>
    <category name="org.apache">
        <priority value="WARN"/>
    </category>   
    <root>
        <priority value="DEBUG"/>
        <appender-ref ref="STDOUT"/>
    </root>
</log4j:configuration>
(2.       引入log4j包于libraries中
 

(3.       在要增加日志记录的包内容调用
    protected Log log = LogFactory.getLog(LoginAction.class);
    log.debug("ttttttttttttt");
7.权限控制
一.通过Filter 来判断
1. 配置 web.xml
<web-app>
   <filter>
    <filter-name>Set Character Encoding</filter-name>
    <filter-class>syd.insur.was.struts.struts.filters.SetCharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>GB2312</param-value>
    </init-param>
    <init-param>
      <param-name>ignore</param-name>
      <param-value>true</param-value>
    </init-param>
</filter>
<filter>
    <filter-name>checkRightFilter</filter-name>
    <filter-class>syd.insur.was.right.filters.checkRightFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Set Character Encoding</filter-name>
    <servlet-name>action</servlet-name>
</filter-mapping>
<filter-mapping>
    <filter-name>checkRightFilter</filter-name>
    <url-pattern>*.do</url-pattern>
</filter-mapping>
 

 

8.数据库处理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();
      }
}
注意:1.调用Statement及Connection及PraparedStatement 都要注意及时的关闭,最好放于finally中保证在函数不论是有Exception时还是其他原因都能及时关闭
2.常见的错误:
(1.                             ResultSet 必须要next()后才能getString()等获得对应的内容,同时ResultSet 也要及时关闭.
 
要点:
尽量多的使用PreparedStatement,同时有尽量多的使用clearBath();addBath();
executeBath() 批处理,但是不要把只查询一次及只更新一次等更新或查询很少的
Satement写成 PreparedStatement 这样
9.分页处理
/**
* <p>Title: 大容量数据的查询的分页,针对数据库为oracle </p>
* <p>Descrīption:
* 好处:
* (1. 不用每个模块都要一个session 范围的变量,来保存相关查询结果集.所有的分页只要用一个page变量就可以,
*    即减少了内存的使用
* (2. 采用sql 只查询出指定的数据结果集,可以增加系统的处理速度
* (3. 把相关的内容封装到此类中可以减少写重复代码 及减少程序复杂度
*
* 注:只针对oracle数据库
* 调用方法: 最好每个用户只用一个javaBean(session范围)也就是session.setAttribute("page",page);
* 调用前请初始化:initPage</p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @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 <1) throw new Exception("所选要显示页码错误, 必须>=1");
     if(iPageSizeIn <1) throw new Exception("所选的页最大记录数出错,必须要>=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>= 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<=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

你可能感兴趣的:(xml,Web,jsp,log4j,struts)