struts2返回json格式的数据

描述:当前端使用ajax发送请求到action时,如果需要返回json格式的数据,如对象集合。具体做法如下:

前端代码:

<%@ 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 enty_json.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">
    -->
        <!-- 引入jquery -->
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.9.1.js"></script>
    
    <script type="text/javascript">
        function loadUsers(){
            $.ajax({
                url: "user.action", 
                type:"post",
               // data:"name="+$(‘#name‘)[0].value+"&password=123",//向后台传送的数据格式
                dataType:"json",
                success: function(data, textStatus){
                    alert(textStatus);
                    $.each(data,function(n,value){
                         var str = "<tr><td>"+value.id+"</td><td>"+value.name+"</td></tr>";
                         $("#userList").append(str);
                    });
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){
                     alert(textStatus);
                }
            });
        }
    </script>

  </head>
  
  <body>
  <input type="button" id="btn" onClick="loadUsers()" value="加载对象列表">
  <center>
      <div>对象列表</div>
      <table id="userList">
         <tr><td>ID</td><td>姓名</td></tr>
      </table>
  </center>

  </body>
</html>

action中的代码:

package action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import dao.UserDao;
import enty.User;

public class UserAction extends ActionSupport{
    private List< User> lists = new ArrayList<User>();
    
    //使用struts2返回json数据,需要在struts.xml配置要返回的数据
    public String execute() {
        UserDao userDao = new UserDao();
        lists = userDao.getUserList();
        return "success";
    }
    //传统方式返回ajax数据,这种返回方式不需要再配置文件中配置
    public String getState(){
        System.out.println("传统的ajax");
        HttpServletResponse response = ServletActionContext.getResponse();
        try {
            PrintWriter out = response.getWriter();
            out.println("{\"success\":\"true\",\"type\":\"succ\"}");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //这个方法必须写上
    public List<User> getLists() {
        return lists;
    }
    public void setLists(List<User> lists) {
        this.lists = lists;
    }
    

}

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>
    <!-- 禁用动态方法调用(即禁用xxx!add.action方式的调用,因为Struts2.1版本开始就不建议这种方式的使用) -->
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
        <package name="struts2" extends="struts-default,json-default">
             <action name="user_*" class="action.UserAction" method="{1}">
                 <result name="success" type="json">
                     <param name="root">lists</param><!-- action中的属性 -->
                 </result>
             </action>
             
        </package>
        
</struts>

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。