十五、Ajax支持

十五、Ajax支持

1.使用stream类型的Result实现Ajax

Action:

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import com.opensymphony.xwork2.ActionSupport;

public class AjaxTest1Action extends ActionSupport{
    private String username;    //用户名
    private String userpass;    //密码
    private InputStream inputStream;    //封装输出结果的二进制流
    
    //setter、getter
    
    public void setUsername(String username){
        this.username = username;
    }
    public String getUsername(){
        return this.username;
    }
    public void setUserpass(String userpass){
        this.userpass = userpass;
    }
    public String getUserpass(){
        return this.userpass;
    }
    
    //提供一个返回二进制流的方法
    public InputStream getResult(){
        return this.inputStream;
    }
    
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        //判断用户名密码并生成对应的响应
        if(username.equals("test")&&userpass.equals("test")){
            inputStream = new ByteArrayInputStream("登陆成功".getBytes("utf-8"));
        }else{
            inputStream = new ByteArrayInputStream("登陆失败".getBytes("utf-8"));
        }
        return SUCCESS;
    }
}

 

struts.xml中的配置:

<action name="ajaxTest1Action" class="testAction.AjaxTest1Action">
            <result type="stream">
                <param name="contentType">text/html</param>
                <param name="inputName">result</param>
            </result>
</action>

jsp页面及js代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.3.1.min.js"></script>
</head>
<body>
<s:form id="loginForm" >
 <s:textfield name="username" key="用户名"/>
 <s:password name="userpass" key="密码"/>
 <s:submit id="loginBn" key="登录"/>
</s:form>

<div id="show">
<!-- 展示登陆结果的div --></div>

<script type="text/javascript">
    //为id为loginBn的按钮绑定事件处理函数
    $("#loginBn").click(
        function(){
            $("#show").hide();
            //指定向ajaxTest1Action发送请求,以id为loginForm表单中值为请求参数
            $.get("ajaxTest1Action",$("#loginForm").serializeArray(),
                    function(data,strutsText){
                        $("#show").append("登陆结果:"+data+"<br/>");
                        $("#show").show(60000);
                    },
                    //指定服务器响应html
                    "html"
            );
        }        
    );
</script>
</body>
</html>

 

 

 

posted @ 2017-08-03 16:38  丶theDawn  阅读(122)  评论(0编辑  收藏  举报