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

struts2.1+json+jquery1.4实现用户名校验
?strutsaction代码这样写的 其实很简单
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;
    }

    @Override
	public String execute() {
        this.result = name+pass;
        System.out.println(pass);
        return  SUCCESS;
    }

}

?然后配置struts.xml文件

<?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>    

?

最后写jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<script type="text/javascript" src="jquery/jquery-1.4.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属性
        document.getElementById("jieguo").innerHTML=data.result;
        
            //获取数据后渲染页面
    }
	</script>
  </head>
  
  <body>
   帐号:<input id="name" type="text">
  	密码:<input id = "pass" type="text">
  结果:<span id="jieguo"></span>
        <input type="button" value="ok" onclick="javascript:clickButton();">
  </body>
</html>

?

里边其实还有jquery带代码中自己下载吧

我用的工具是myeclipse8.6forspring 布局如下图

?

?

?