struts2-json-jquery ajax 操作

struts 和 json所用jar包 

package com.jokey.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jokey.bean.User;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    private User user;

    public  List<User> getUsers() {
        return users;
    }

    public  void setUsers(List<User> users) {
        users = users;
    }

    //将会被Struts2序列化为JSON字符串的对象
    private Map<String, Object> dataMap;
    
    private  List<User> users = new ArrayList<User>();

    /**
     * 构造方法
     */
    public UserAction() {
        //初始化Map对象
        dataMap = new HashMap<String, Object>();
    }

    /**
     * 测试通过action以视图方式返回JSON数据
     * @return
     */
    public String login() {
        if(user!=null&&user.getId().equals("jokey")&&user.getPassword().equals("123")){
            dataMap.put("loginResult", "true");
        }else{
            dataMap.put("loginResult", "false");
        }
        return SUCCESS;
    };
    
    public String getList(){
        User user1 = new User();
        user1.setId("01");
        user1.setName("peter");
        User user2 = new User();
        user2.setId("02");
        user2.setName("tom");
        users.add(user1);
        users.add(user2);
        return SUCCESS;
    }
    
    public String delUser(){
        User user1 = new User();
        user1.setId("01");
        user1.setName("peter");
        User user2 = new User();
        user2.setId("02");
        user2.setName("tom");
        users.add(user1);
        users.add(user2);
        boolean flag = false;
        for (User user : users) {
            if(user.getId().equals(user.getId()));
            users.remove(user);
            flag = true;
            dataMap.put("delResult", flag);
        }
        return SUCCESS;
    }

    
    
    /**
     * Struts2序列化指定属性时,必须有该属性的getter方法,实际上,如果没有属性,而只有getter方法也是可以的
     * @return
     */
    public Map<String, Object> getDataMap
<?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.devMode" value="true" />

    <package name="default" namespace="/" extends="json-default">
        <action name="login" class="com.jokey.action.UserAction" method="login">
            <result type="json">
                <param name="root">dataMap</param>
            </result>
        </action>
        <action name="getList" class="com.jokey.action.UserAction" method="getList">
            <result type="json">
                <param name="root">users</param>
            </result>
        </action>
        <action name="del" class="com.jokey.action.UserAction" method="delUser">
            <result type="json">
                <param name="root">dataMap</param>
            </result>
        </action>
        
    </package>


</struts>

 

() {
        return dataMap;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="json" uri="/struts-json-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <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="js/jquery-1.7.1.min.js"></script>
  <script type="text/javascript" src="js/jquery.form.js"></script>
  <script type="text/javascript">
      function submitForm(){
          $.ajax({
            type: "POST",
            dataType:'json',
            data:$('#login').serialize(),//获取表单中提交内容 自动拼装参数
            //防止IE8 中文乱码
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            url: 'login.action',//提交到的action地址
            success: function(dataMap){
             if(dataMap.loginResult=='true'){
                     alert('登陆成功');
                    location.href='list.jsp';
             }else{
                 alert('登陆失败');
             }
            }
         });
      }
  </script>
  
  
  </head>
  
  <body>
 
       <s:form id="login" action="" theme="simple">
           <s:textfield name="user.id"></s:textfield>
           <s:password name="user.password"></s:password>
       </s:form>
           <button onclick="submitForm()">提交</button>
  </body>
</html>





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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'list.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="js/jquery-1.7.1.min.js"></script>
  <script>
  //文档加载后 自动请求数据
      $(document).ready(function(){
          init();
      });
  
  //初始化页面
  function init(){
      $.ajax({
          type: "POST",
          dataType:'json',
          //防止IE8 中文乱码
          contentType: "application/x-www-form-urlencoded; charset=utf-8",
          url: 'getList.action',//提交到的action地址
          success: function(users){
              var innerHtml='';
                for(var i=0;i<users.length;i++){
                    innerHtml+='<tr><td>'+users[i].id+'</td>+<td>'+users[i].name+'</td>+<td><a href=\"javascript:void(0);\" onclick=\"delUser('+users[i].id+')\">果断删除</a></td></tr>';
                }
                $('#userTable').html(innerHtml);
          }
       });
  }
  
  
      function delUser(id){
          $.ajax({
            type: "POST",
            dataType:'json',
            data:'user.id='+id,
            //防止IE8 中文乱码
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            url: 'del.action',//提交到的action地址
            success: function(dataMap){
             if(dataMap.delResult||dataMap.delResult=='true'){
                     alert('删除成功');
                     init();
             }else{
                 alert('删除失败');
             }
            }
         });
          
      }
  </script>
  </head>
  
  <body>
  <table id="userTable" border="1px" rules="all">
  
  </table>
  </body>
</html>

 

posted @ 2013-04-26 15:13  ×jokey  阅读(592)  评论(0编辑  收藏  举报