struts2中的Ajax异步校验

Posted bluedarkni

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts2中的Ajax异步校验相关的知识,希望对你有一定的参考价值。

登录时验证码的异步校验:

1.验证码生成的是图片因此在struts.xml文件里面配置action 时,result标签中type 属性是stream

2.验证码图片的src的值为配置action名字:

3.登录处理的action里面需要有一个对应的JSONObject 类型的成员变量

4.struts.xml里面配置异步请求的action,pakage需要继承json-default;result标签中type 属性是josn;

 

param标签的name属性为root,还有个后处理器,对结果进行处理,

 

如果自己定义name的话,需要注意返回的josn\'格式再获取值:

 

 验证码action:

package ni.jun.yang.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class CreateImageAction extends ActionSupport{
    
    private static final long serialVersionUID = 1L;

    private ByteArrayInputStream inputStream;

    private static int WIDTH = 60;

    private static int HEIGHT = 20;

    public ByteArrayInputStream getInputStream()
    {
        return inputStream;
    }

    public void setInputStream(ByteArrayInputStream inputStream)
    {
        this.inputStream = inputStream;
    }

    private static String createRandom()
    {
        String str = "0123456789qwertyuiopasdfghjklzxcvbnm";

        char[] rands = new char[4];

        Random random = new Random();

        for (int i = 0; i < 4; i++)
        {
            rands[i] = str.charAt(random.nextInt(36));
        }

        return new String(rands);
    }

    private void drawBackground(Graphics g)
    {
        // 画背景
        g.setColor(new Color(0xDCDCDC));

        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 随机产生 120 个干扰点

        for (int i = 0; i < 120; i++)
        {
            int x = (int) (Math.random() * WIDTH);

            int y = (int) (Math.random() * HEIGHT);

            int red = (int) (Math.random() * 255);

            int green = (int) (Math.random() * 255);

            int blue = (int) (Math.random() * 255);

            g.setColor(new Color(red, green, blue));

            g.drawOval(x, y, 1, 0);
        }
    }

    private void drawRands(Graphics g, String rands)
    {
        g.setColor(Color.BLACK);

        g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18));

     // 在不同的高度上输出验证码的每个字符

        g.drawString("" + rands.charAt(0), 1, 17);

        g.drawString("" + rands.charAt(1), 16, 15);

        g.drawString("" + rands.charAt(2), 31, 18);

        g.drawString("" + rands.charAt(3), 46, 16);

        System.out.println(rands);

    }

    @Override
    public String execute() throws Exception
    {
        HttpServletResponse response = ServletActionContext.getResponse();
//        HttpServletRequest request = ServletActionContext.getRequest();
//        HttpSession session = request.getSession();
     // 设置浏览器不要缓存此图片
        response.setHeader("Pragma", "no-cache");

        response.setHeader("Cache-Control", "no-cache");

        response.setDateHeader("Expires", 0);

        String rands = createRandom();

        BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
                BufferedImage.TYPE_INT_RGB);

        Graphics g = image.getGraphics();

        // 产生图像
        drawBackground(g);

        drawRands(g, rands);

     // 结束图像 的绘制 过程, 完成图像
        g.dispose();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        ImageIO.write(image, "jpeg", outputStream);

        ByteArrayInputStream input = new ByteArrayInputStream(outputStream
                .toByteArray());

        this.setInputStream(input);

        HttpSession session = ServletActionContext.getRequest().getSession();
        session.setMaxInactiveInterval(120);  //设置验证码有效时间120s
        session.setAttribute("checkCode", rands);
        
        input.close();
        
        outputStream.close();

        return SUCCESS;
    }

}

验证码xml配置:

<action name="checkimage" class="ni.jun.yang.action.CreateImageAction">
            <result name="success" type="stream"></result>
        </action>

页面jsp代码:

<%@ page language="Java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags" prefix = "s" %>
<!DOCTYPE HTML >
<html>
  <head>
  <base href="<%=basePath%>">    
  <title>登录</title>        
  <meta charset="utf-8">
  <script src="jquery-3.2.1.min.js"></script>
 </head>
 <body>
<script>
 $(function(){
    
     
     $("#check").blur(function(){
         
         var checkcode = $(this).val();
         alert(checkcode);
         $.ajax({
                url:"checkimage1",
                data:{check:checkcode},
                type:"post",
                dataType:"json",            
                success:function(result){
                    alert(result.result);
                }
        });
     });     
 });
      
 </script>
 
 <s:form action="loginaction" theme="simple">
     帐户:<s:textfield name = "userName"></s:textfield><br/>
     密码:<s:password name = "psw"></s:password><br/>
     验证码:<img src="checkimage"><s:textfield name = "check"  id="check"></s:textfield><br/>
     <s:submit value="登录"></s:submit>
 </s:form>
 
 </body>
</html>

登录处理action:

package ni.jun.yang.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import net.sf.json.JSONObject;
import ni.jun.yang.service.LoginService;
import ni.jun.yang.bean.User;
import ni.jun.yang.service.*;

public class LoginAction {
    private String userName;
    private String psw;
    private String check;
    private JSONObject result;
    public LoginAction() {
        
    }
    
    public JSONObject getResult() {
        return result;
    }

    public void setResult(JSONObject result) {
        this.result = result;
    }

    public String getCheck() {
        return check;
    }

    public void setCheck(String check) {
        this.check = check;
    }

    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPsw() {
        return psw;
    }
    public void setPsw(String psw) {
        this.psw = psw;
    }
    
    public String  execute(){

//        HttpServletRequest request = ServletActionContext.getRequest();
//        String xString = request.getParameter("userName");
//        System.out.println("请求获取:"+xString);
//        System.out.println("--------");
//        System.out.println("参数封装:"+userName);
//
//        request.setAttribute("userName", userName);
//        LoginService ls = new LoginService();    
        String checkCode = (String) ActionContext.getContext().getSession().get("checkCode");
        if(check.equals(checkCode)){
            IUserService ius = new UserServiceImpl();        
            User user1 = new User();
            user1.setUserName(userName);
            user1.setUserPsw(psw);        
            User user = ius.selectUser(user1);    
            System.out.println(user.getUserSex());
            if(user != null){
                HttpSession session = ServletActionContext.getRequest().getSession();
                session.setMaxInactiveInterval(30*60); //登录成功设置session时间1800s
                return  "success";
            }else{
                return "fail";
            }
        }else{
            return "fail";
        }        
    }
    
    public String  execute1(){    // ajax 异步验证验证码
        String checkCode = (String) ActionContext.getContext().getSession().get("checkCode");
        result = new JSONObject();
        if(check.equals(checkCode)){
            result.accumulate("result", "正确!"); 
        }else{
            result.accumulate("result", "错误!");
        }
                
        return "success";
    }
    
}

ajax请求的xml配置:

<package name="mystrusts1" extends="json-default" namespace="/">
        <action name="checkimage1" class="ni.jun.yang.action.LoginAction" method="execute1">
            <result name="success" type="json">
                <param name="root">result</param>
            </result>
        </action>
    </package>

 

以上是关于struts2中的Ajax异步校验的主要内容,如果未能解决你的问题,请参考以下文章

struts2中Ajax校验

使用ajax异步下载文件,后端为struts2

AJAX异步校验

Ajax异步方式实现登录与參数的校验

AJAX异步校验

SSH实战 · 唯唯乐购项目(上)