日期:2014-05-16  浏览次数:20629 次

struts2实现ajax

Struts2的这个功能相信已经有很多了。。我这个是相对来说极其简单的实现。相信一看就明白。

首先要引如jquery.1.3.2.min.js。引入struts2必须的六个包。。还要引入

json-lib-2.3-jdk13.jar、struts2-json-plugin-2.1.8.1.jar?、ezmorph-1.0.6.jar

commons-logging-1.1.1.jar、commons-lang-2.5.jar、commons-collections-3.2.jar、

commons-beanutils-1.8.3.jar包。引入完后。先看看index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
	<script type="text/javascript" src="${pageContext.request.contextPath }/jquery/jquery-1.3.2.min.js"></script>
	<script type="text/javascript">
	function clickButton()
    {    
	    //alert($('#name').val());
        var url = "hello";
        var params = {
               name:$("#name").val(),
               pass:$("#pass").val()
        };
        jQuery.post(url, params, callbackFun, 'json');
    }
    function callbackFun(data)
    {
        alert(data.result);//对应HelloWorld类的message属性
            //获取数据后渲染页面
    }
	</script>
  </head>
  
  <body>
   <input id="name" type="text">
  	<input id = "pass" type="text">
        <input type="button" value="ok" onclick="javascript:clickButton();">
  </body>
</html>

?

?

然后就是struts2配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="ajax" extends="json-default">
		<action name="hello" class="com.vo.HelloWorld">
			<result type="json" />
		</action>
	</package>
</struts>    

?完了就是类文件了

package com.vo;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorld extends ActionSupport {

	private static final long serialVersionUID = 1035615877474749202L;
	private String name;
    private String result;
    private String pass;

    // ajax请求参数赋值
    public void setName(String name) {
        this.name = name;
    }
    public void setPass(String pass){
    	this.pass = pass;
    }

    // ajax返回结果
    public String getResult() {
        return result;
    }

    public String execute() {
        this.result = name+pass;
        System.out.println(pass);
        return "success";
    }

}

?

就大功告成了。底下有例子。别忘记下jar包。可以下载。可以运行的。

?