- 浏览: 304686 次
文章分类
最新评论
-
流年末年:
那四个参数还是没看懂.....能不能解释下showPassst ...
我写的密码强度验证方法(原创) -
kingcs2008:
// 验证pws.jsshowPassstrength(&qu ...
我写的密码强度验证方法(原创) -
h957355152:
请问博主这个怎么用呢?我直接放到jsp里面调用showPass ...
我写的密码强度验证方法(原创) -
qq_15138059:
我写的全国省市县三级联动菜单,拿出来和大家分享了(原创) -
valenon:
评论呢?从MAIL FROM命令开始貌似就出错了:500 Er ...
如何发送伪造的电子邮件
前面的文章:
struts+spring+hibernate 的 web 应用 < 一 > 架构搭建
struts+spring+hibernate 的 web 应用 < 二 > Dao 层代码编写
struts+spring+hibernate 的 web 应用 < 三 > Service 层代码编写
Web
层代码量比较大,涉及的地方也比较多,考虑到文章过于庞大,所以分两篇写。
我们还是先从主要的
action
开始吧。
在
com.game.products.web.actions
包中新建
ProductsAction
,这是一个
DispatchAction
,代码如下:
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 。代码如下:
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
。代码如下:
<! 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
,接着添加如下代码:
< 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
,代码如下:
<! 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
类来过滤编码,类的代码如下:
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.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 。在这配置验证规则:
"-//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
过来就可以用了。为了方便大家,我这里将里面配置代码粘贴出来:
<! 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 >
发表评论
-
java正则表达式高级用法:转换驼峰标示
2012-06-26 16:47 5803String source = "LastLog ... -
你会做Web上的用户登录功能吗?(转)
2012-06-25 13:22 1374Web上的用户登录功能应 ... -
使用pager-taglib.jar实现的分页技术
2012-06-24 02:34 934//1.导入pager-taglib.jar包; / ... -
我写的验证码生成方案,可防止绝大多数机械识别。
2012-06-20 14:59 2408web.xml <!DOCTYPE web-app ... -
如何在myeclipse中使用maven?
2012-06-11 14:22 168431.下载maven,解压到D盘ma ... -
安装subclipse, MyEclipse8 SVN插件
2012-06-09 22:39 962安装subclipse, MyEclipse8 SVN插件 ... -
PDF生成器
2012-05-28 02:53 851我自己写的一个pdf生成器,能导出百度博客为PDF -
我的自动投票器
2012-04-17 13:58 1301自动投票器,支持windows的32位机器 下面的压缩包是编 ... -
list,set,map,数组间的相互转换(转载)
2012-03-16 16:29 28621.list转set Java代码 ... -
一个给pojo生成hashcode、equals、toString等方法的工具类
2012-03-06 09:52 4256一个给pojo生成hashcode、equals、toStri ... -
ehcache的用法
2012-02-13 22:13 0Spring ... -
使用ehcache来缓存页面
2012-02-13 22:08 811关于缓存的话题,在坛子里已经有很多讨论,简单的来说,如果一个应 ... -
java笔记:自己动手写javaEE框架(二)--业务层Service以及Service单元测试
2012-02-13 00:55 0前一篇博文里有三 ... -
struts+spring+hibernate的web应用<四> Web层代码编写(2)
2012-02-13 00:50 0接着就是写资源文件了。 在 com.game. ... -
struts+spring+hibernate的web应用<三> Service层代码编写
2012-02-13 00:46 868前面的文章: ... -
struts+spring+hibernate的web应用<二> Dao层代码编写
2012-02-13 00:45 864前一篇文章 (struts+spring ... -
struts+spring+hibernate的web应用<一> 架构搭建
2012-02-13 00:44 779许久没有些文章了,现 ... -
ehcache缓存管理
2012-02-12 23:52 1004EHCache 是一个纯java的,在Hibernate2 ... -
检测一个字符串是否在jvm的常量池中(原创)
2012-01-11 09:07 2160检测一个字符串是否在jvm的常量池中 public ... -
我写的密码强度验证方法(原创)
2011-12-18 15:26 8389/* *说明: * 该方法主要分析密码的内容构成 ...
相关推荐
### Java8 + Tomcat8 + Struts2.5 + Spring4.3 + Hibernate5.2 框架搭建详细过程 #### 一、环境配置与准备 在搭建一个基于Java8 + Tomcat8 + Struts2.5 + Spring4.3 + Hibernate5.2 的项目前,首先需要对开发环境...
在IT行业中,SSH(Struts + Spring + Hibernate)是一个经典的Java Web开发框架组合,用于构建高效、可扩展的Web应用程序。本项目通过SSH框架实现了图书管理系统的图书修改和删除功能,下面将详细介绍这三个核心组件...
SSH(Struts2、Spring、Hibernate)是一个常见的Java开发框架组合,用于构建基于Maven的Web应用程序。Maven是一个项目管理工具,它可以帮助开发者管理和构建项目,而SSH框架则提供了模型-视图-控制器(MVC)架构的...
在项目源代码目录中创建四个包:`po`(持久化对象)、`dao`(数据访问对象)、`service`(业务逻辑层)以及`action`(Struts的Action)。 #### 三、模型层开发 ##### 1. 构建实体类 在`po`包中创建`User`类: ```...
12.6.16 编写Spring和Hibernate的配置文件spring-config.xml 12.6.17 编写web.xml 12.6.18 验证示例 12.7 小结 第四篇 J2EE项目案例精选 第十三章 网上调查系统 13.1 系统概述 13.2 需求分析 13.2.1 系统用例图 ...
Struts2、Spring4和Hibernate是Java开发中的三大框架,它们在构建企业级Web应用程序时起着核心作用。本教程将深入探讨这三个框架如何协同工作,以实现高效、灵活和可扩展的电子商务平台。 首先,Struts2是一个基于...
Struts、Spring、Hibernate以及MySQL是Java开发领域中非常经典的四大框架组合,它们共同构建了一个强大的Web应用程序架构。Struts提供了MVC(Model-View-Controller)设计模式的支持,Spring作为一个全面的轻量级...
Struts2、Spring4和Hibernate4是Java Web开发中的三大主流框架,它们分别负责MVC模式中的表现层、业务层和服务层。这个最新的项目系统整合了这三个框架,旨在提供一个高效、灵活且易于维护的开发环境。下面将详细...
SSH(Struts+Spring+Hibernate)是Java Web开发中一种常见的技术栈,它将MVC设计模式、依赖注入和持久层框架集成为一个整体,大大提高了开发效率和代码的可维护性。下面我们将深入探讨SSH框架的各个组成部分及其结合...
Struts2+Spring+Hibernate和Struts2+Spring+Ibatis是两种常见的Java Web应用程序集成框架,它们分别基于ORM框架Hibernate和轻量级数据访问框架Ibatis。这两种框架结合Spring,旨在提供一个强大的、可扩展的、易于...
Struts、Spring 和 Hibernate 是Java开发中非常著名的三个开源框架,它们组合在一起形成的SSH(Struts、Spring、Hibernate)框架,是企业级Web应用开发的常用解决方案。SSH框架的整合可以实现模型-视图-控制器(MVC...
Struts1、Spring2和Hibernate2是Java Web开发中的三个重要框架,它们分别负责MVC模式中的表现层、业务层和服务层。这个整合例子旨在展示如何将这三个框架协同工作,以构建一个完整的Java Web应用程序。 Struts1是...
这本“java web 实战宝典_JSP+Servlet+Struts_2+Hibernate+Spring+Ajax”涵盖了JSP和Servlet作为Web基础技术的知识,以及Struts 2、Spring、Hibernate三个主流的SSH框架,并且提供了Ajax技术的应用介绍。这是一本...
Struts、Spring 和 Hibernate 是Java Web开发中的三大框架,它们结合使用可以构建高效、模块化的应用程序,特别是对于处理用户登录和文件上传等常见功能。在这个项目中,"struts+spring+hibernate(mysql)用户登录及...
Struts、Spring、Hibernate和Ajax是Java Web开发中的四大核心技术,它们共同构建了一个高效、灵活的Web应用程序架构。在这个"Struts+Spring+Hibernate+Ajax的Demo"中,开发者使用了这些技术来创建一个功能丰富的示例...
本资料集合了"零基础学Java_Web开发:JSP+Servlet+Struts+Spring+Hibernate+Ajax",涵盖了从初级到进阶的重要概念,帮助初学者系统地掌握Web开发技能。 1. **JSP(JavaServer Pages)技术**: JSP是Java平台上的...
Struts2.1、Spring2.5和Hibernate3.3是经典的Java企业级开发框架组合,它们各自在应用程序的不同层面提供了强大的支持。本篇将详细阐述这三个组件的整合过程,以及各自的核心特性。 首先,Struts2是一个基于MVC设计...