The important thing in life is to have a great aim , and the determination

常用链接

统计

IT技术链接

保险相关

友情链接

基金知识

生活相关

最新评论

struts+spring+hibernate的web应用示例

struts+spring+hibernate的web应用<一> 架构搭建

开发工具:

Eclipse 3.2 + NLpack1-eclipse-SDK-3.2.1-win32( 中文语言包 )

插件:

tomcatPluginV31 :用于 tomcat 项目建立和管理。

Properties Editor struts 中的资源国际化的中文编辑插件,不需要再用命令去转换文本格式了。

xmlbuddy_2.0.72 xml 强大编辑器,而且是免费的。

GEF-SDK-3.2.2+tk.eclipse.plugin.htmleditor_2.0.4+tk.eclipse.plugin.struts_2.0.4 jsp 页面编辑器,这个编辑器远没有 myeclipse 或者 wtp 等大型插件那么强大,但一是免费,二是占资源少的缘故,而且编辑一般的 jsp 页面也够用了,所以我觉得这个插件还凑合够用。

sqlexplorer_plugin_3.0.0.20060901 sql 管理器, 开源插件,比较好用,特别是针对 mysql 这种没有什么强大的 sql 图形编辑管理器的数据库来说。如果用 sqlserver, 这个插件也就可有可无了。

数据库: SQLServer 2000

首先是建库建表,

create database game

create table products(

game_id int primary key NOT NULL ,

game_name_cn varchar (100) NOT NULL ,

game_name_en varchar (100) NOT NULL ,

game_capacity int NOT NULL ,

game_version int NOT NULL ,

game_media int NOT NULL ,

game_copyright int NOT NULL ,

game_price decimal(10, 2) ,

game_content varchar (100)

)

开始搭架子了。

因为使用的是 tomcatPluginV31 ,所以建议 eclipse 的工作空间选择 tomcat webapps 目录。这样项目就不需要再部署了。

新建一个 tomcat 项目,新建 -> 项目 ->java-> tomcat project ,在项目名处,写 ”game” ,点击完成。

接着新建一些包,如下图所示。
ssh1.jpg

然后向 WEB-INF"lib 包中添加一些需要的 jar ,所需的 jar 如下图所示:

ssh2.jpg

需要注意的是,这里
hibernate3.jar hibernate3.1 strust strust1.x

至此,项目基本搭建完毕,下一篇就开始写项目代码了。

struts+spring+hibernate的web应用<二> Dao层代码编写

前一篇文章 (struts+spring+hibernate的web应用<架构搭建) 让我们打好了架子,接下来就来编写代码了。在编码之前,我们需要先自行了解 strust,spring,hibernate 基础知识,后面的文章将不会过多的介绍这些框架的基础知识。整个项目由 Dao,Services,Web 三层组成, Dao 层主要通过 hibernate 来操作数据库, Service 层主要体现了业务,事务的处理, Web 层由 struts 来控制。整个项目的控制交由 spring 管理。

现在的这个小项目除了完成基本的添删改查,还有一个简单的分页功能。这个分页功能不仅前台分页,而且在后台数据库也进行了分页处理。

现在就来编写 Dao 层的代码。

首先写好 pojo 的代码:

com.game.products.model 中新建 products.hbm.xml 类,代码如下:

<? xml version="1.0" encoding="GB2312" ?>
<! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>

< hibernate-mapping >
     
< class  name ="com.game.products.model.Products"  table ="products"   >
         
< id  name ="gameId"  type ="string" >
            
< column  name ="game_id"  length ="5"   />
            
< generator  class ="assigned"   />
        
</ id >
        
< property  name ="gameNameCn"  type ="string" >
            
< column  name ="game_name_cn"  length ="100"   />
        
</ property >
         
< property  name ="gameNameEn"  type ="string" >
            
< column  name ="game_name_en"  length ="100"   />
        
</ property >
        
< property  name ="gameCapacity"  type ="string" >
            
< column  name ="game_capacity"  length ="4"   />
        
</ property >
         
< property  name ="gameVersion"  type ="string" >
            
< column  name ="game_version"  length ="4"   />
        
</ property >
          
< property  name ="gameMedia"  type ="string" >
            
< column  name ="game_media"  length ="4"   />
        
</ property >
        
< property  name ="gameCopyright"  type ="string" >
            
< column  name ="game_copyright"  length ="4"   />
        
</ property >
        
< property  name ="gamePrice"  type ="string" >
            
< column  name ="game_price"  length ="4"   />
        
</ property >  
         
< property  name ="gameContent"  type ="string" >
            
< column  name ="game_content"  length ="100"   />
        
</ property >
     
</ class >
</ hibernate-mapping >


 

注意这里的 ID 不是数据库自动生成的,而是根据需要由程序生成,一般项目中的主键 ID 都是采取这种方式。

然后在这个包中再新建 Products 类,代码如下:

package  com.game.products.model;

public   class  Products  {
    
//     Fields 
     private  String gameId; // 编号
     private  String gameNameCn; // 中文名称
     private  String gameNameEn; // 英文名称
     private  String gameCapacity; // 碟数
     private  String gameVersion; // 版本
     private  String gameMedia; // 介质
     private  String gameCopyright; // 版权
     private  String gamePrice; // 价格
     private  String gameContent; // 攻略
    
    
//     Constructors
     public  Products() {}
    
    
//     Property accessors
     public  String getGameCapacity()  {
        
return  gameCapacity;
    }


    
public   void  setGameCapacity(String gameCapacity)  {
        
this .gameCapacity  =  gameCapacity;
    }


    
public  String getGameId()  {
        
return  gameId;
    }


    
public   void  setGameId(String gameId)  {
        
this .gameId  =  gameId;
    }


    
public  String getGameNameCn()  {
        
return  gameNameCn;
    }


    
public   void  setGameNameCn(String gameNameCn)  {
        
this .gameNameCn  =  gameNameCn;
    }


    
public  String getGameNameEn()  {
        
return  gameNameEn;
    }


    
public   void  setGameNameEn(String gameNameEn)  {
        
this .gameNameEn  =  gameNameEn;
    }


    
public  String getGameVersion()  {
        
return  gameVersion;
    }


    
public   void  setGameVersion(String gameVersion)  {
        
this .gameVersion  =  gameVersion;
    }


    
public  String getGameMedia()  {
        
return  gameMedia;
    }


    
public   void  setGameMedia(String gameMedia)  {
        
this .gameMedia  =  gameMedia;
    }


    
public  String getGameCopyright()  {
        
return  gameCopyright;
    }


    
public   void  setGameCopyright(String gameCopyright)  {
        
this .gameCopyright  =  gameCopyright;
    }


    
public  String getGameContent()  {
        
return  gameContent;
    }


    
public   void  setGameContent(String gameContent)  {
        
this .gameContent  =  gameContent;
    }


    
public  String getGamePrice()  {
        
return  gamePrice;
    }


    
public   void  setGamePrice(String gamePrice)  {
        
this .gamePrice  =  gamePrice;
    }


}


 

需要注意的是,我这里都是采用了 string 类型,因为在项目中传递数据,用 string 类型最为方便,同时也便于代码的编写。只是在前台需要编写验证代码,免得有字符数据插入整数字段而造成数据库异常。

com.game.products.dao.iface 包中新建ProductsDao接口。

代码如下所示:

package  com.game.products.dao.iface;

import  java.util.List;

import  com.game.products.model.Products;

public   interface  ProductsDao  {
    List getProducts();
// 获得所有记录
    List getProducts( int  pageSize,  int  startRow); // 获得一段记录
     int  getRows(); // 获得总行数
     int  getRows(String fieldname,String value); // 获得总行数
    List queryProducts(String fieldname,String value); // 根据条件查询的所有记录
    List queryProducts(String fieldname,String value, int  pageSize,  int  startRow); // 根据条件查询的一段记录
    Products getProduct(String gameId); // 根据ID获得记录
    String getMaxID(); // 获得最大ID值
     void  addProduct(Products pd); // 添加记录
     void  updateProductd(Products pd); // 修改记录
     void  deleteProduct(Products pd); // 删除记录    
}


 

在com.game.products.dao.hibernate包中新建继承HibernateDaoSupport的ProductsMapDao类,并实现了ProductsDao接口。

代码如下:

package  com.game.products.dao.hibernate;

import  java.sql.SQLException;
import  java.util.Iterator;
import  java.util.List;

import  org.hibernate.HibernateException;
import  org.hibernate.Query;
import  org.hibernate.Session;
import  org.springframework.orm.hibernate3.HibernateCallback;
import  org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import  com.game.products.dao.iface.ProductsDao;
import  com.game.products.model.Products;


/**
 * 
@author  cwf
 *
 
*/

public   class  ProductsMapDao  extends  HibernateDaoSupport  implements  ProductsDao  {

    
public  ProductsMapDao() {}

    
/**
     * 函数说明:添加信息
     * 参数说明:对象 
     * 返回值:
     
*/

    
public   void  addProduct(Products pd)  {
        
this .getHibernateTemplate().save(pd);
    }


    
/**
     * 函数说明:删除信息
     * 参数说明: 对象
     * 返回值:
     
*/

    
public   void  deleteProduct(Products pd)  {
        
this .getHibernateTemplate().delete(pd);
    }


    
/**
     * 函数说明:获得所有的信息
     * 参数说明: 
     * 返回值:信息的集合
     
*/

    
public  List getProducts()  {
        String sql
= " FROM Products ORDER BY gameNameCn " ;
        
return   this .getHibernateTemplate().find(sql);
    }

    
    
/**
     * 函数说明:获得总行数
     * 参数说明: 
     * 返回值:总行数
     
*/

    
public   int  getRows()  {
        String sql
= " FROM Products ORDER BY gameNameCn " ;
        List list
= this .getHibernateTemplate().find(sql);
        
return  list.size();
    }

    
    
/**
     * 函数说明:获得一段记录信息
     * 参数说明: 
     * 返回值:信息的集合
     
*/

    
public  List getProducts( int  pageSize,  int  startRow)  throws  HibernateException  {
        
final   int  pageSize1 = pageSize;
        
final   int  startRow1 = startRow;
        
return   this .getHibernateTemplate().executeFind( new  HibernateCallback() {

            
public  List doInHibernate(Session session)  throws  HibernateException, SQLException  {
                Query query
= session.createQuery( " FROM Products ORDER BY gameNameCn " );
                query.setFirstResult(startRow1);
                query.setMaxResults(pageSize1);
                
return  query.list();
            }

        }
);
    }


    
/**
     * 函数说明:获得一条的信息
     * 参数说明: ID
     * 返回值:对象
     
*/

    
public  Products getProduct(String gameId)  {
        
return  (Products) this .getHibernateTemplate().get(Products. class ,gameId);
    }


    
/**
     * 函数说明:获得最大ID
     * 参数说明: 
     * 返回值:最大ID
     
*/

    
public  String getMaxID()  {
        String sql
= " SELECT MAX(gameId)+1 FROM Products   " ;
        String noStr 
=   null ;
        List ll 
=  (List)  this .getHibernateTemplate().find(sql);
        Iterator itr 
=  ll.iterator();
        
if  (itr.hasNext())  {
            Object noint 
=  itr.next();
            
if (noint  ==   null ) {
                noStr 
=   " 1 " ;                
            }
else {
                noStr 
=  noint.toString();
            }

        }

        
        
if (noStr.length() == 1 ) {
            noStr
= " 000 " + noStr;
        }
else   if (noStr.length() == 2 ) {
            noStr
= " 00 " + noStr;
        }
else   if (noStr.length() == 3 ) {
            noStr
= " 0 " + noStr;
        }
else {
            noStr
= noStr;
        }

        
return  noStr;
    }


    
/**
     * 函数说明:修改信息
     * 参数说明: 对象
     * 返回值:
     
*/

    
public   void  updateProductd(Products pd)  {
        
this .getHibernateTemplate().update(pd);
    }


    
/**
     * 函数说明:查询的所有信息
     * 参数说明: 集合
     * 返回值:
     
*/

    
public  List queryProducts(String fieldname,String value)  {
        System.out.println(
" value:  " + value);
        String sql
= " FROM Products where  " + fieldname + "  like '% " + value + " %' " + " ORDER BY gameNameCn " ;
        
return   this .getHibernateTemplate().find(sql);
    }

    
    
/**
     * 函数说明:获得总行数
     * 参数说明: 
     * 返回值:总行数
     
*/

    
public   int  getRows(String fieldname,String value)  {
        String sql
= " FROM Products where  " + fieldname + "  like '% " + value + " %' " + " ORDER BY gameNameCn " ;
        List list
= this .getHibernateTemplate().find(sql);
        
return  list.size();
    }

    
    
/**
     * 函数说明:查询的一段信息
     * 参数说明: 集合
     * 返回值:
     
*/

    
public  List queryProducts(String fieldname,String value, int  pageSize,  int  startRow)  {
        
final   int  pageSize1 = pageSize;
        
final   int  startRow1 = startRow;
        
final  String sql = " FROM Products where  " + fieldname + "  like '% " + value + " %' " + " ORDER BY gameNameCn " ;
        
return   this .getHibernateTemplate().executeFind( new  HibernateCallback() {

            
public  List doInHibernate(Session session)  throws  HibernateException, SQLException  {
                Query query
= session.createQuery(sql);
                query.setFirstResult(startRow1);
                query.setMaxResults(pageSize1);
                
return  query.list();
            }

        }
);
    }


}


在com.game.bean.hibernate包中新建hibernate.cfg.xml,代码如下:

<? xml version="1.0" encoding="GB2312" ?>
<! DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
>
< hibernate-configuration >
    
< session-factory >
        
< property  name ="dialect" > org.hibernate.dialect.SQLServerDialect </ property >
        
< property  name ="show_sql" > true </ property >

        
< mapping  resource ="com/game/products/model/products.hbm.xml" ></ mapping >
    
</ session-factory >
</ hibernate-configuration >


 

至此,DAO层的代码已经编写完成。下一篇,将编写service层代码。


struts+spring+hibernate的web应用<三> Service层代码编写

前面的文章:

struts+spring+hibernate web 应用 < > 架构搭建

struts+spring+hibernate web 应用 < > Dao 层代码编写

现在开始编写 Service 层代码:

com.game.products.services.iface 包中新建 ProductsService 接口,代码如下:

package  com.game.products.services.iface;

import  java.util.List;

import  com.game.products.model.Products;

public   interface  ProductsService  {
    
void  addProduct(Products pd); // 添加记录
     void  deleteProduct(Products pd); // 删除记录    
    List getProducts(); // 获得所有记录
     int  getRows();; // 获得总行数
    List getProducts( int  pageSize,  int  startRow) ; // 获得一段记录
    Products getProduct(String gameId); // 根据ID获得记录
    String getMaxID(); // 获得最大ID值
     void  updateProductd(Products pd); // 修改记录
    List queryProducts(String fieldname,String value); // 根据条件查询的所有记录
     int  getRows(String fieldname,String value); // 获得总行数
    List queryProducts(String fieldname,String value, int  pageSize,  int  startRow); // 根据条件查询的一段记录
}

com.game.products.services 包中新建 ProductsServiceImp 类,这个类实现了 ProductsService 接口,代码如下:

package  com.game.products.services;

import  java.util.List;

import  com.game.products.dao.iface.ProductsDao;
import  com.game.products.model.Products;
import  com.game.products.services.iface.ProductsService;

public   class  ProductsServiceImp  implements  ProductsService {
    
private  ProductsDao productsDao;
    
    
public  ProductsServiceImp() {}
    
    
/**
     * 函数说明:添加信息
     * 参数说明:对象 
     * 返回值:
     
*/

    
public   void  addProduct(Products pd)  {
        productsDao.addProduct(pd);
    }


    
/**
     * 函数说明:删除信息
     * 参数说明: 对象
     * 返回值:
     
*/

    
public   void  deleteProduct(Products pd)  {
        productsDao.deleteProduct(pd);
    }


    
/**
     * 函数说明:获得所有的信息
     * 参数说明: 
     * 返回值:信息的集合
     
*/

    
public  List getProducts()  {
        
return  productsDao.getProducts();
    }

    
    
/**
     * 函数说明:获得总行数
     * 参数说明: 
     * 返回值:总行数
     
*/

    
public   int  getRows()  {
        
return  productsDao.getRows();
    }

    
    
/**
     * 函数说明:获得一段信息
     * 参数说明: 
     * 返回值:信息的集合
     
*/

    
public  List getProducts( int  pageSize,  int  startRow)  {
        
return  productsDao.getProducts(pageSize, startRow);
    }


    
/**
     * 函数说明:获得一条的信息
     * 参数说明: ID
     * 返回值:对象
     
*/

    
public  Products getProduct(String gameId)  {
        
return  productsDao.getProduct(gameId);
    }


    
/**
     * 函数说明:获得最大ID
     * 参数说明: 
     * 返回值:最大ID
     
*/

    
public  String getMaxID()  {
        
return  productsDao.getMaxID();
    }


    
/**
     * 函数说明:修改信息
     * 参数说明: 对象
     * 返回值:
     
*/

    
public   void  updateProductd(Products pd)  {
        productsDao.updateProductd(pd);
    }


    
/**
     * 函数说明:查询信息
     * 参数说明: 集合
     * 返回值:
     
*/

    
public  List queryProducts(String fieldname,String value)  {
        
return  productsDao.queryProducts(fieldname, value);
    }

    
    
/**
     * 函数说明:获得总行数
     * 参数说明: 
     * 返回值:总行数
     
*/

    
public   int  getRows(String fieldname,String value)  {
        
return  productsDao.getRows(fieldname, value);
    }

    
    
/**
     * 函数说明:查询一段信息
     * 参数说明: 集合
     * 返回值:
     
*/

    
public  List queryProducts(String fieldname,String value, int  pageSize,  int  startRow)  {
        
return  productsDao.queryProducts(fieldname, value,pageSize,startRow);
    }


    
public  ProductsDao getProductsDao()  {
        
return  productsDao;
    }


    
public   void  setProductsDao(ProductsDao productsDao)  {
        
this .productsDao  =  productsDao;
    }


}


 

基本的业务层代码就这些了。因为还有分页的业务,所以接下来编写分页的代码。


分页是个公共的类,所以放在
com.game.commons 中。

Pager 类,封装了分页需要的属性,代码如下:

package  com.game.commons;

import  java.math. * ;

public   class  Pager  {
    
private   int  totalRows;  // 总行数
     private   int  pageSize  =   30 // 每页显示的行数
     private   int  currentPage;  // 当前页号
     private   int  totalPages;  // 总页数
     private   int  startRow;  // 当前页在数据库中的起始行
    
    
public  Pager()  {
    }

    
    
public  Pager( int  _totalRows)  {
        totalRows 
=  _totalRows;
        totalPages
= totalRows / pageSize;
        
int  mod = totalRows % pageSize;
        
if (mod > 0 ) {
            totalPages
++ ;
        }

        currentPage 
=   1 ;
        startRow 
=   0 ;
    }

    
    
public   int  getStartRow()  {
        
return  startRow;
    }

    
public   int  getTotalPages()  {
        
return  totalPages;
    }

    
public   int  getCurrentPage()  {
        
return  currentPage;
    }

    
public   int  getPageSize()  {
        
return  pageSize;
    }

    
public   void  setTotalRows( int  totalRows)  {
        
this .totalRows  =  totalRows;
    }

    
public   void  setStartRow( int  startRow)  {
        
this .startRow  =  startRow;
    }

    
public   void  setTotalPages( int  totalPages)  {
        
this .totalPages  =  totalPages;
    }

    
public   void  setCurrentPage( int  currentPage)  {
        
this .currentPage  =  currentPage;
    }

    
public   void  setPageSize( int  pageSize)  {
        
this .pageSize  =  pageSize;
    }

    
public   int  getTotalRows()  {
        
return  totalRows;
    }

    
public   void  first()  {
        currentPage 
=   1 ;
        startRow 
=   0 ;
    }

    
public   void  previous()  {
        
if  (currentPage  ==   1 {
            
return ;
        }

        currentPage
-- ;
        startRow 
=  (currentPage  -   1 *  pageSize;
    }

    
public   void  next()  {
        
if  (currentPage  <  totalPages)  {
            currentPage
++ ;
        }

        startRow 
=  (currentPage  -   1 *  pageSize;
    }

    
public   void  last()  {
        currentPage 
=  totalPages;
        startRow 
=  (currentPage  -   1 *  pageSize;
    }

    
public   void  refresh( int  _currentPage)  {
        currentPage 
=  _currentPage;
        
if  (currentPage  >  totalPages)  {
            last();
        }

    }

}


 

PagerService 类,主要有个 getPager 方法返回 Pager 类。代码如下:

package  com.game.commons;

public   class  PagerService  {
    
public  Pager getPager(String currentPage,String pagerMethod, int  totalRows)  {
        
//     定义pager对象,用于传到页面
        Pager pager  =   new  Pager(totalRows);
        
//     如果当前页号为空,表示为首次查询该页
        
//     如果不为空,则刷新pager对象,输入当前页号等信息
         if  (currentPage  !=   null {
            pager.refresh(Integer.parseInt(currentPage));
        }

        
//     获取当前执行的方法,首页,前一页,后一页,尾页。
         if  (pagerMethod  !=   null {
            
if  (pagerMethod.equals( " first " ))  {
                pager.first();
            }
  else   if  (pagerMethod.equals( " previous " ))  {
                pager.previous();
            }
  else   if  (pagerMethod.equals( " next " ))  {
                pager.next();
            }
  else   if  (pagerMethod.equals( " last " ))  {
                pager.last();
            }

        }

        
return  pager;
    }

}

这个分页方法比较简单,而且功能也齐全,许多页面级的开源 table 中分页很多也是基于这个原理,所以理解了这个分页,对其他各种分页技术的理解也就迎刃而解了。

服务层的代码就这些了,接下来就可以写 spring 的配置文件来用 spring 管理这些 Dao Service 了。

spring-context 包中新建 applicationContext.xml 。配置的写法如下:

<? xml version="1.0" encoding="ISO-8859-1" ?>
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
 
< beans >
    
<!--  dataSource config  -->
    
< bean  id ="dataSource"  class ="org.springframework.jndi.JndiObjectFactoryBean" >
        
< property  name ="jndiName" >
            
< value > java:comp/env/jdbc/game </ value >
        
</ property >
    
</ bean >
<!--  SessionFactory  -->
    
< bean  id ="sessionFactory"
        class
="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >

        
< property  name ="dataSource" >
            
< ref  bean ="dataSource" />
        
</ property >
        
< property  name ="configLocation" >
            
< value > classpath:com"game"bean"hibernate"hibernate.cfg.xml </ value >
        
</ property >         
    
</ bean >
    
    
<!--  TransactionManager   -->
    
< bean  id ="transactionManager"
        class
="org.springframework.orm.hibernate3.HibernateTransactionManager" >
        
< property  name ="sessionFactory" >
            
< ref  local ="sessionFactory" />
        
</ property >
    
</ bean >
<!--  DAO  -->
    
< bean  id ="productsDao"  class ="com.game.products.dao.hibernate.ProductsMapDao" >
        
< property  name ="sessionFactory" >
            
< ref  bean ="sessionFactory" />
        
</ property >
    
</ bean >
    
    
<!--  Services  -->
     
< bean  id ="productsService"  class ="com.game.products.services.ProductsServiceImp" >
        
< property  name ="productsDao" >
            
< ref  bean ="productsDao" />
        
</ property >
    
</ bean >  
< bean  id ="pagerService"  class ="com.game.commons.PagerService" >
    
</ bean >
</beans>


 

配置文件不难,主要是些 IOC 控制。数据库链接我采用的是数据源方式,需要在 tomcat 的conf文件夹下的 server.xml 中添加数据源,添加的数据如下:

< Context  path ="/game"  docBase ="D:"tomcat-5.5.20"webapps"game"  debug ="0"  reloadable ="true" >
        
< Resource
            
name ="jdbc/game"
            type
="javax.sql.DataSource"
            password
=""
            driverClassName
="net.sourceforge.jtds.jdbc.Driver"
            maxIdle
="2"
            maxWait
="5000"
            username
="sa"
            url
="jdbc:jtds:sqlserver://127.0.0.1:16899/game"
            maxActive
="4" />

        
</ Context >


 

这个数据源是针对 tomcat 5.5 以上版本的,以下版本的写法有所不同,不同之处可以用 google 搜索得知。这个数据源很简单,并没有过多的配置来优化系统,只是为了让项目更容易让人理解。需要注意都是,我的数据链接的JDBC包是jtds包,而不是普通的那个三个jar包。

下一篇,将写 Web 层的代码了。


struts+spring+hibernate的web应用<四> Web层代码编写(1)

前面的文章:

struts+spring+hibernate web 应用 < > 架构搭建

struts+spring+hibernate web 应用 < > Dao 层代码编写

struts+spring+hibernate web 应用 < > Service 层代码编写

Web 层代码量比较大,涉及的地方也比较多,考虑到文章过于庞大,所以分两篇写。
我们还是先从主要的
action 开始吧。

com.game.products.web.actions 包中新建 ProductsAction ,这是一个 DispatchAction ,代码如下:

package  com.game.products.web.actions;

import  java.util.List;

import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;

import  org.acegisecurity.AccessDeniedException;
import  org.apache.struts.action.ActionForm;
import  org.apache.struts.action.ActionForward;
import  org.apache.struts.action.ActionMapping;
import  org.apache.struts.actions.DispatchAction;

import  com.game.commons.Pager;
import  com.game.commons.PagerService;
import  com.game.products.model.Products;
import  com.game.products.services.iface.ProductsService;
import  com.game.products.web.forms.ProductsForm;


public   class  ProductsAction  extends  DispatchAction  {
    
    
private  ProductsService productsService;
    
private  PagerService pagerService;
    
    
/**  
     * 显示所有信息
     
*/

    
public  ActionForward doGetProducts(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res)
{
        String flag
= req.getParameter( " flag " );
        
        
int  totalRows = productsService.getRows();
        String currentPage
= req.getParameter( " currentPage " );
        String pagerMethod
= req.getParameter( " pagerMethod " );
        
        Pager pager
= pagerService.getPager(currentPage, pagerMethod, totalRows);
        
        List productsList
= productsService.getProducts(pager.getPageSize(), pager.getStartRow());
        
        req.setAttribute(
" productsList " , productsList);
        req.setAttribute(
" PAGER " , pager);
        req.setAttribute(
" flag " , flag);
        req.setAttribute(
" totalRows " , String.valueOf(totalRows));
        
        
return  mapping.findForward( " all " );
    }

    
    
/**  
     * 显示一条信息
     
*/

    
public  ActionForward doGetProduct(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res)
{
        String flag
= req.getParameter( " flag " );
        String gameId
= req.getParameter( " gameId " );
        String fieldname
= "" ;
        String value
= "" ;
        
if (flag.equals( " 2 " )) {
            fieldname
= (String)req.getParameter( " fieldname " );
            value
= (String)req.getParameter( " value " );
            req.setAttribute(
" fieldname " , fieldname);
            req.setAttribute(
" value " , value);
        }

        
        Products pd
= productsService.getProduct(gameId);
        req.setAttribute(
" pd " , pd);
        req.setAttribute(
" flag " , flag);
        
return  mapping.findForward( " one " );
    }

    
    
/**  
     * 添加信息页面
     
*/

    
public  ActionForward doAddProductPage(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res)
{
        String flag
= req.getParameter( " flag " );
        req.setAttribute(
" flag " , flag);
        String fieldname
= "" ;
        String value
= "" ;
        
if (flag.equals( " 2 " )) {
            fieldname
= (String)req.getParameter( " fieldname " );
            value
= (String)req.getParameter( " value " );
            req.setAttribute(
" fieldname " , fieldname);
            req.setAttribute(
" value " , value);
        }

        
        String maxid
= productsService.getMaxID();
        req.setAttribute(
" maxid " , maxid);
        
return  mapping.findForward( " add " );
    }

    
    
/**  
     * 添加信息
     
*/

    
public  ActionForward doAddProduct(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res)
{
        ProductsForm pf
= (ProductsForm)form;
        String flag
= pf.getFlag();
        req.setAttribute(
" flag " , flag);
        String fieldname
= "" ;
        String value
= "" ;
        
if (flag.equals( " 2 " )) {
            fieldname
= pf.getFieldname();
            value
= pf.getValue();
            req.setAttribute(
" fieldname " , fieldname);
            req.setAttribute(
" value " , value);
        }

        
        Products pd
= new  Products();
        pd.setGameCapacity(pf.getGameCapacity());
        pd.setGameId(pf.getGameId());
        pd.setGameMedia(pf.getGameMedia());
        pd.setGameNameCn(pf.getGameNameCn());
        pd.setGameNameEn(pf.getGameNameEn());
        pd.setGameVersion(pf.getGameVersion());
        pd.setGameCopyright(pf.getGameCopyright());
        pd.setGameContent(pf.getGameContent());
        
if (pf.getGamePrice().equals( "" )) {
            pd.setGamePrice(
null );
        }
else {
            pd.setGamePrice(pf.getGamePrice());
        }

        
        
int  sign = 1 ;
        
try {
            productsService.addProduct(pd);
            sign
= 1 ;
        }
catch (Exception e) {
            sign
= 2 ;
        }

        
        
if (sign == 1 ) {
            
return  mapping.findForward( " success " );
        }
else {
            
return  mapping.findForward( " failure " );
        }

    }

    
    
/**  
     * 修改信息
     
*/

    
public  ActionForward doUpdateProduct(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res)
{
        ProductsForm pf
= (ProductsForm)form;
        String gameId
= pf.getGameId();
        
        String flag
= pf.getFlag();
        req.setAttribute(
" flag " , flag);
        String fieldname
= "" ;
        String value
= "" ;
        
if (flag.equals( " 2 " )) {
            fieldname
= pf.getFieldname();
            value
= pf.getValue();
            req.setAttribute(
" fieldname " , fieldname);
            req.setAttribute(
" value " , value);
        }

        
        Products pd
= productsService.getProduct(gameId);
        pd.setGameCapacity(pf.getGameCapacity());
        pd.setGameId(pf.getGameId());
        pd.setGameMedia(pf.getGameMedia());
        pd.setGameNameCn(pf.getGameNameCn());
        pd.setGameNameEn(pf.getGameNameEn());
        pd.setGameVersion(pf.getGameVersion());
        pd.setGameCopyright(pf.getGameCopyright());
        pd.setGameContent(pf.getGameContent());
        
if (pf.getGamePrice().equals( "" )) {
            pd.setGamePrice(
null );
        }
else {
            pd.setGamePrice(pf.getGamePrice());
        }

        
        
int  sign = 1 ;
        
try {
            productsService.updateProductd(pd);
            sign
= 1 ;
        }
catch (Exception e) {
            sign
= 2 ;
        }

        
        
if (sign == 1 ) {
            
return  mapping.findForward( " success " );
        }
else {
            
return  mapping.findForward( " failure " );
        }

    }

    
    
/**  
     * 删除信息
     
*/

    
public  ActionForward doDeleteProduct(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res)
{
        String flag
= req.getParameter( " flag " );
        req.setAttribute(
" flag " , flag);
        String fieldname
= "" ;
        String value
= "" ;
        
if (flag.equals( " 2 " )) {
            fieldname
= (String)req.getParameter( " fieldname " );
            value
= (String)req.getParameter( " value " );
            req.setAttribute(
" fieldname " , fieldname);
            req.setAttribute(
" value " , value);
        }

        
        String gameId
= req.getParameter( " gameId " );
        
        Products pd
= productsService.getProduct(gameId);
        
int  sign = 1 ;
        
try {
            productsService.deleteProduct(pd);
            sign
= 1 ;
        }
catch (Exception e) {
            sign
= 2 ;
        }

        
        
if (sign == 1 ) {
            
return  mapping.findForward( " success " );
        }
else {
            
return  mapping.findForward( " failure " );
        }

    }

    
    
/**  
     * 返回信息
     
*/

    
public  ActionForward doReturnProduct(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res)
{
        String flag
= req.getParameter( " flag " );
        req.setAttribute(
" flag " , flag);
        String fieldname
= "" ;
        String value
= "" ;
        
if (flag.equals( " 1 " )) {
            
int  totalRows = productsService.getRows();
            String currentPage
= req.getParameter( " currentPage " );
            String pagerMethod
= req.getParameter( " pagerMethod " );
            
            Pager pager
= pagerService.getPager(currentPage, pagerMethod, totalRows);
            
            List productsList
= productsService.getProducts(pager.getPageSize(), pager.getStartRow());
            
            req.setAttribute(
" productsList " , productsList);
            req.setAttribute(
" PAGER " , pager);
            req.setAttribute(
" flag " , flag);
            req.setAttribute(
" totalRows " , String.valueOf(totalRows));
        }
else   if (flag.equals( " 2 " )) {
            fieldname
= (String)req.getParameter( " fieldname " );
            value
= (String)req.getParameter( " value " );
            
int  totalRows = productsService.getRows(fieldname,value);
            String currentPage
= req.getParameter( " currentPage " );
            String pagerMethod
= req.getParameter( " pagerMethod " );
            
            Pager pager
= pagerService.getPager(currentPage, pagerMethod, totalRows);

            req.setAttribute(
" fieldname " , fieldname);
            req.setAttribute(
" value " , value);
            
            List productsList
= productsService.queryProducts(fieldname, value,pager.getPageSize(), pager.getStartRow());
            
            req.setAttribute(
" productsList " , productsList);
            req.setAttribute(
" PAGER " , pager);
            req.setAttribute(
" totalRows " , String.valueOf(totalRows));
        }

        
        
return  mapping.findForward( " all " );
        
    }

    
    
/**  
     * 查询信息
     
*/

    
public  ActionForward doQueryProduct(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res)
{
        String flag
= req.getParameter( " flag " );
        req.setAttribute(
" flag " , flag);
        String fieldname
= "" ;
        String value
= "" ;
        fieldname
= (String)req.getParameter( " fieldname " );
        value
= (String)req.getParameter( " value " );
        
        
int  totalRows = productsService.getRows(fieldname,value);
        String currentPage
= req.getParameter( " currentPage " );
        String pagerMethod
= req.getParameter( " pagerMethod " );
        
        Pager pager
= pagerService.getPager(currentPage, pagerMethod, totalRows);

        req.setAttribute(
" fieldname " , fieldname);
        req.setAttribute(
" value " , value);
        
        List productsList
= productsService.queryProducts(fieldname, value,pager.getPageSize(), pager.getStartRow());
        
        req.setAttribute(
" productsList " , productsList);
        req.setAttribute(
" PAGER " , pager);
        req.setAttribute(
" totalRows " , String.valueOf(totalRows));
        
        
return  mapping.findForward( " all " );
        
    }


    
public  ProductsService getProductsService()  {
        
return  productsService;
    }


    
public   void  setProductsService(ProductsService productsService)  {
        
this .productsService  =  productsService;
    }


    
public  PagerService getPagerService()  {
        
return  pagerService;
    }


    
public   void  setPagerService(PagerService pagerService)  {
        
this .pagerService  =  pagerService;
    }

    
}


 

com.game.products.web.forms 包中新建 ProductsForm ,他继承了 ValidatorForm 。代码如下:

package  com.game.products.web.forms;

import  javax.servlet.http.HttpServletRequest;

import  org.apache.struts.action.ActionMapping;
import  org.apache.struts.validator.ValidatorForm;

public   class  ProductsForm  extends  ValidatorForm  {
    
//     Fields 
     private  String gameId; // 编号
     private  String gameNameCn; // 中文名称
     private  String gameNameEn; // 英文名称
     private  String gameCapacity; // 碟数
     private  String gameVersion; // 版本
     private  String gameMedia; // 介质
     private  String gameCopyright; // 版权
     private  String gamePrice; // 价格
     private  String gameContent; // 攻略
    
    
private  String flag;
    
private  String fieldname;
    
private  String value;
    
    
//     Constructors
     public  ProductsForm() {
        gameId
= null ;
        gameNameCn
= null ;
        gameNameEn
= null ;
        gameCapacity
= null ;
        gameVersion
= null ;
        gameMedia
= null ;
        gameCopyright
= null ;
        gamePrice
= null ;
        gameContent
= null ;
        
        flag
= null ;
        fieldname
= null ;
        value
= null ;
    }

    
    
//  reset
     public   void  reset(ActionMapping mapping, HttpServletRequest request)  {
        gameId
= null ;
        gameNameCn
= null ;
        gameNameEn
= null ;
        gameCapacity
= null ;
        gameVersion
= null ;
        gameMedia
= null ;
        gameCopyright
= null ;
        gamePrice
= null ;
        gameContent
= null ;
        
        flag
= null ;
        fieldname
= null ;
        value
= null ;
    }

    
    
//     Property accessors
     public  String getGameCapacity()  {
        
return  gameCapacity;
    }


    
public   void  setGameCapacity(String gameCapacity)  {
        
this .gameCapacity  =  gameCapacity;
    }


    
public  String getGameId()  {
        
return  gameId;
    }


    
public   void  setGameId(String gameId)  {
        
this .gameId  =  gameId;
    }


    
public  String getGameNameCn()  {
        
return  gameNameCn;
    }


    
public   void  setGameNameCn(String gameNameCn)  {
        
this .gameNameCn  =  gameNameCn;
    }


    
public  String getGameNameEn()  {
        
return  gameNameEn;
    }


    
public   void  setGameNameEn(String gameNameEn)  {
        
this .gameNameEn  =  gameNameEn;
    }


    
public  String getGameVersion()  {
        
return  gameVersion;
    }


    
public   void  setGameVersion(String gameVersion)  {
        
this .gameVersion  =  gameVersion;
    }


    
public  String getGameMedia()  {
        
return  gameMedia;
    }


    
public   void  setGameMedia(String gameMedia)  {
        
this .gameMedia  =  gameMedia;
    }


    
public  String getFieldname()  {
        
return  fieldname;
    }


    
public   void  setFieldname(String fieldname)  {
        
this .fieldname  =  fieldname;
    }


    
public  String getFlag()  {
        
return  flag;
    }


    
public   void  setFlag(String flag)  {
        
this .flag  =  flag;
    }


    
public  String getValue()  {
        
return  value;
    }


    
public   void  setValue(String value)  {
        
this .value  =  value;
    }


    
public  String getGameCopyright()  {
        
return  gameCopyright;
    }


    
public   void  setGameCopyright(String gameCopyright)  {
        
this .gameCopyright  =  gameCopyright;
    }


    
public  String getGameContent()  {
        
return  gameContent;
    }


    
public   void  setGameContent(String gameContent)  {
        
this .gameContent  =  gameContent;
    }


    
public  String getGamePrice()  {
        
return  gamePrice;
    }


    
public   void  setGamePrice(String gamePrice)  {
        
this .gamePrice  =  gamePrice;
    }


}

接着编写配置文件。

struts-config 包中新建 struts-config.xml 。代码如下:

<? xml version="1.0" encoding="ISO-8859-1" ?>
<! 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-bean  name ="productsForm"  type ="com.game.products.web.forms.ProductsForm"   />
    
</ form-beans >
    
    
< global-forwards >
        
< forward  name ="success"  path ="/products/product_success.jsp"   />
        
< forward  name ="failure"  path ="/products/product_failure.jsp"   />
    
</ global-forwards >
    
    
< action-mappings >
        
< action  path ="/getProducts"  type ="org.springframework.web.struts.DelegatingActionProxy"  parameter ="method"  scope ="request"  validate ="false" >
            
< forward  name ="all"  path ="/products/products.jsp"   />
        
</ action >
        
< action  path ="/getProduct"  type ="org.springframework.web.struts.DelegatingActionProxy"  parameter ="method"  scope ="request"  validate ="false" >
            
< forward  name ="one"  path ="/products/product.jsp"   />
        
</ action >
        
< action  path ="/deleteProduct"  type ="org.springframework.web.struts.DelegatingActionProxy"  parameter ="method"  scope ="request"  validate ="false" >             
        
</ action >
        
< action  path ="/addProductPage"  type ="org.springframework.web.struts.DelegatingActionProxy"  parameter ="method"  scope ="request"  validate ="false" >
            
< forward  name ="add"  path ="/products/addproduct.jsp"   />
        
</ action >
        
< action  path ="/addProduct"  name ="productsForm"  type ="org.springframework.web.struts.DelegatingActionProxy"  parameter ="method"  scope ="request"  validate ="false"  input ="/product_failure.jsp" >
        
</ action >
        
< action  path ="/updateProduct"  name ="productsForm"  type ="org.springframework.web.struts.DelegatingActionProxy"  parameter ="method"  scope ="request"  validate ="false"  input ="/product_failure.jsp" >
        
</ action >
        
        
< action  path ="/returnProduct"  type ="org.springframework.web.struts.DelegatingActionProxy"  parameter ="method"  scope ="request"  validate ="false" >
            
< forward  name ="all"  path ="/products/products.jsp"   />
        
</ action >
        
< action  path ="/queryProducts"  type ="org.springframework.web.struts.DelegatingActionProxy"  parameter ="method"  scope ="request"  validate ="false" >
            
< forward  name ="all"  path ="/products/products.jsp"   />
        
</ action >
    
</ action-mappings >
    
    
< message-resources  parameter ="com.game.resources.ApplicationResourcesProducts"   />
    
    
< plug-in  className ="org.apache.struts.validator.ValidatorPlugIn" >
        
< set-property  property ="pathnames"
            value
="/WEB-INF/struts-validator/validator-rules.xml,/WEB-INF/struts-validator/validation.xml" />
    
</ plug-in >     
    
</ struts-config >


 

需要注意的是,这里的 action 交由 spring DelegatingActionProxy 管理了。

打开 applicationContext.xml ,接着添加如下代码:

<!--  View  -->
    
< bean  name ="/getProducts"  class ="com.game.products.web.actions.ProductsAction"  singleton ="false" >
        
< property  name ="productsService" >
            
< ref  bean ="productsService" />
        
</ property >
        
< property  name ="pagerService" >
            
< ref  bean ="pagerService" />
        
</ property >
    
</ bean >
    
< bean  name ="/getProduct"  class ="com.game.products.web.actions.ProductsAction"  singleton ="false" >
        
< property  name ="productsService" >
            
< ref  bean ="productsService" />
        
</ property >
    
</ bean >
    
< bean  name ="/deleteProduct"  class ="com.game.products.web.actions.ProductsAction"  singleton ="false" >
        
< property  name ="productsService" >
            
< ref  bean ="productsService" />
        
</ property >
    
</ bean >
    
< bean  name ="/addProductPage"  class ="com.game.products.web.actions.ProductsAction"  singleton ="false" >
        
< property  name ="productsService" >
            
< ref  bean ="productsService" />
        
</ property >
    
</ bean >
    
< bean  name ="/addProduct"  class ="com.game.products.web.actions.ProductsAction"  singleton ="false" >
        
< property  name ="productsService" >
            
< ref  bean ="productsService" />
        
</ property >
    
</ bean >
    
< bean  name ="/updateProduct"  class ="com.game.products.web.actions.ProductsAction"  singleton ="false" >
        
< property  name ="productsService" >
            
< ref  bean ="productsService" />
        
</ property >
    
</ bean >
    
< bean  name ="/returnProduct"  class ="com.game.products.web.actions.ProductsAction"  singleton ="false" >
        
< property  name ="productsService" >
            
< ref  bean ="productsService" />
        
</ property >
        
< property  name ="pagerService" >
            
< ref  bean ="pagerService" />
        
</ property >
    
</ bean >
    
< bean  name ="/queryProducts"  class ="com.game.products.web.actions.ProductsAction"  singleton ="false" >
        
< property  name ="productsService" >
            
< ref  bean ="productsService" />
        
</ property >
        
< property  name ="pagerService" >
            
< ref  bean ="pagerService" />
        
</ property >
    
</ bean >


 

接着编写 web.xml ,代码如下:

<? xml version="1.0" encoding="GB2312" ?>
<! 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 >
    
< display-name > 游戏软件管理系统 </ display-name >
    
< context-param >
        
< param-name > log4jConfigLocation </ param-name >
        
< param-value > /WEB-INF/classes/log4j.properties </ param-value >
    
</ context-param >
    
< context-param >
        
< param-name > contextConfigLocation </ param-name >
        
< param-value > /WEB-INF/spring-context/applicationContext.xml </ param-value >
      
</ context-param >
    
    
< filter >
        
< filter-name > Set Character Encoding </ filter-name >
        
< filter-class > com.game.commons.SetCharacterEncodingFilter </ filter-class >
        
< init-param >
            
< param-name > encoding </ param-name >
            
< param-value > GB2312 </ param-value >
        
</ init-param >
    
</ filter >

    
< filter-mapping >
        
< filter-name > Set Character Encoding </ filter-name >
        
< url-pattern > /* </ url-pattern >
    
</ filter-mapping >
    
    
<!--
          - Loads the root application context of this web app at startup.
          - The application context is then available via
          - WebApplicationContextUtils.getWebApplicationContext(servletContext).
      
-->
      
< listener >
        
< listener-class > org.springframework.web.context.ContextLoaderListener </ listener-class >
      
</ listener >

      
< listener >
        
< listener-class > org.springframework.web.util.Log4jConfigListener </ listener-class >
      
</ listener >
    
    
<!--  Action Servlet Configuration  -->
    
< 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/struts-config.xml </ param-value >
            
</ init-param >
            
< init-param >
                
< param-name > debug </ param-name >
                
< param-value > 3 </ param-value >
            
</ init-param >
            
< init-param >
                
< param-name > detail </ param-name >
                
< param-value > 3 </ param-value >
            
</ init-param >
            
< init-param >
                
< param-name > nocache </ param-name >
                
< param-value > yes </ param-value >
            
</ init-param >
            
< load-on-startup > 2 </ load-on-startup >
    
</ servlet >
    
    
<!--  Action Servlet Mapping  -->
    
< servlet-mapping >
        
< servlet-name > action </ servlet-name >
        
< url-pattern > *.do </ url-pattern >
    
</ servlet-mapping >
 
    
<!--  The Welcome File List  -->
    
< welcome-file-list >
        
< welcome-file > products/index.jsp </ welcome-file >
    
</ welcome-file-list >

    
<!--  Struts Tag Library Descriptors  -->
    
< taglib >
        
< taglib-uri > struts-bean </ taglib-uri >
        
< taglib-location > /WEB-INF/tld/struts-bean.tld </ taglib-location >
    
</ taglib >

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

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

    
< taglib >
        
< taglib-uri > struts-nested </ taglib-uri >
        
< taglib-location > /WEB-INF/tld/struts-nested.tld </ taglib-location >
    
</ taglib >
</ web-app >

大家可能注意到了这里有个 Set Character Encoding 过滤器。我们需要在 com.game.commons 包中新建 SetCharacterEncodingFilter 类来过滤编码,类的代码如下:

package  com.game.commons;

import  java.io.IOException;

import  javax.servlet.Filter;
import  javax.servlet.FilterChain;
import  javax.servlet.FilterConfig;
import  javax.servlet.ServletException;
import  javax.servlet.ServletRequest;
import  javax.servlet.ServletResponse;

public   class  SetCharacterEncodingFilter  implements  Filter  {
protected  String encoding  =   null ;
protected  FilterConfig filterConfig  =   null ;
protected   boolean  ignore  =   true ;

public   void  init(FilterConfig filterConfig)  throws  ServletException  {
this .filterConfig = filterConfig;
this .encoding = filterConfig.getInitParameter( " encoding " );
String value
= filterConfig.getInitParameter( " ignore " );
if (value == null )
this .ignore = true ;
else   if (value.equalsIgnoreCase( " true " ))
this .ignore = true ;
else
this .ignore = false ;
}


public   void  doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  throws  IOException, ServletException  {
//  TODO 自动生成方法存根
if  (ignore  ||  (request.getCharacterEncoding()  ==   null ))  {
String encoding 
=  selectEncoding(request);
if  (encoding  !=   null )
request.setCharacterEncoding(encoding);
}

chain.doFilter(request, response);
}


public   void  destroy()  {
//  TODO 自动生成方法存根
this .encoding  =   null ;
this .filterConfig  =   null ;
}


protected  String selectEncoding(ServletRequest request)  {
return  ( this .encoding);
}

}

为了项目的测试运行,我们还需要配置 log4j.properties ,这个文件放在 src 根目录下。代码如下:

log4j.rootLogger=info,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.SimpleLayout
log4j.logger.com.wehave=DEBUG
# log4j.logger.org.springframework=DEBUG
# SqlMap logging configuration
# log4j.logger.com.ibatis=DEBUG
# log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
# log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
# log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
# log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
#log4j.logger.java.sql.ResultSet=DEBUG
#log4j.logger.javax.sql=DEBUG


 

这是一个简单的 log4j 配置方法,只是在后台打印出需要的数据。如果还有别的需求,可以参考这个文档:如何使用 Log4j

为了达到页面验证的目的,我们还需要使用到 struts 的验证框架。

struts-validator 中添加 validation.xml 。在这配置验证规则:

<! DOCTYPE form-validation PUBLIC
    "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
    "http://jakarta.apache.org/commons/dtds/validator_1_0.dtd"
>
    
< form-validation >
    
< formset >
        
< form  name ="productsForm" >
            
< field  property ="gameNameCn"  depends ="required" >
                
< arg0  key ="errors.gameNameCn" />
            
</ field >     
            
< field  property ="gameNameEn"  depends ="required" >
                
< arg0  key ="errors.gameNameEn" />
            
</ field >
            
< field  property ="gameCapacity"  depends ="integer" >
                
< arg0  key ="errors.gameCapacity" />
            
</ field >
            
< field  property ="gamePrice"  depends ="float" >
                
< arg0  key ="errors.gamePrice" />
            
</ field >
        
</ form >     
    
</ formset >
</ form-validation >

在同个目录下,添加 validator-rules.xml ,这个在 struts 开发包中有,只需要 copy 过来就可以用了。为了方便大家,我这里将里面配置代码粘贴出来:

<? xml version="1.0" encoding="ISO-8859-1"  ?>
<! DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_0.dtd"
>
<!--

   This file contains the default Struts Validator pluggable validator
   definitions.  It should be placed somewhere under /WEB-INF and
   referenced in the struts-config.xml under the plug-in element
   for the ValidatorPlugIn.

      <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
                                                  /WEB-INF/validation.xml"/>
      </plug-in>

   These are the default error messages associated with
   each validator defined in this file.  They should be
   added to your projects ApplicationResources.properties
   file or you can associate new ones by modifying the
   pluggable validators msg attributes in this file.

   # Struts Validator Error Messages
   errors.required={0} is required.
   errors.minlength={0} can not be less than {1} characters.
   errors.maxlength={0} can not be greater than {1} characters.
   errors.invalid={0} is invalid.

   errors.byte={0} must be a byte.
   errors.short={0} must be a short.
   errors.integer={0} must be an integer.
   errors.long={0} must be a long.
   errors.float={0} must be a float.
   errors.double={0} must be a double.

   errors.date={0} is not a date.
   errors.range={0} is not in the range {1} through {2}.
   errors.creditcard={0} is an invalid credit card number.
   errors.email={0} is an invalid e-mail address.

-->

< form-validation >

    
< global >
        
< validator  name ="required"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateRequired"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            msg
="errors.required" >
            
< javascript > <![CDATA[
            function validateRequired(form) {
                var isValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oRequired = new required();
                for (x in oRequired) {
                    var field = form[oRequired[x][0]];
                    
                    if (field.type == 'text' ||
                        field.type == 'textarea' ||
                        field.type == 'file' ||
                        field.type == 'select-one' ||
                        field.type == 'radio' ||
                        field.type == 'password' ||
                        field.type == 'hidden') {
                        
                        var value = '';
                        // get field's value
                        if (field.type == "select-one") {
                            var si = field.selectedIndex;
                            if (si >= 0) {
                                value = field.options[si].value;
                            }
                        } else {
                            value = field.value;
                        }
                        
                        if (trim(value).length == 0) {
                        
                            if (i == 0) {
                                focusField = field;
                            }
                            fields[i++] = oRequired[x][1];
                            isValid = false;
                        }
                    }
                }
                if (fields.length > 0) {
                  if(focusField.type!='hidden'){
                   focusField.focus();
                  }
                   alert(fields.join('"n'));
                }
                return isValid;
            }
            
            // Trim whitespace from left and right sides of s.
            function trim(s) {
                return s.replace( /^"s*/, "" ).replace( /"s*$/, "" );
            }
            
            
]]>   </ javascript >
        
</ validator >
        
<!--
          Åжϸ´Ñ¡¿ò²»ÄÜΪ¿Õ
          ÕÔÆ·º£  2004
          
-->
        
< validator  name ="requiredif"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateRequiredIf"  
            methodParams
="java.lang.Object,
                               org.apache.commons.validator.ValidatorAction,
                               org.apache.commons.validator.Field,
                               org.apache.struts.action.ActionErrors,
                               org.apache.commons.validator.Validator,
                               javax.servlet.http.HttpServletRequest"
 
            msg
="errors.required" >
            
< javascript > <![CDATA[
            function validateRequiredIf(form) {
                var isValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                var j=0;
                oRequiredif = new requiredif();
                for (x in oRequiredif) {
                    var field = form[oRequiredif[x][0]];
                    for(var ii=0;ii<field.length;ii++){
                        if(field[ii].checked==true){
                            j++;
                        }
                    }  
                     if (j == 0) {
                        
                            if (i == 0) {
                                focusField = field;
                            }
                            fields[i++] = oRequiredif[x][1];
                            isValid = false;
                    }
                }

                if (fields.length > 0) {
                   alert(fields.join('"n'));
                }
                return isValid;
            }
            
]]>   </ javascript >
        
</ validator >
        
< validator  name ="minlength"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateMinLength"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.minlength" >
            
< javascript > <![CDATA[
            function validateMinLength(form) {
                var isValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oMinLength = new minlength();
                for (x in oMinLength) {
                    var field = form[oMinLength[x][0]];
                    
                    if (field.type == 'text' ||
                        field.type == 'textarea'||
                        field.type == 'password') {
                        
                        var iMin = parseInt(oMinLength[x][2]("minlength"));
                        if ((trim(field.value).length > 0) && (field.value.length < iMin)) {
                            if (i == 0) {
                                focusField = field;
                            }
                            fields[i++] = oMinLength[x][1];
                            isValid = false;
                        }
                    }
                }
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('"n'));
                }
                return isValid;
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="maxlength"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateMaxLength"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.maxlength" >
            
< javascript > <![CDATA[
            function validateMaxLength(form) {
                var isValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oMaxLength = new maxlength();
                for (x in oMaxLength) {
                    var field = form[oMaxLength[x][0]];
                    
                    if (field.type == 'text' ||
                        field.type == 'textarea'||
                        field.type == 'password') {
                        
                        var iMax = parseInt(oMaxLength[x][2]("maxlength"));
                        if (field.value.length > iMax) {
                            if (i == 0) {
                                focusField = field;
                            }
                            fields[i++] = oMaxLength[x][1];
                            isValid = false;
                        }
                    }
                }
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('"n'));
                }
                return isValid;
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="mask"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateMask"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.invalid" >
            
< javascript > <![CDATA[
            function validateMask(form) {
                var isValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oMasked = new mask();
                for (x in oMasked) {
                    var field = form[oMasked[x][0]];
                    
                    if ((field.type == 'text' || 
                         field.type == 'textarea'||
                        field.type == 'password') && 
                         (field.value.length > 0)) {
                        
                        if (!matchPattern(field.value, oMasked[x][2]("mask"))) {
                            if (i == 0) {
                                focusField = field;
                            }
                            fields[i++] = oMasked[x][1];
                            isValid = false;
                        }
                    }
                }
                
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('"n'));
                }
                return isValid;
            }

            function matchPattern(value, mask) {
               return mask.exec(value);
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="byte"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateByte"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.byte"  jsFunctionName ="ByteValidations" >
            
< javascript > <![CDATA[
            function validateByte(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oByte = new ByteValidations();
                for (x in oByte) {
                    var field = form[oByte[x][0]];
                    
                    if (field.type == 'text' ||
                        field.type == 'textarea' ||
                        field.type == 'select-one' ||
                        field.type == 'radio') {

                        var value = '';
                        // get field's value
                        if (field.type == "select-one") {
                            var si = field.selectedIndex;
                            if (si >= 0) {
                                value = field.options[si].value;
                            }
                        } else {
                            value = field.value;
                        }
                        
                        if (value.length > 0) {
                            if (!isAllDigits(value)) {
                                bValid = false;
                                if (i == 0) {
                                    focusField = field;
                                }
                                fields[i++] = oByte[x][1];

                            } else {

                                var iValue = parseInt(value);
                                if (isNaN(iValue) || !(iValue >= -128 && iValue <= 127)) {
                                    if (i == 0) {
                                        focusField = field;
                                    }
                                    fields[i++] = oByte[x][1];
                                    bValid = false;
                                }
                            }
                        }
                        
                    }
                }
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('"n'));
                }
                return bValid;
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="short"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateShort"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.short"  jsFunctionName ="ShortValidations" >
            
< javascript > <![CDATA[
            function validateShort(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oShort = new ShortValidations();
                for (x in oShort) {
                    var field = form[oShort[x][0]];
                    
                    if (field.type == 'text' ||
                        field.type == 'textarea' ||
                        field.type == 'select-one' ||
                        field.type == 'radio') {
                        
                        var value = '';
                        // get field's value
                        if (field.type == "select-one") {
                            var si = field.selectedIndex;
                            if (si >= 0) {
                                value = field.options[si].value;
                            }
                        } else {
                            value = field.value;
                        }
                        
                        if (value.length > 0) {
                            if (!isAllDigits(value)) {
                                bValid = false;
                                if (i == 0) {
                                    focusField = field;
                                }
                                fields[i++] = oShort[x][1];

                            } else {
                        
                                var iValue = parseInt(value);
                                if (isNaN(iValue) || !(iValue >= -32768 && iValue <= 32767)) {
                                    if (i == 0) {
                                        focusField = field;
                                    }
                                    fields[i++] = oShort[x][1];
                                    bValid = false;
                                }
                           }
                       }
                    }
                }
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('"n'));
                }
                return bValid;
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="integer"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateInteger"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.integer"  jsFunctionName ="IntegerValidations" >
            
< javascript > <![CDATA[
            function validateInteger(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oInteger = new IntegerValidations();
                for (x in oInteger) {
                    var field = form[oInteger[x][0]];

                    if (field.type == 'text' ||
                        field.type == 'textarea' ||
                        field.type == 'select-one' ||
                        field.type == 'radio') {
                        
                        var value = '';
                        // get field's value
                        if (field.type == "select-one") {
                            var si = field.selectedIndex;
                            if (si >= 0) {
                                value = field.options[si].value;
                            }
                        } else {
                            value = field.value;
                        }
                        
                        if (value.length > 0) {
                        
                            if (!isAllDigits(value)) {
                                bValid = false;
                                if (i == 0) {
                                    focusField = field;
                                }
                                fields[i++] = oInteger[x][1];
                                
                            } else {
                                var iValue = parseInt(value);
                                if (isNaN(iValue) || !(iValue >= -2147483648 && iValue <= 2147483647)) {
                                    if (i == 0) {
                                        focusField = field;
                                    }
                                    fields[i++] = oInteger[x][1];
                                    bValid = false;
                               }
                           }
                       }
                    }
                }
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('"n'));
                }
                return bValid;
            }

            function isAllDigits(argvalue) {
                argvalue = argvalue.toString();
                var validChars = "0123456789";
                var startFrom = 0;
                if (argvalue.substring(0, 2) == "0x") {
                   validChars = "0123456789abcdefABCDEF";
                   startFrom = 2;
                } else if (argvalue.charAt(0) == "-") {
                    startFrom = 1;
                }
                
                for (var n = startFrom; n < argvalue.length; n++) {
                    if (validChars.indexOf(argvalue.substring(n, n+1)) == -1) return false;
                }
                return true;
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="long"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateLong"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.long" />
        
< validator  name ="float"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateFloat"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.float"  jsFunctionName ="FloatValidations" >
            
< javascript > <![CDATA[
            function validateFloat(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oFloat = new FloatValidations();
                for (x in oFloat) {
                    var field = form[oFloat[x][0]];
                    
                    if (field.type == 'text' ||
                        field.type == 'textarea' ||
                        field.type == 'select-one' ||
                        field.type == 'radio') {
                        
                        var value = '';
                        // get field's value
                        if (field.type == "select-one") {
                            var si = field.selectedIndex;
                            if (si >= 0) {
                                value = field.options[si].value;
                            }
                        } else {
                            value = field.value;
                        }
                        
                        if (value.length > 0) {
                            // remove '.' before checking digits
                            var tempArray = value.split('.');
                            var joinedString= tempArray.join('');

                            if (!isAllDigits(joinedString)) {
                                bValid = false;
                                if (i == 0) {
                                    focusField = field;
                                }
                                fields[i++] = oFloat[x][1];

                            } else {
                                var iValue = parseFloat(value);
                                if (isNaN(iValue)) {
                                    if (i == 0) {
                                        focusField = field;
                                    }
                                    fields[i++] = oFloat[x][1];
                                    bValid = false;
                                }
                            }
                        }
                    }
                }
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('"n'));
                }
                return bValid;
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="double"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateDouble"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.double" />
        
< validator  name ="date"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateDate"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.date"  jsFunctionName ="DateValidations" >
            
< javascript > <![CDATA[
            function validateDate(form) {
               var bValid = true;
               var focusField = null;
               var i = 0;
               var fields = new Array();
               oDate = new DateValidations();
               for (x in oDate) {
                   var value = form[oDate[x][0]].value;
                   var datePattern = oDate[x][2]("datePatternStrict");
                   if ((form[oDate[x][0]].type == 'text' ||
                        form[oDate[x][0]].type == 'textarea') &&
                       (value.length > 0) &&
                       (datePattern.length > 0)) {
                     var MONTH = "MM";
                     var DAY = "dd";
                     var YEAR = "yyyy";
                     var orderMonth = datePattern.indexOf(MONTH);
                     var orderDay = datePattern.indexOf(DAY);
                     var orderYear = datePattern.indexOf(YEAR);
                     if ((orderDay < orderYear && orderDay > orderMonth)) {
                         var iDelim1 = orderMonth + MONTH.length;
                         var iDelim2 = orderDay + DAY.length;
                         var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
                         var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
                         if (iDelim1 == orderDay && iDelim2 == orderYear) {
                            dateRegexp = new RegExp("^(""d{2})(""d{2})(""d{4})$");
                         } else if (iDelim1 == orderDay) {
                            dateRegexp = new RegExp("^(""d{2})(""d{2})[" + delim2 + "](""d{4})$");
                         } else if (iDelim2 == orderYear) {
                            dateRegexp = new RegExp("^(""d{2})[" + delim1 + "](""d{2})(""d{4})$");
                         } else {
                            dateRegexp = new RegExp("^(""d{2})[" + delim1 + "](""d{2})[" + delim2 + "](""d{4})$");
                         }
                         var matched = dateRegexp.exec(value);
                         if(matched != null) {
                            if (!isValidDate(matched[2], matched[1], matched[3])) {
                               if (i == 0) {
                                   focusField = form[oDate[x][0]];
                               }
                               fields[i++] = oDate[x][1];
                               bValid =  false;
                            }
                         } else {
                            if (i == 0) {
                                focusField = form[oDate[x][0]];
                            }
                            fields[i++] = oDate[x][1];
                            bValid =  false;
                         }
                     } else if ((orderMonth < orderYear && orderMonth > orderDay)) {
                         var iDelim1 = orderDay + DAY.length;
                         var iDelim2 = orderMonth + MONTH.length;
                         var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
                         var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
                         if (iDelim1 == orderMonth && iDelim2 == orderYear) {
                             dateRegexp = new RegExp("^(""d{2})(""d{2})(""d{4})$");
                         } else if (iDelim1 == orderMonth) {
                             dateRegexp = new RegExp("^(""d{2})(""d{2})[" + delim2 + "](""d{4})$");
                         } else if (iDelim2 == orderYear) {
                             dateRegexp = new RegExp("^(""d{2})[" + delim1 + "](""d{2})(""d{4})$");
                         } else {
                             dateRegexp = new RegExp("^(""d{2})[" + delim1 + "](""d{2})[" + delim2 + "](""d{4})$");
                         }
                         var matched = dateRegexp.exec(value);
                         if(matched != null) {
                             if (!isValidDate(matched[1], matched[2], matched[3])) {
                                 if (i == 0) {
                                     focusField = form[oDate[x][0]];
                                 }
                                 fields[i++] = oDate[x][1];
                                 bValid =  false;
                              }
                         } else {
                             if (i == 0) {
                                 focusField = form[oDate[x][0]];
                             }
                             fields[i++] = oDate[x][1];
                             bValid =  false;
                         }
                     } else if ((orderMonth > orderYear && orderMonth < orderDay)) {
                         var iDelim1 = orderYear + YEAR.length;
                         var iDelim2 = orderMonth + MONTH.length;
                         var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
                         var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
                         if (iDelim1 == orderMonth && iDelim2 == orderDay) {
                             dateRegexp = new RegExp("^(""d{4})(""d{2})(""d{2})$");
                         } else if (iDelim1 == orderMonth) {
                             dateRegexp = new RegExp("^(""d{4})(""d{2})[" + delim2 + "](""d{2})$");
                         } else if (iDelim2 == orderDay) {
                             dateRegexp = new RegExp("^(""d{4})[" + delim1 + "](""d{2})(""d{2})$");
                         } else {
                             dateRegexp = new RegExp("^(""d{4})[" + delim1 + "](""d{2})[" + delim2 + "](""d{2})$");
                         }
                         var matched = dateRegexp.exec(value);
                         if(matched != null) {
                             if (!isValidDate(matched[3], matched[2], matched[1])) {
                                 if (i == 0) {
                                     focusField = form[oDate[x][0]];
                                  }
                                  fields[i++] = oDate[x][1];
                                  bValid =  false;
                              }
                          } else {
                              if (i == 0) {
                                  focusField = form[oDate[x][0]];
                              }
                              fields[i++] = oDate[x][1];
                              bValid =  false;
                          }
                     } else {
                         if (i == 0) {
                             focusField = form[oDate[x][0]];
                         }
                         fields[i++] = oDate[x][1];
                         bValid =  false;
                     }
                  }
               }
               if (fields.length > 0) {
                  focusField.focus();
                  alert(fields.join('"n'));
               }
               return bValid;
            }

        function isValidDate(day, month, year) {
            if (month < 1 || month > 12) {
                    return false;
                }
                if (day < 1 || day > 31) {
                    return false;
                }
                if ((month == 4 || month == 6 || month == 9 || month == 11) &&
                    (day == 31)) {
                    return false;
                }
                if (month == 2) {
                    var leap = (year % 4 == 0 &&
                               (year % 100 != 0 || year % 400 == 0));
                    if (day>29 || (day == 29 && !leap)) {
                        return false;
                    }
                }
                return true;
            }
]]>   </ javascript >
        
</ validator >
        
<!--  range is deprecated use intRange instead  -->
        
< validator  name ="range"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateIntRange"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
="integer"  msg ="errors.range" >
            
< javascript > <![CDATA[
            function validateRange(form) {
                return validateIntRange(form);
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="intRange"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateIntRange"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
="integer"  msg ="errors.range" >
            
< javascript > <![CDATA[
            function validateIntRange(form) {
                var isValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oRange = new intRange();
                for (x in oRange) {
                    var field = form[oRange[x][0]];
                    
                    if ((field.type == 'text' ||
                         field.type == 'textarea') &&
                        (field.value.length > 0)) {
                        
                        var iMin = parseInt(oRange[x][2]("min"));
                        var iMax = parseInt(oRange[x][2]("max"));
                        var iValue = parseInt(field.value);
                        if (!(iValue >= iMin && iValue <= iMax)) {
                            if (i == 0) {
                                focusField = field;
                            }
                            fields[i++] = oRange[x][1];
                            isValid = false;
                        }
                    }
                }
                if (fields.length > 0) {
                    focusField.focus();
                    alert(fields.join('"n'));
                }
                return isValid;
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="floatRange"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateFloatRange"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
="float"  msg ="errors.range" >
            
< javascript > <![CDATA[
            function validateFloatRange(form) {
                var isValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oRange = new floatRange();
                for (x in oRange) {
                    var field = form[oRange[x][0]];
                    
                    if ((field.type == 'text' ||
                         field.type == 'textarea') &&
                        (field.value.length > 0)) {
                        
                        var fMin = parseFloat(oRange[x][2]("min"));
                        var fMax = parseFloat(oRange[x][2]("max"));
                        var fValue = parseFloat(field.value);
                        if (!(fValue >= fMin && fValue <= fMax)) {
                            if (i == 0) {
                                focusField = field;
                            }
                            fields[i++] = oRange[x][1];
                            isValid = false;
                        }
                    }
                }
                if (fields.length > 0) {
                    focusField.focus();
                    alert(fields.join('"n'));
                }
                return isValid;
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="creditCard"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateCreditCard"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.creditcard" >
            
< javascript > <![CDATA[
            function validateCreditCard(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oCreditCard = new creditCard();
                for (x in oCreditCard) {
                    if ((form[oCreditCard[x][0]].type == 'text' ||
                         form[oCreditCard[x][0]].type == 'textarea') &&
                        (form[oCreditCard[x][0]].value.length > 0)) {
                        if (!luhnCheck(form[oCreditCard[x][0]].value)) {
                            if (i == 0) {
                                focusField = form[oCreditCard[x][0]];
                            }
                            fields[i++] = oCreditCard[x][1];
                            bValid = false;
                        }
                    }
                }
                if (fields.length > 0) {
                    focusField.focus();
                    alert(fields.join('"n'));
                }
                return bValid;
            }

            /**
             * Reference: http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl
             */
            function luhnCheck(cardNumber) {
                if (isLuhnNum(cardNumber)) {
                    var no_digit = cardNumber.length;
                    var oddoeven = no_digit & 1;
                    var sum = 0;
                    for (var count = 0; count < no_digit; count++) {
                        var digit = parseInt(cardNumber.charAt(count));
                        if (!((count & 1) ^ oddoeven)) {
                            digit *= 2;
                            if (digit > 9) digit -= 9;
                        };
                        sum += digit;
                    };
                    if (sum == 0) return false;
                    if (sum % 10 == 0) return true;
                };
                return false;
            }

            function isLuhnNum(argvalue) {
                argvalue = argvalue.toString();
                if (argvalue.length == 0) {
                    return false;
                }
                for (var n = 0; n < argvalue.length; n++) {
                    if ((argvalue.substring(n, n+1) < "0") ||
                        (argvalue.substring(n,n+1) > "9")) {
                        return false;
                    }
                }
                return true;
            }
]]>   </ javascript >
        
</ validator >
        
< validator  name ="email"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateEmail"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.email" >
            
< javascript > <![CDATA[
            function validateEmail(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                oEmail = new email();
                for (x in oEmail) {
                    if ((form[oEmail[x][0]].type == 'text' ||
                         form[oEmail[x][0]].type == 'textarea') &&
                        (form[oEmail[x][0]].value.length > 0)) {
                        if (!checkEmail(form[oEmail[x][0]].value)) {
                            if (i == 0) {
                                focusField = form[oEmail[x][0]];
                            }
                            fields[i++] = oEmail[x][1];
                            bValid = false;
                        }
                    }
                }
                if (fields.length > 0) {
                    focusField.focus();
                    alert(fields.join('"n'));
                }
                return bValid;
            }

            /**
             * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com),
             * http://javascript.internet.com
             */
            function checkEmail(emailStr) {
               if (emailStr.length == 0) {
                   return true;
               }
               var emailPat=/^(.+)@(.+)$/;
               var specialChars="""("")<>@,;:"""""""""".""[""]";
               var validChars=""[^""s" + specialChars + ""]";
               var quotedUser="(""[^""]*"")";
               var ipDomainPat=/^("d{1,3})[.]("d{1,3})[.]("d{1,3})[.]("d{1,3})$/;
               var atom=validChars + '+';
               var word="(" + atom + "|" + quotedUser + ")";
               var userPat=new RegExp("^" + word + "(""." + word + ")*$");
               var domainPat=new RegExp("^" + atom + "(""." + atom + ")*$");
               var matchArray=emailStr.match(emailPat);
               if (matchArray == null) {
                   return false;
               }
               var user=matchArray[1];
               var domain=matchArray[2];
               if (user.match(userPat) == null) {
                   return false;
               }
               var IPArray = domain.match(ipDomainPat);
               if (IPArray != null) {
                   for (var i = 1; i <= 4; i++) {
                      if (IPArray[i] > 255) {
                         return false;
                      }
                   }
                   return true;
               }
               var domainArray=domain.match(domainPat);
               if (domainArray == null) {
                   return false;
               }
               var atomPat=new RegExp(atom,"g");
               var domArr=domain.match(atomPat);
               var len=domArr.length;
               if ((domArr[domArr.length-1].length < 2) ||
                   (domArr[domArr.length-1].length > 3)) {
                   return false;
               }
               if (len < 2) {
                   return false;
               }
               return true;
            }
]]>   </ javascript >
        
</ validator >
        
<!--
          ÅжÏÊý×éÿ¸öÊýÖµ¶¼²»ÄÜΪ¿Õ
          ÕÔÆ·º£  2004
          
-->
        
< validator  name ="requiredArray"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateRequiredArray"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.required"  
            jsFunctionName
="RequiredArrayValidations" >
            
< javascript > <![CDATA[
            function validateRequiredArray(form) {
                var isValid = true;
                var focusField = null;
                var i = 0;
                var fields = new Array();
                var j=0;
                oRequired = new RequiredArrayValidations();
                for (x in oRequired) {
                    var field = form[oRequired[x][0]];
                    for(var ii=0;ii<field.length;ii++){
                        if(field[ii].value.length>0){
                            j++;
                        }
                    }  
                     if (j < field.length) {
                        
                            if (i == 0) {
                                focusField = field;
                            }
                            fields[i++] = oRequired[x][1];
                            isValid = false;
                    }
                }

                if (fields.length > 0) {
                   alert(fields.join('"n'));
                }
                return isValid;
            }
            
]]>   </ javascript >
        
</ validator >
        
<!--
          ÅжÏÊý×éÿ¸ö²»Îª¿ÕµÄÊýÖµ¶¼±ØÐëΪÕûÐÍ
          ÕÔÆ·º£  2004
          
-->
        
< validator  name ="integerArray"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateIntegerArray"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.integer"  
            jsFunctionName
="IntegerArrayValidations" >
            
< javascript > <![CDATA[
            function validateIntegerArray(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var j=0;
                var fields = new Array();
                oInteger = new IntegerArrayValidations();
                for (x in oInteger) {
                    var field = form[oInteger[x][0]];
                    for(var ii=0;ii<field.length;ii++){
                        var value=field[ii].value;
                        if (value.length > 0) {
                        
                            if (!isAllDigits(value)) {
                                bValid = false;                                
                                j++;
                                if(j==1){
                                    focusField = field[ii];
                                }
                                
                            } else {
                                var iValue = parseInt(value);
                                if (isNaN(iValue) || !(iValue >= -2147483648 && iValue <= 2147483647)) {
                                    bValid = false;
                                    j++;
                                    if(j==1){
                                        focusField = field[ii];
                                    }
                               }
                           }
                       }
                    }  
                     if (j > 0) {
                        
                            fields[i++] = oInteger[x][1];
                            isValid = false;
                    }
                }
                    
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('"n'));
                }
                return bValid;
            }

            
]]>   </ javascript >
        
</ validator >
        
<!--
          ÅжÏÊý×éÿ¸ö²»Îª¿ÕµÄÊýÖµ¶¼±ØÐëΪ¸¡µãÐÍ
          ÕÔÆ·º£  2004
          
-->
        
< validator  name ="floatArray"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateFloatArray"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.float"  
            jsFunctionName
="FloatArrayValidations" >
            
< javascript > <![CDATA[
            function validateFloatArray(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var j=0;
                var fields = new Array();
                oFloat = new FloatArrayValidations();
                for (x in oFloat) {
                    var field = form[oFloat[x][0]];
                    for(var ii=0;ii<field.length;ii++){
                        var value=field[ii].value;
                        
                       if (value.length > 0) {
                            // remove '.' before checking digits
                            var tempArray = value.split('.');
                            var joinedString= tempArray.join('');

                            if (!isAllDigits(joinedString)) {
                                bValid = false;
                                j++;
                                if (j == 1) {
                                    focusField = field[ii];
                                }
                                
                            } else {
                                var iValue = parseFloat(value);
                                if (isNaN(iValue)) {
                                    j++;
                                    if (j == 1) {
                                        focusField = field[ii];
                                    }
                                    bValid = false;
                                }
                            }
                        }
                    }  
                     if (j > 0) {
                        
                            fields[i++] = oFloat[x][1];
                            isValid = false;
                    }
                }
                    
                if (fields.length > 0) {
                   focusField.focus();
                   alert(fields.join('"n'));
                }
                return bValid;
            }

            
]]>   </ javascript >
        
</ validator >
        
<!--
          ÅжÏÊý×éÿ¸ö²»Îª¿ÕµÄÊýÖµ¶¼±ØÐëΪ˫¾«¶ÈÐÍ
          ÕÔÆ·º£  2004
          
-->         
        
< validator  name ="doubleArray"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateDoubleArray"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.double" />
        
<!--
          ÅжÏÊý×éÿ¸ö²»Îª¿ÕµÄÊýÖµ¶¼±ØÐëΪÈÕÆÚÐÍ
          ÕÔÆ·º£  2004
          
-->             
        
< validator  name ="dateArray"  
            classname
="org.apache.struts.validator.FieldChecks"  
            method
="validateDateArray"  
            methodParams
="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
 
            depends
=""  msg ="errors.date"  jsFunctionName ="DateArrayValidations" >
            
< javascript > <![CDATA[
            function validateDateArray(form) {
                var bValid = true;
                var focusField = null;
                var i = 0;
                var j=0;
                var fields = new Array();
                oDate = new DateArrayValidations();
                for (x in oDate) {
                    var field = form[oDate[x][0]];
                    for(var ii=0;ii<field.length;ii++){
                        var value=field[ii].value;
                        var datePattern = oDate[x][2]("datePatternStrict");
                        if ((value.length > 0) &&
                           (datePattern.length > 0)) {
                          var MONTH = "MM";
                          var DAY = "dd";
                          var YEAR = "yyyy";
                          var orderMonth = datePattern.indexOf(MONTH);
                          var orderDay = datePattern.indexOf(DAY);
                          var orderYear = datePattern.indexOf(YEAR);
                          if ((orderDay < orderYear && orderDay > orderMonth)) {
                             var iDelim1 = orderMonth + MONTH.length;
                             var iDelim2 = orderDay + DAY.length;
                             var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
                             var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
                             if (iDelim1 == orderDay && iDelim2 == orderYear) {
                                dateRegexp = new RegExp("^(""d{2})(""d{2})(""d{4})$");
                             } else if (iDelim1 == orderDay) {
                                dateRegexp = new RegExp("^(""d{2})(""d{2})[" + delim2 + "](""d{4})$");
                             } else if (iDelim2 == orderYear) {
                                dateRegexp = new RegExp("^(""d{2})[" + delim1 + "](""d{2})(""d{4})$");
                             } else {
                                dateRegexp = new RegExp("^(""d{2})[" + delim1 + "](""d{2})[" + delim2 + "](""d{4})$");
                             }
                             var matched = dateRegexp.exec(value);
                             if(matched != null) {
                                if (!isValidDate(matched[2], matched[1], matched[3])) {
                                   
                                   bValid =  false;
                                   j++;
                                }
                             } else {
                                bValid =  false;
                                j++;
                             }
                           } else if ((orderMonth < orderYear && orderMonth > orderDay)) {
                             var iDelim1 = orderDay + DAY.length;
                             var iDelim2 = orderMonth + MONTH.length;
                             var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
                             var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
                             if (iDelim1 == orderMonth && iDelim2 == orderYear) {
                                 dateRegexp = new RegExp("^(""d{2})(""d{2})(""d{4})$");
                             } else if (iDelim1 == orderMonth) {
                                 dateRegexp = new RegExp("^(""d{2})(""d{2})[" + delim2 + "](""d{4})$");
                             } else if (iDelim2 == orderYear) {
                                 dateRegexp = new RegExp("^(""d{2})[" + delim1 + "](""d{2})(""d{4})$");
                             } else {
                                 dateRegexp = new RegExp("^(""d{2})[" + delim1 + "](""d{2})[" + delim2 + "](""d{4})$");
                             }
                             var matched = dateRegexp.exec(value);
                             if(matched != null) {
                                 if (!isValidDate(matched[1], matched[2], matched[3])) {
                                     j++;
                                     bValid =  false;
                                  }
                             } else {
                                 j++;
                                 bValid =  false;
                             }
                           } else if ((orderMonth > orderYear && orderMonth < orderDay)) {
                             var iDelim1 = orderYear + YEAR.length;
                             var iDelim2 = orderMonth + MONTH.length;
                             var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
                             var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
                             if (iDelim1 == orderMonth && iDelim2 == orderDay) {
                                 dateRegexp = new RegExp("^(""d{4})(""d{2})(""d{2})$");
                             } else if (iDelim1 == orderMonth) {
                                 dateRegexp = new RegExp("^(""d{4})(""d{2})[" + delim2 + "](""d{2})$");
                             } else if (iDelim2 == orderDay) {
                                 dateRegexp = new RegExp("^(""d{4})[" + delim1 + "](""d{2})(""d{2})$");
                             } else {
                                 dateRegexp = new RegExp("^(""d{4})[" + delim1 + "](""d{2})[" + delim2 + "](""d{2})$");
                             }
                             var matched = dateRegexp.exec(value);
                             if(matched != null) {
                                 if (!isValidDate(matched[3], matched[2], matched[1])) {
                                     j++;
                                     bValid =  false;
                                  }
                              } else {
                                  j++;
                                  bValid =  false;
                              }
                         } else {
                             j++;
                             bValid =  false;
                         }
                      }                      
                      }
                     if (j > 0) {
                        
                            fields[i++] = oDate[x][1];
                            isValid = false;
                     }
                }
                    
                if (fields.length > 0) {
                   alert(fields.join('"n'));
                }
                return bValid;
            }

            
]]>   </ javascript >
        
</ validator >
    
</ global >

</ form-validation >



struts+spring+hibernate的web应用<四> Web层代码编写(2)

接上一篇:struts+spring+hibernate的web应用<四> Web层代码编写(1)

接着就是写资源文件了。

com.game.resources包中添加ApplicationResourcesProducts.properties文件。如果你的eclipse中有Properties Editor这个插件,就可以用Properties Editor打开资源文件进行编写,省去了用命令行转换格式的麻烦。配置内容如下:

errors.required={0}不能为空.
errors.minlength={0}不能小于 {1} 个字符.
errors.maxlength={0}不能大于 {1} 个字符.
errors.invalid={0}输入格式不对.
errors.byte={0}必须为字节.
errors.short={0}必须为短整型.
errors.integer={0}必须为整型.
errors.long={0}必须为长整型.
errors.float={0}必须为浮点型.
errors.double={0}必须为双精度型.
errors.date={0}不是一个正确的日期或格式不对.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is not a valid credit card number.
errors.email={0}不是一个有效的email地址.

errors.gameNameCn=游戏中文名称
errors.gameNameEn=游戏英文名称
errors.gameCapacity=碟数
errors.gamePrice=价格


 

需要注意的是

这一节是不能省去的。

接下来就是写页面文件了。在products文件夹中添加如下页面。

index.jsp页面代码:

<%@ page contentType="text/html;charset=GBK" language="java" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title>游戏软件管理系统</title>
</head>
<body>

<href="/game/getProducts.do?method=doGetProducts&&flag=1">进入游戏软件管理单元</a>
</body>
</html>

products.jsp页面代码:

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" import="com.game.commons.Pager;"%>
<%@ taglib uri="struts-html" prefix="html" %>
<%@ taglib uri="struts-logic" prefix="logic" %>
<%@ taglib uri="struts-bean" prefix="bean" %>
<%
String flag=(String)request.getAttribute("flag");
String totalRows=(String)request.getAttribute("totalRows");
String fieldname="";
String value="";
if(flag.equals("2")){
    fieldname
=(String)request.getAttribute("fieldname");
    value
=(String)request.getAttribute("value");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title></title>
<script language = "JavaScript">
function btnQuery() {
    
if(myfm.value.value=="")
    
{    
        alert(
"请输入查询关键字!");
    }
else{
        window.location.href
="/game/queryProducts.do?method=doQueryProduct&&flag=2&&fieldname="+myfm.fieldname.value+"&&value="+myfm.value.value;
     }

 }

 
</script>
</head>
<body>
<form  name="myfm" method="post">
<table border="1">
<tr>
<td>
<href="/game/getProducts.do?method=doGetProducts&&flag=1">察看所有记录</a>
&nbsp;&nbsp;&nbsp;
</td>
<td>
<href="/game/addProductPage.do?method=doAddProductPage&&flag=<%= flag%>&&fieldname=<%=fieldname%>&&value=<%= value%>">添加</a>
&nbsp;&nbsp;&nbsp;
</td>
<td>
    
<select name="fieldname" >
        
<option value="gameNameCn">中文名称</option>
        
<option value="gameNameEn">英文名称</option>
        
<option value="gameCapacity">碟数</option>
        
<option value="gameVersion">版本</option>
        
<option value="gameMedia">介质</option>
        
<option value="gameCopyright">版权</option>
    
</select>
    
<input value="" name="value"  />

<href="#" onclick="btnQuery()">查询</a>
</td>
</tr>
</table>
<br>
<br>
  
<table border="1">
    
<tr>
        
<td>游戏中文名称</td>
        
<td>游戏英文名称</td>
        
<td>软件版本</td>
        
<td>软件介质</td>
        
<td>碟数</td>
        
<td>版权</td>
        
<td>价格(元)</td>
        
<td>攻略</td>
    
</tr>
    
<logic:iterate id="pd" name="productsList">
    
<tr>
        
<td><href="/game/getProduct.do?method=doGetProduct&&flag=<%=flag%>&&gameId=<bean:write name="pd" property="gameId"/>&&flag=<%= flag%>&&fieldname=<%=fieldname%>&&value=<%= value%>"><bean:write name="pd" property="gameNameCn"/></a></td>
        
<td><bean:write name="pd" property="gameNameEn"/></td>
        
<td>
            
<logic:equal name="pd" property="gameVersion" value="1">
                中文版
            
</logic:equal>
            
<logic:equal name="pd" property="gameVersion" value="2">
                英文版
            
</logic:equal>
        
</td>
        
<td>
            
<logic:equal name="pd" property="gameMedia" value="1">
                CD
            
</logic:equal>
            
<logic:equal name="pd" property="gameMedia" value="2">
                DVD5
            
</logic:equal>
            
<logic:equal name="pd" property="gameMedia" value="3">
                DVD9
            
</logic:equal>
        
</td>
        
<td><bean:write name="pd" property="gameCapacity"/></td>
        
<td>
            
<logic:equal name="pd" property="gameCopyright" value="1">
                正版
            
</logic:equal>
            
<logic:equal name="pd" property="gameCopyright" value="2">
                翻版
            
</logic:equal>
        
</td>
        
<td><bean:write name="pd" property="gamePrice"/></td>
        
<td><bean:write name="pd" property="gameContent"/></td>
    
</tr>
    
</logic:iterate>
    
<tr>
        
<%if(flag.equals("1")){%>
            
<td colspan="8" align="right" class="head">
                共有
<%=totalRows%>条记录&nbsp;&nbsp;&nbsp;&nbsp;
                第
<bean:write name="PAGER" property="currentPage"/>&nbsp;
                共
<bean:write name="PAGER" property="totalPages"/>&nbsp;
                
<html:link action="/getProducts.do?method=doGetProducts&&flag=1&&pagerMethod=first" paramName="PAGER" paramProperty="currentPage" paramId="currentPage">首页</html:link>
                
<html:link action="/getProducts.do?method=doGetProducts&&flag=1&&pagerMethod=previous" paramName="PAGER" paramProperty="currentPage" paramId="currentPage">上一页</html:link>
                
<html:link action="/getProducts.do?method=doGetProducts&&flag=1&&pagerMethod=next" paramName="PAGER" paramProperty="currentPage" paramId="currentPage">下一页</html:link>
                
<html:link action="/getProducts.do?method=doGetProducts&&flag=1&&pagerMethod=last" paramName="PAGER" paramProperty="currentPage" paramId="currentPage">尾页</html:link>
            
</td>    
        
<%}else if(flag.equals("2")){%>
        
<% Pager pager=(Pager)request.getAttribute("PAGER");%>
            
<td colspan="8" align="right" class="head">
                共有
<%=totalRows%>条记录&nbsp;&nbsp;&nbsp;&nbsp;
                第
<bean:write name="PAGER" property="currentPage"/>&nbsp;
                共
<bean:write name="PAGER" property="totalPages"/>&nbsp;
                
<href="/game/queryProducts.do?method=doQueryProduct&&flag=2&&fieldname=<%=fieldname%>&&value=<%= value%>&&pagerMethod=first&&currentPage=<%=pager.getCurrentPage()%>" >首页</a>
                
<href="/game/queryProducts.do?method=doQueryProduct&&flag=2&&fieldname=<%=fieldname%>&&value=<%= value%>&&pagerMethod=previous&&currentPage=<%=pager.getCurrentPage()%>" >上一页</a>
                
<href="/game/queryProducts.do?method=doQueryProduct&&flag=2&&fieldname=<%=fieldname%>&&value=<%= value%>&&pagerMethod=next&&currentPage=<%=pager.getCurrentPage()%>" >下一页</a>
                
<href="/game/queryProducts.do?method=doQueryProduct&&flag=2&&fieldname=<%=fieldname%>&&value=<%= value%>&&pagerMethod=last&&currentPage=<%=pager.getCurrentPage()%>" >尾页</a>
                
            
</td>    
        
<%}%>
    
</tr>
</table>
</form>
</body>
</html>



addproduct.jsp页面代码:

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<%@ taglib uri="struts-html" prefix="html" %>
<%@ taglib uri="struts-logic" prefix="logic" %>
<%@ taglib uri="struts-bean" prefix="bean" %>
<%
String flag=(String)request.getAttribute("flag");
String fieldname="";
String value="";
if(flag.equals("2")){
    fieldname
=(String)request.getAttribute("fieldname");
    value
=(String)request.getAttribute("value");
}
String maxid=(String)request.getAttribute("maxid");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title></title>
<html:base/>
<html:javascript formName="productsForm" method="validate"/>
<script Language="JavaScript">
       
function btn_AddFolder() {
           
if(confirm("确定要保存吗?")){
            
if(document.productsForm.onsubmit()){        
                document.forms[
0].submit();
            }

        }
  
    }

</script>
</head>
<body>

<href="/game/returnProduct.do?method=doReturnProduct&&flag=<%= flag%>&&fieldname=<%=fieldname%>&&value=<%= value%>">返回</a>
<html:form action="/addProduct.do" onsubmit="return validate(this)">
<table border="1">
    
<tr>
        
<td>游戏中文名称</td>
        
<td>游戏英文名称</td>
        
<td>软件版本</td>
        
<td>软件介质</td>
        
<td>碟数</td>
        
<td>版权</td>
        
<td>价格(元)</td>
        
<td>攻略</td>
    
</tr>
    
<tr>
        
<td><html:text property="gameNameCn"/></td>
        
<td><html:text property="gameNameEn"/></td>
        
<td>
            
<html:select property="gameVersion" >
                  
<html:option value= "2">英文版&nbsp;&nbsp;&nbsp;&nbsp;</html:option>
                  
<html:option value= "1">中文版</html:option>
              
</html:select>   
        
</td>
        
<td>
            
<html:select property="gameMedia" >
                  
<html:option value= "1">CD&nbsp;&nbsp;&nbsp;&nbsp;</html:option>
                  
<html:option value= "2">DVD5</html:option>
                  
<html:option value= "3">DVD9</html:option>
              
</html:select>   
        
</td>
        
<td><html:text property="gameCapacity" size="5"/></td>
        
<td>
            
<html:select property="gameCopyright" >
                  
<html:option value= "2">翻版&nbsp;&nbsp;&nbsp;&nbsp;</html:option>
                  
<html:option value= "1">正版</html:option>
              
</html:select>  
        
</td>
        
<td><html:text property="gamePrice"/></td>
        
<td><html:text property="gameContent"/></td>
    
</tr>
    
</table>
<html:hidden property="gameId" value="<%= maxid%>"/>
<html:hidden property="method" value="doAddProduct"/>
<html:hidden property="flag" value="<%= flag%>"/>
<html:hidden property="fieldname" value="<%= fieldname%>"/>
<html:hidden property="value" value="<%=value%>"/>
<input type="button" value="保存" onclick="btn_AddFolder()"/>

</html:form>
</body>
</html>


product.jsp页面代码:

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<%@ taglib uri="struts-html" prefix="html" %>
<%@ taglib uri="struts-logic" prefix="logic" %>
<%@ taglib uri="struts-bean" prefix="bean" %>
<%
String flag=(String)request.getAttribute("flag");
String fieldname="";
String value="";
if(flag.equals("2")){
    fieldname
=(String)request.getAttribute("fieldname");
    value
=(String)request.getAttribute("value");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title></title>
<html:javascript formName="productsForm" method="validate"/>
</head>
<body>
<href="/game/addProductPage.do?method=doAddProductPage&&flag=<%= flag%>&&fieldname=<%=fieldname%>&&value=<%= value%>">添加</a> &nbsp;&nbsp;&nbsp;
<href="/game/returnProduct.do?method=doReturnProduct&&flag=<%= flag%>&&fieldname=<%=fieldname%>&&value=<%= value%>">返回</a>&nbsp;&nbsp;&nbsp;
<href="/game/deleteProduct.do?method=doDeleteProduct&&flag=<%= flag%>&&gameId=<bean:write name="pd" property="gameId"/>&&fieldname=<%=fieldname%>&&value=<%= value%>">删除</a>
<br>
<br>
<html:form action="/updateProduct.do" onsubmit="return validate(this)">
<table border="1">
    
<tr>
        
<td>游戏中文名称</td>
        
<td>游戏英文名称</td>
        
<td>软件版本</td>
        
<td>软件介质</td>
        
<td>碟数</td>
        
<td>版权</td>
        
<td>价格(元)</td>
        
<td>攻略</td>
    
</tr>
    
<tr>
        
<td><html:text name="pd" property="gameNameCn"/></td>
        
<td><html:text name="pd" property="gameNameEn"/></td>
        
<td>
            
<html:select name="pd" property="gameVersion" >
                  
<html:option value= "1">中文版&nbsp;&nbsp;&nbsp;&nbsp;</html:option>
                  
<html:option value= "2">英文版</html:option>
              
</html:select> 
        
</td>
        
<td>
            
<html:select name="pd" property="gameMedia" >
                  
<html:option value= "1">CD&nbsp;&nbsp;&nbsp;&nbsp;</html:option>
                  
<html:option value= "2">DVD5</html:option>
                  
<html:option value= "3">DVD9</html:option>
              
</html:select>  
        
</td>
        
<td><html:text name="pd" property="gameCapacity" size="5"/></td>
        
<td>
            
<html:select name="pd" property="gameCopyright" >
                  
<html:option value= "1">正版&nbsp;&nbsp;&nbsp;&nbsp;</html:option>
                  
<html:option value= "2">翻版</html:option>
              
</html:select>  
        
</td>
        
<td><html:text name="pd" property="gamePrice" size="10"/></td>
        
<td><html:text name="pd" property="gameContent"/></td>
    
</tr>
    
</table>
<html:hidden property="method" value="doUpdateProduct"/>
<html:hidden name="pd" property="gameId" />
<html:hidden property="flag" value="<%= flag%>"/>
<html:hidden property="fieldname" value="<%= fieldname%>"/>
<html:hidden property="value" value="<%=value%>"/>
<html:submit property="submit" value="保存"></html:submit>
</html:form>
</body>
</html>


product_success.jsp页面代码:

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<%
String flag=(String)request.getAttribute("flag");
String fieldname="";
String value="";
if(flag.equals("2")){
    fieldname
=(String)request.getAttribute("fieldname");
    value
=(String)request.getAttribute("value");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title></title>
</head>
<body>
操作成功!

<href="/game/returnProduct.do?method=doReturnProduct&&flag=<%= flag%>&&fieldname=<%=fieldname%>&&value=<%= value%>">返回</a>
<href="/game/addProductPage.do?method=doAddProductPage&&flag=<%= flag%>&&fieldname=<%=fieldname%>&&value=<%= value%>">继续添加</a>
</body>
</html>

product_failure.jsp页面代码:

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<%
String flag=(String)request.getAttribute("flag");
String fieldname="";
String value="";
if(flag.equals("2")){
    fieldname
=(String)request.getAttribute("fieldname");
    value
=(String)request.getAttribute("value");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title></title>
</head>
<body>
操作失败!
<href="/game/returnProduct.do?method=doReturnProduct&&flag=<%= flag%>&&fieldname=<%=fieldname%>&&value=<%= value%>">返回</a>
</body>
</html>

最后在tld文件夹中添加下列tld文件。

至此,整个项目基本编写完了,运行tomcat,看看我们的项目的效果吧!

在地址栏输入http://localhost:8088/game/products/index.jsp

然后点击“进入游戏软件管理单元”链接,主界面出现了。

ssh5.jpg

posted on 2008-03-01 21:39 鸿雁 阅读(824) 评论(0)  编辑  收藏 所属分类: IT技术相关


只有注册用户登录后才能发表评论。


网站导航: