码迷,mamicode.com
首页 > Web开发 > 详细

struts2下实现的json传递list,object。

时间:2015-10-07 18:53:54      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

必须的jar:技术分享

java bean:

package upload.progress.action;

public class music {
    private String name;
    private String singer;
    private String source;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSinger() {
        return singer;
    }
    public void setSinger(String singer) {
        this.singer = singer;
    }
    public String getSource() {
        return source;
    }
    public void setSource(String source) {
        this.source = source;
    }
    

}

struts2.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.devMode" value="false" />

    <include file="example.xml"/>



    <package name="default" namespace="/" extends="struts-default">
        <default-action-ref name="index" />
        <action name="index">
            <result type="redirectAction">
                <param name="actionName">HelloWorld</param>
                <param name="namespace">/example</param>
            </result>
        </action>
    </package>
     -->

     <package name="default" namespace="/Fileupload" extends="struts-default">
        
        <action name="practice" class="action.PracticeAction" method="practice_one">
            <result type="redirect" name="success">
                /js/uploadify.jsp
            </result>
        </action>
      
    </package>
    <!-- Add packages here -->
    <package name="ajax" namespace="/ajax" extends="json-default">
        
        <action name="ajaxTest1" class="action.ajaxTest1" method="ajaxTest">
            <result type="stream">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
                
            </result>
        </action>
        <action name="json" class="upload.progress.action.jsonTest1" method="returnMessage">
            <result name="success" type="json"></result>
        </action>
        <action name="jsonMusic" class="upload.progress.action.jsonTest1" method="returnMusic">
            <result name="success" type="json"></result>
        </action>
         <action name="jsonMusicList" class="upload.progress.action.jsonTest1" method="returnMusicList">
            <result name="success" type="json">
                <param name="root">musicList</param>
            </result>
        </action>
    </package>

</struts>

jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
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 jsonTest1.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 src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
    $("#showMessage").click(function(){
    
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "ajax/json.action",
            success: function(data){
                $("#message").html("<font color=‘red‘>"+data.message+"</font>");
            }
        });
        });
        
        $("#showMusic").click(function(){
                $.ajax({
                    type : "POST",
                    dataType : "json",
                    url : "ajax/jsonMusic.action",
                    success : function(data){
                        $.each(data,function(i,item){
                            if(item!=null){
                                alert(item.name);    
                            }
                        })
                    }
                });
            });
    
    
    $("#showList").click(function(){
                $.ajax({
                    type : "POST",
                    dataType : "json",
                    url : "ajax/jsonMusicList.action",
                    success : function(data){
                        $.each(data,function(i,item){
                            if(item!=null){
                            alert(item.name);
                            }
                        })
                    }
                });
            });
    });
</script>
  </head>
  
  <body>
    <table align="center">
        <tr>
            <td id="showMessage">Message</td>
            <td id="showMusic">showMusic</td>
            <td id="showList">showList</td>
        </tr>
        
    </table>
    <div id="message"></div>
  </body>
</html>

action:

package upload.progress.action;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import com.opensymphony.xwork2.ActionSupport;

public class jsonTest1 extends ActionSupport {
    /**
     * 处理json的action
     */
    private static final long serialVersionUID = -1519192049194890338L;
    private String message;
    private music Music;
    private List<music> musicList;
    
    public String returnMessage(){
        System.out.println("json invoking");
        message="json 字符串";
        return SUCCESS;
    }

    public String returnMusic(){
        Music =new music();
        Music.setName("忘情水");
        Music.setSinger("刘德华");
        Music.setSource("百度");
        return SUCCESS;
    }
    public String returnMusicList(){
        musicList=new ArrayList<music>();
        music Music1 =new music();
        Music1.setName("忘情水1");
        Music1.setSinger("刘德华1");
        Music1.setSource("百度1");
        
        music Music2 =new music();
        Music2.setName("忘情水2");
        Music2.setSinger("刘德华2");
        Music2.setSource("百度2");
        
        music Music3 =new music();
        Music3.setName("忘情水3");
        Music3.setSinger("刘德华3");
        Music3.setSource("百度3");
        musicList.add(Music1);
        musicList.add(Music2);
        musicList.add(Music3);
        
        return SUCCESS;
    }
    
    public String jsonArray(){
        List<String> list=new ArrayList<String>();
        JSONArray jsonArray=new JSONArray(list);
        
        return SUCCESS;
    }
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public music getMusic() {
        return Music;
    }

    public void setMusic(music music) {
        Music = music;
    }

    public List<music> getMusicList() {
        return musicList;
    }

    public void setMusicList(List<music> musicList) {
        this.musicList = musicList;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }



}

使用流的方式:

action:

package action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import Util.HibernateUtil;

import com.opensymphony.xwork2.ActionSupport;

public class ajaxTest1 extends ActionSupport {
    /**
     * 判断姓名是否存在
     */
    private static final long serialVersionUID = 1L;
    private InputStream inputStream;
    private String name;
    private String location;
    @SuppressWarnings("unchecked")
    public String ajaxTest() throws UnsupportedEncodingException{
        if(name.equals("")){
            inputStream=new ByteArrayInputStream("姓名不可以是空值哦。".getBytes("utf-8"));
            System.out.println("AJAX invoing-------------name="+name);
        }else{
            //inputStream=new ByteArrayInputStream("姓名可以使用".getBytes("utf-8"));
            SessionFactory sessionFactory= HibernateUtil.getSessionFactory();
            Session session=sessionFactory.getCurrentSession();
            Transaction tr= session.beginTransaction();
            String hql="from domain.user where name=‘"+name+"‘ ";
            Query query=session.createQuery(hql);
            List<domain.user> list=query.list();
            //System.out.println(list.get(0).getName());
            
            if(!list.isEmpty()){
                inputStream=new ByteArrayInputStream("姓名已存在。".getBytes("utf-8"));
            }else{
                inputStream=new ByteArrayInputStream("姓名可以使用。".getBytes("utf-8"));
            }
            session.clear();
            session.flush();
            tr.commit();
        }
        return SUCCESS;
    }
    public InputStream getInputStream() {
        return inputStream;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }

}

jsp:

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
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>ajaxTest1</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.min.js"></script>
<script type="text/javascript" src="../js/jquery.js"></script>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">

    $(function(){
    alert();
    $("#examine").focusout(function(){
    
        test();
    });
    
    
});


function test(){
    $.ajax({
            type: "POST",
            url: "ajax/ajaxTest1.action",
             data: "name="+$("#examine").val(),
             success: function(msg){
                 alert( "Data Saved: " + msg );
            }
            
             
        });
        }
</script>

  </head>
  
  <body>
  <form action="" method="post"  enctype="multipart/form-data"></form>
  <table>
      <tr>
          <td>姓名:</td>
          <td></td>
          <td>密码:</td>
      </tr>
      <tr>
          <td> <input name="username" type="text" maxlength="40" id="examine"></td>
          <td></td>
          <td> <input name="password" type="password" maxlength="40" ></td>
      </tr>
  </table>
 
  </body>
</html>

 

struts2下实现的json传递list,object。

标签:

原文地址:http://www.cnblogs.com/liusijia/p/4859109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!