使用strut2框架对数据进行验证

以登录为例介绍

1
先创建bean对象
2
创建对应的action
3
action的同级目录下创建验证的配置文件
.
4
创建jsp文件


备注:当一个Action中有多个业务方法时 : Action -映射名-validation.xml

如以EmployeeAction的添加方法为例。

添加员工信息的映射名。

<action name="addEmployee" class="EmployeeAction"

           method="addEmployee">

           <result name="success">

              /sm/employee/employeeSuccess.jsp

           </result>

           <result name="input">

              /sm/employee/addEmployee.jsp

           </result>

</action>

Xml验证文件的命名:EmployeeAction-addEmployee-validation.xml



具体实现:
package com.exeerp.sm.bean;

import java.io.Serializable;
import java.sql.Date;
import java.util.List;



/**
*
雇员bean

*/
public class Employee implements Serializable{

    /**
*
登陆用户名

*/
    private String userID;

    /**
*
登陆密码
*/
    private String pwd;

public String getUserID() {
return userID;
}

public void setUserID(String userID) {
this.userID = userID;
}

public String getPwd() {
return pwd;
}

public void setPwd(String pwd) {
this.pwd = pwd;
}
}
2.
对应的action  EmployeeAction.java
package com.exeerp.sm.ctrl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.exeerp.pub.action.BaseAction;
import com.exeerp.pub.exception.BizException;
import com.exeerp.pub.exception.DaoException;
import com.exeerp.pub.util.ExceptionMessage;
import com.exeerp.pub.util.Paginated;
import com.exeerp.sm.bean.Department;
import com.exeerp.sm.bean.Employee;
import com.exeerp.sm.biz.EmployeeManager;
import com.opensymphony.xwork2.ActionContext;

public class EmployeeAction extends BaseAction
{
static Logger logger = Logger.getLogger(EmployeeAction.class);
//
业务层EmployeeManager对象

private EmployeeManager employeeManager;
private Employee employee;

private Department department;
//
设置当前页
private int currentPage=1;

//
分页对象
private Paginated paging;
    /**
*
实现登陆
* @return
*/
public String loginAction(){
  try {
if(employeeManager.login(employee))    //
判断是否登录成功
{
Map map = ServletActionContext.getContext().getSession();  //
定义会话
// Map map = new HashMap();
map.put("UserID", employee.getUserID());        //
将对象放入会话中
System.out.println("dd="+map.get("UserID").toString());
ServletActionContext.getRequest().setAttribute("UserID",employee.getUserID());  //
将对象放入request
return SUCCESS;
}else{
return INPUT;
}
} catch (DaoException e) {
logger.error(e.getMessage());
this.setMessage(e.getMessage());
return INPUT;
} catch(Exception e){
logger.error(e.getMessage());
e.printStackTrace();
this.setMessage(e.getMessage());
return INPUT;
}
}
}
创建的验证文件 EmployeeAction-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<!--
验证用户登录
-->
<validators>
    <field name="employee.userID"><!--
此处的值与页面的name值要对应
-->
     
        <field-validator type="requiredstring">
        <param name="trim">true</param>
          <message>
用户名不能为空
</message>
        </field-validator>
        <field-validator type="requiredstring">
        <param name="trim">true</param>
          <message>
用户名不能为空
</message>
        </field-validator>
    </field>
    <field name="employee.pwd">
        <field-validator type="requiredstring">
            <message>
密码不能为空
</message>
        </field-validator>
      <field-validator type="regex"><!--
使用正则表达式进行验证
-->
<param name="expression">\w{4,10}</param>
<message>
密码输入不合法</message>[微软用户1] 

</field-validator>
    </field>

 

<field name="repassword">
     <field-validator type="requiredstring">
       <param name="trim"></param>
       <message>
重复密码不能为空!
</message>
     </field-validator>
     <field-validator type="stringlength">
       <param name="minLength">6</param>
       <param name="maxLength">10</param>
       <message>
重复密码应在${minLength}${maxLength}之间
</message>
     </field-validator>
   </field>
  
   <field name="age">
     <field-validator type="int">
       <param name="min">1</param>
       <param name="max">150</param>
       <message>
年龄应该在${min}${max}之间
</message>
     </field-validator>
   </field>
  
   <field name="birthday">
     <field-validator type="date">
       <param name="min">2000-10-01</param>
       <param name="max">2008-10-01</param>
       <message>
生日应该在${min}${max}之间
</message>
     </field-validator>
   </field>
  
   <field name="graduation">
     <field-validator type="date">
       <param name="min">2008-01-01</param>
       <param name="max">2018-01-01</param>
       <message>
毕业时间应该在${min}${max}之间
</message>
     </field-validator>
   </field> 

</validators>
Jsp
页面:
Login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<META [email protected] name=reply-to>
<META content=http://sg803.savalo.com / name=Identifier-URL>
<title>
登陆界面
</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<style>
body {
font-size: 12px;
}

td {
font-size: 12px;
}

.input {
height: 15px;
width: 104px;
border: none;
font-size: 12px;
color: #603900;
}

.menu:link {
color: #990000;
text-decoration: none;
}

.menu:visited {
color: #990000;
text-decoration: none;
}

.menu:hover {
color: #ff0000;
text-decoration: none;
position: relative;
top: 1px;
}

.menu:active {
color: #990000;
text-decoration: none;
position: relative;
top: 1px;
}

.loginButton {
width: 57px;
height: 18px;
border: 0px;
}
</style>

</head>
<h1><font color="red">SSSSSSSSSSS:<s:fielderror/></font></h1
[微软用户2] 
>
<body bgcolor="#000000" leftmargin="0" topmargin="0" marginwidth="0"
marginheight="0">

<s:form action="loginAction" onsubmit="return validation()">
<table width="100%" height="100%" border="0" align="center"
cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table width="797" height="457" border="0" align="center"
cellpadding="0" cellspacing="0" id="__01">
<tr>
<td colspan="8">
<img src="images/images/index_01.jpg" width="797" height="154"
alt="">
</td>
</tr>
<tr>
<td height="29" colspan="8"
background="images/images/index_02.jpg">
<table width="96%" border="0" align="center" cellpadding="0"
cellspacing="0">
<tr>
<td width="230" height="22" align="center" valign="bottom">
<script>
today=new Date();
var day;
var date;
var hello;
hour=today.getHours()
if(hour < 6)hello='
凌晨好! '
else if(hour < 9)hello='
早上好
! '
else if(hour < 12)hello='
上午好
! '
else if(hour < 14)hello='
中午好
! '
else if(hour < 17)hello='
下午好
! '
else if(hour < 19)hello='
傍晚好
! '
else if(hour < 22)hello='
晚上好
! '
else {hello='
半夜好
! '}
day=today.getDay()
if(day==0)day=' 
星期日
'
else if(day==1)day=' 
星期一
'
else if(day==2)day=' 
星期二
'
else if(day==3)day=' 
星期三
'
else if(day==4)day=' 
星期四
'
else if(day==5)day=' 
星期五
'
else if(day==6)day=' 
星期六
'
date=(today.getYear())+'
'+(today.getMonth()+1)+''+today.getDate()+'
';
document.write("<strong><font color=#ff6600>" +hello+"</font></strong>");
document.write('
今天是
 ')
document.write(date);
document.write(day);
</script>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td rowspan="7">
<img src="images/images/index_03.jpg" width="466" height="274"
alt="">
</td>
<td colspan="3" rowspan="5">
<img src="images/images/index_04.jpg" width="125" height="151" alt="">
</td>
<td colspan="4">
<img src="images/images/index_05.jpg" width="206" height="72"
alt="">
</td>
</tr>
<tr>
<td height="17" colspan="3"
background="images/images/index_06.jpg">
<input name="employee.userID" id="UserID" type="text"
class="input" value="
请输入用户名
">
</td>
<td rowspan="5">
<img src="images/images/index_07.jpg" width="101" height="97"
alt="">
</td>
</tr>
<tr>
<td colspan="3">
<img src="images/images/index_08.jpg" width="105" height="22"
alt="">
</td>
</tr>
<tr>
<td height="17" colspan="3"
background="images/images/index_09.jpg">
<input name="employee.pwd" id="Pwd" type="password"
class="input">
</td>
</tr>
<tr>
<td colspan="3">
<img src="images/images/index_10.jpg" width="105" height="23"
alt="">
</td>
</tr>
<tr>
<td>
<img src="images/images/index_11.jpg" width="65" height="18"
alt="">
</td>
<td background="images/images/index_12.jpg">
<input type="submit" name="" class="loginButton"
style="FILTER: alpha(opacity = 0)" />
</td>
<td colspan="2">
<img src="images/images/index_13.jpg" width="23" height="18"
alt="">
</td>
<td background="images/images/index_14.jpg">
<input type="button" name="" class="loginButton"
style="FILTER: alpha(opacity = 0)" onclick="clear()" />
</td>
<td>
<img src="images/images/index_15.jpg" width="28" height="18"
alt="">
</td>
</tr>
<tr>
<td colspan="7">
<img src="images/images/index_16.jpg" width="331" height="105"
alt="">
</td>
</tr>
<tr>
<td>
<img src="images/images/??????
分隔符
?.gif" width="466" height="1"
alt="">
</td>
<td>
<img src="images/images/??????
分隔符
?.gif" width="65" height="1"
alt="">
</td>
<td>
<img src="images/images/??????
分隔符
.gif" width="57" height="1"
alt="">
</td>
<td>
<img src="images/images/??????
分隔符
?.gif" width="3" height="1"
alt="">
</td>
<td>
<img src="images/images/??????
分隔符
.gif" width="20" height="1"
alt="">
</td>
<td>
<img src="images/images/??????
分隔符
?.gif" width="57" height="1"
alt="">
</td>
<td>
<img src="images/images/??????
分隔符
?.gif" width="28" height="1"
alt="">
</td>
<td>
<img src="images/images/??????
分隔符
.gif" width="101" height="1"
alt="">
</td>
</tr>
</table>
</td>
</tr>
</table>
</s:form>
</body>
</html>
<script>
    function addListener(element,e,fn)
    {   
    if(element.addEventListener){   
          element.addEventListener(e,fn,false);   
    } else {   
        element.attachEvent("on" + e,fn);   
    }   
}
var UserID = document.getElementById("UserID");
var Pwd = document.getElementById("Pwd");
addListener(UserID,"click",function(){
UserID.value = "";
})
        addListener(Pwd,"click",function(){
Pwd.value = "";
})
     
     
    function validation(){
        var userName = document.getElementById("UserID").value;
        var userPassword = document.getElementById("Pwd").value;
        var Name = userName.split("
请输入用户名
"); 
        var Password = userPassword.split("
请输入密码
");
        if(userName.length==0||Name[0]==""){
            alert('
用户名不能为空
');
            return false;
        }
        if(userPassword.length==0||Password.length>1){
            alert('
密码不能为空
');
            return false;
        }
      }
     
      function clear(){
            alert('dsd');
            var UserID = document.getElementById("UserID");
var Pwd = document.getElementById("Pwd");
UserID.value = "";
Pwd.value="";
      }
  </script>

 

 

 

 


 [微软用户1]正则表达式验证

 [微软用户2]显示错误信息

你可能感兴趣的:(框架,bean,jsp,xml,正则表达式)