struts2+ajax+json 基本

struts2的基本配置就不再详述:

1.添加基本的类库:struts2+jquery+json类库(所有依赖jar文件在struts/lib下可以找到)  [ commons-beanutils.jar commons-collections.jar  commons-lang.jar  ezmorph.jar  json-lib.jar struts2-json-plugin.jar  ]

基本类库

2.整个项目图如下:

3.struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <constant name="struts.devMode" value="true" />
   
    <package name="ttt"  extends="json-default">
        <action name="jsonAction" class="action.JsonAction">
            <result type="json">
                <param name="root">result</param>
            </result>
        </action>   
    </package>
</struts>
 

4.index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src=\'#\'" /jquery-1.6.js"></script>
    <script type="text/javascript" src=\'#\'" /index.js"></script>
  </head>
 
  <body>
   <form>
           Name:<input id="name" name="user.name" value=""/> <font color="red"><span id="result"></span></font>  <br/>
           Age:<input name="user.age" value=""/>   <br/>
           <input type="button" id="button1" value="提交"/>
   </form>
 
  </body>
</html>
 

5.index.js

$(function(){
   
    $("#name").focus(function(){
        $(this).val("");
        $("#result").html("");
    });
   
    $("#name").blur(function(){
        if( $(this).val()=="" ){
            $("#result").html("用户名不能为空");
        }else{
                   
        var params=$("input").serialize();
        $.ajax({
            url:"jsonAction",
            type:"post",
            dataType:"json",
            data:params,
            success:update_page
        });
        }
    });
});

function update_page(result){
    $("#result").html(result);
}

 

本文出自 “李新博客” 博客,谢绝转载!

你可能感兴趣的:(Ajax,职场,基本配置,休闲)