struts2 ajax json 异步刷新整合

来源:互联网 发布:windows 10有扫雷 编辑:程序博客网 时间:2024/06/09 20:05

必要的包有:struts2主要包,json包

1.html关键代码如下:

搜索代码:

<div id="searchtitle">
                <div>
              
                <div><input id="textfield"  type="text" name="condition" value='<s:property value="condition"/>'/><input id="submit" type="button" value="搜索"onclick="search()"/>

</div>                
               </div>
 </div>


  <table width="765" border="0" cellpadding="0" cellspacing="0"
                    id="tableContent">
                    此处将填充异步刷新内容
        </table>


2.ajax的js代码如下:

var xmlHttp;
function createXMLHttpRequest()
{
    if(window.ActiveXObject)
    {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest)
    {
        xmlHttp = new XMLHttpRequest();
    }
}

function handleStateChange1()
{
    if(xmlHttp.readyState == 4)
    {
        if(xmlHttp.status == 200)
        {
            var divObj = document.getElementById("tableContent");
            var userinfos = eval('(' + xmlHttp.responseText + ')');//将action层返回的json格式数组转换为js的数组
            if(userinfos.length > 0){
                for(var i = 0; i < userinfos.length ;i++){
                    divObj.innerHTML = divObj.innerHTML +  "<tr><td height='105' align='center' valign='middle' class='td2'>"+
                 "<img src='images/mainBannerContent2People2Img.gif' width='54' height='54' alt='' /></td>"+
                    "<td height='105' align='left' valign='bottom' class='td3'><font color='#005dc3' size='3' face='微软小黑'><b>"+userinfo[i].username+"</b></font> </td>"+//输出数值属性
                    "</tr>";    
                }
            }else {
                divObj.innerHTML = "<div>无结果</div>";
            }
            
        }
    }
}

var obj = 0;
var condition;
function search(){
 
    condition = document.getElementById("textfield");
    createXMLHttpRequest();
    var url = "SearchOne.action?condition="+condition.value+"&searchtype="+searchtype;//异步刷新的action
    xmlHttp.open("POST", url, true);    
    xmlHttp.onreadystatechange = handleStateChange1;
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xmlHttp.send(null);
}


3.action层代码如下:

package com.nbf.find.action;


import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;
import org.json.JSONObject;

import com.nbf.find.service.UserService;
import com.nbf.find.vo.Userinfo;
import com.opensymphony.xwork2.ActionSupport;

public class SearchOneAction extends ActionSupport {
    /**
     *
     */
    private static final long serialVersionUID = 7848488788100591233L;
    private UserService userService;
    
    public String execute(){
        int currentpage = 0;
        int searchtype = 1;
        List<Userinfo> userinfos = new ArrayList<Userinfo>();    //异步数据对象列表
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        
        response.setContentType("text/json;charset=UTF-8");//设置异步传输格式
        response.setHeader("Cache-Control", "no-cache");//设置不缓存
        String cp = request.getParameter("currentPage");
        
        String st = request.getParameter("searchtype");
        if(st != null){
            searchtype = Integer.parseInt(st);
        }
        
        if(cp != null ){
            currentpage = Integer.parseInt(cp);
        }
        String condition = null;
        try {
            condition = new String(request.getParameter("condition").getBytes("iso-8859-1"), "utf-8");//转换格式为utf-8防止乱码
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        if(searchtype == 1){//找号码
            userinfos.addAll(userService.getUserinfoByUserId(Long.parseLong(condition)));//从service层得到对象列表

        } else if(searchtype == 2){//找姓名
         
            userinfos.addAll(userService.getUserinfosByUsername(condition, currentpage, 20));
    
        }

        JSONArray jsons = new JSONArray();//json数组格式
        if(!userinfos.isEmpty()){
            for(Userinfo userinfo : userinfos){
                jsons.put(new JSONObject(userinfo));
            }
        }

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(jsons.toString());//将json格式数组返回到客户端
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            writer.flush();
            writer.close();        
        }
        
        return SUCCESS;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public UserService getUserService() {
        return userService;
    }

    

}

4.struts2.xml配置

<action name="SearchOne" class="com.nbf.find.action.SearchOneAction">
            <result>/searchone.jsp</result>
            <interceptor-ref name="defaultStack"/>
        </action>



原创粉丝点击