Struts2中ajax结合action实现表单时时验证

在struts2中实现表单的时时验证 

<1>编写action UserAction:

package com.dreamers.login;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.dreamers.db.SeleceTable;
import com.dreamers.xml.GetPath;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport implements ServletRequestAware ,ServletResponseAware{
    /**
     * 
     */
 private static int p = 0;
    private static final long serialVersionUID = 1L;
    private HttpServletRequest request;
    private HttpServletResponse response;
    
    private SeleceTable dao = new SeleceTable();
    public void setServletRequest(HttpServletRequest request) {
        this.request =request;
    }
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }
public ArrayList<String> readIPXml(){
  GetPath path = new GetPath();
  String dir = path.getIPPath();
  ArrayList<String> list = new ArrayList<String>();
  try{
   
   InputStream fis = new FileInputStream(dir);
   BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
   String line = null;// 用来保存每行读取的内容
   line = reader.readLine(); // 读取第一行
   while (line != null) { // 如果 line 为空说明读完了
   list.add(line);
   line = reader.readLine(); // 读取下一行
      }
   fis.close();
  }catch(IOException e){
   System.out.println("读取ip列表错误");
  }
  return list;
 }
 
 public String findIP(String user_name){
   int ipnum = 0;
   p = 0;
   ArrayList<String>ipList = new ArrayList<String>(); 
   ipList=this.readIPXml();
   for(int i = 0; i < ipList.size(); i++){
    if(ipList.get(i).equals(null)||ipList.get(i)==null||ipList.get(i).equals("null")||ipList.get(i).equals(""))
     ipList.remove(i);
   }
   System.out.println("6");
   SeleceTable select = new SeleceTable();
   for(int i = 0; i < ipList.size(); i++){
    try{
     System.out.println(user_name+"连接"+ipList.get(i));
     select.select(user_name, ipList.get(i));
     ipnum = i;
     break;
    }catch(Exception e){
     p = p + 1;
     System.out.println("ppppp====="+p);
    }
    }
   System.out.println("7");
   if(p == ipList.size())
    return null;
   
   System.out.println("ipnum"+ipnum);
   String ipp = this.readIPXml().get(ipnum);
   return ipp;
   }
    public Boolean searchdb(String name){
     try{
      String ipnum= this.findIP(name);
      System.out.println("name"+name+"lainjie "+ipnum);
     ArrayList<ArrayList<String>> searchdb =dao.select(name, ipnum);
     ArrayList<String> usernamelist =searchdb.get(1);
     for(int i=0;i < usernamelist.size();i++){
       System.out.println(usernamelist.get(i));
     }
     return  usernamelist.contains(name);
     }catch(IndexOutOfBoundsException e){
      return false;
     }
    }
    public String execute() throws Exception {
        String name = request.getParameter("name");
        String value = request.getParameter("value");
        //System.out.println("name="+name);
        //System.out.println("value="+value);
        String info = null;
        response.setContentType("text/html;charset=GBK");
        if("code".equals(name)){
            String sessionCode = (String)request.getSession().getAttribute("_CODE_");
    //        System.out.println(sessionCode);
            if(value!=null && value.equals(sessionCode)){
                response.getWriter().println("1验证码正确");
            }else{
                response.getWriter().println("0验证码错误");
            }
        }else{
            if("username".equals(name)){
                info="用户名";
            }else if("email".equals(name)){
                info="邮件地址";
            }
        //    System.out.println(dao.querySameValue(name, value));
            if(searchdb(value)){
                response.getWriter().println("0该"+info+"已存在,请更换"+info+".");
            }else{
                response.getWriter().println("1该"+info+"可以正常使用");
            }
        }
        return null;
    }
    
}


<2>在Struts.xml中配置

<action name="check" class="com.dreamers.login.UserAction">
 
 </action>


<3>编写界面regin.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>register.jsp</title>
    <style type="text/css">
        body,td,input{
        font-family: Arial;
        font-size: 12px; 
        }
        table.default{
        border-collapse:collapse;
        width: 300px; 
        }
        table.default,td{
        border: 1px solid black;
        padding:3px;
        }
        table.default td.item{
        background: #006699;
        color: #fff;
        }
        div.ok{
            color: #006600;
        }
        div.warning{
            color: #FF0000;
        }
    </style>
    <script type="text/javascript" src="checker.js"></script>
  </head>
  
  <body>
    <h1>欢迎用户注册!</h1>
    <form action="regin.action">
        <table class="default">
        <tr>
            <td class="item" width="30%">用户名:</td>
            <td width="70%">
                <input type="text" name="username" id="username" οnblur="Checker.checkNode(this)">
                <div id="usernameCheckDiv" class="warning">请输入用户名</div>
            </td>
        </tr>
        <tr>
            <td class="item">密码:</td>
            <td>
            <input type="password" name="password" id="password" οnblur="Checker.checkPassword()">
            <div id="passwordCheckDiv" class="warning">请输入密码</div>
            <td>
        </tr>
        <tr>
            <td class="item">密码验证:</td>
            <td>
                <input type="password" name="password2" id="password2" οnblur="Checker.checkPassword()">
                <div id="password2CheckDiv" class="warning">请再次输入密码</div>
            </td>
        </tr>
        <tr>
            <td class="item">E-mail:</td>
            <td>
                <input type="text" name="email" id="email" οnblur="Checker.checkNode(this)" >
                <div id="emailCheckDiv" class="warning">请输入邮件地址</div>
            </td>
        </tr>
        <tr>
            <td class="item">验证码:</td>
            <td>
                <input type="text" name="code" id="code" size="5" οnblur="Checker.checkNode(this)">
                <img src="code.jsp" width="40" height="20" border="0" alt="">
                <div id="codeCheckDiv" class="warning">请输入图片中的验证码</div>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="submit" value="注册">
                <input type="reset" value="重置">
            </td>
        </tr>
        </table>
    </form>
  </body>
</html>


<4>code.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page contentType="image/png" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>生成验证码</title>
    
  </head>
  
  <body>
   <% 
           //设置页面不缓存 
    response.setHeader("Pragma","No-cache"); 
    response.setHeader("Cache-Control","no-cache"); 
    response.setDateHeader("Expires", 0);  int width=50;          //设置图片宽度 
    int height=20;          // 设置图片高度 
     //创建缓存图像 
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
     
    Graphics g = image.getGraphics();      // 获取图形 
     
    g.setColor(new Color(000, 102, 153));     // 设置背景色 
    g.fillRect(0, 0, width, height);       // 填充背景 
     
    g.setColor(new Color(000, 000, 000));     // 设置边框颜色 
    g.drawRect(0, 0, width-1, height-1);      // 绘制边框 
     
    g.setFont(new Font("Arial", Font.PLAIN, 16));    //设定字体 
     
    Random random = new Random();      // 生成随机类 
     //随机产生4 位数字验证码 
    StringBuffer sbRan = new StringBuffer();     //保存验证码文本 
    for (int i=0; i<4; i++){ 
        String ranNum = String.valueOf(random.nextInt(10)); 
        sbRan.append(ranNum); 
        //将验证码绘制到图像中 
        g.setColor(new  Color(255, 255, 255)); 
        g.drawString(ranNum, 10 * i + 5, 16); 
    } 
     g.dispose();          //部署图像 
     
    session.setAttribute("_CODE_", sbRan.toString());   // 将验证码保存在session 对象中供对比 
    ImageIO.write(image, "PNG", response.getOutputStream());  //输出图像到页面 
       out.clear();
    out = pageContext.pushBody(); 
   %>
  </body>
</html>


<5>编写的js文件 Checker .js

var Checker = new function(){
    this._url="check.action";
    this._infoDivSuffix= "CheckDiv" ;//提示信息Div的同意后缀
    this.checkNode = function(_node){
        var nodeId = _node.id;
        if(_node.value!=""){
            var xmlHttp=this.createXmlHttp();
            xmlHttp.onreadystatechange = function(){
                if(xmlHttp.readyState==4){
                    Checker.showInfo(nodeId+Checker._infoDivSuffix,xmlHttp.responseText);
                }
            }
            xmlHttp.open("POST",this._url,true);
            xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            //alert(_node.id);
            //alert(_node.value);
            xmlHttp.send("name="+nodeId+"&value="+(_node.value));
        }
    }
    //显示服务器反馈信息 
    this.showInfo = function(_infoDivId , text){ 
        var infoDiv = document.getElementById(_infoDivId); //获取显示信息的div 
        var status = text.substr(0,1);     //反馈信息的第一个字符表示信息类型 
        if (status == "1") { 
            infoDiv.className = "ok";     //检查结果正常 
        } else { 
            infoDiv.className = "warning";    //检查结果需要用户修改 
        } 
        infoDiv.innerHTML = text.substr(1);    //写回详细信息 
    } 
 
    //用于创建XMLHttpRequest 对象 
    this.createXmlHttp = function() { 
        var xmlHttp = null; 
        //根据window.XMLHttpRequest 对象是否存在使用不同的创建方式 
        if (window.XMLHttpRequest) { 
           xmlHttp = new XMLHttpRequest();    //FireFox、Opera 等浏览器支持的创建方式 
        } else { 
           xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE 浏览器支持的创建方式 
        } 
        return xmlHttp; 
    } 
 
    //检查两次输入的密码是否一致 
    this.checkPassword = function() { 
        var p1 = document.getElementById("password").value;  //获取密码 
        var p2 = document.getElementById("password2").value;  //获取验证密码 
 
        //当两部分密码都输入完毕后进行判断 
        if (p1 != "" && p2 != "") { 
            if (p1 != p2) { 
                this.showInfo("password2" + Checker._infoDivSuffix, 
                                 "0 密码验证与密码不一致。"); 
 
            } else { 
                this.showInfo("password2" + Checker._infoDivSuffix, "1 两次密码输入正确")
            } 
        } else if (p1 != null) { 
            this.showInfo("password" + Checker._infoDivSuffix, "1"); 
        } 
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值