java后台传递json数据到前端并渲染react组件(react+struts2)

一、前端包括CommentList,Comment,CommentBox组件(父→子,CommentBox→CommentList→Comment),CommentBox组件负责从后台接收json数据,然后存到组件状态机中,然后CommentList组件用this.props得到json数据再分配给Comment组件。

 

代码如下:

1.CommentBox组件

var CommentBox=React.createClass({
            loadCommentsFromServer:function() {
                $.ajax({
                    url:this.props.url,
                    type:"GET",
                    dataType:"json",
                    cache:false,
                    success:function(data) {
                        this.setState({data:data});
                    }.bind(this),
                    error:function(xhr,status,err) {    
                        console.error(this.props.url, status, err.toString());
                    }.bind(this)
                });
            },
            getInitialState:function() {
                return {data:[]};
            },
            
            componentDidMount:function() {
                this.loadCommentsFromServer();
                setInterval(this.loadCommentsFromServer,this.props.pollInterval);
            },

            render:function() {
                return (
                    <div className="commentBox">
                        <h1>comments</h1>
                        <CommentList data={this.state.data}/>
                        <CommentForm />
                    </div>
                );
            }
});

 

2.CommentList组件

var CommentList=React.createClass({
            render:function() {
                var commentNodes=this.props.data;    
                return (
                    <Comment key={commentNodes.id} author={commentNodes.author}>
                        {commentNodes.text}
                    </Comment>
                );
            }

 });

 

3.Comment组件

var Comment=React.createClass({
            render:function() {
                return (
                    <div className="comment">
                        <h1 className="commentAuthor">{this.props.author}</h1>
                        {this.props.children}
                    </div>
                );
            }
 });

 

 

 

 

二、后台使用struts2框架,利用text类(action类),发送json数据到前端。

 

代码如下:

 

1.text类:

import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONObject;
import com.opensymphony.xwork2.ActionSupport;

public class text extends ActionSupport{
    public String execute()throws Exception {
   
         HttpServletResponse response=ServletActionContext.getResponse();
         response.setContentType("text/html;charset=UTF-8"); 
         PrintWriter out = response.getWriter();
         
        JSONObject json=new JSONObject();
        json.put("id", "1");
        json.put("author", "a1");
        json.put("text", "用户存在");
        System.out.println(json.toJSONString());
        
        
        return null;
    }
}

注意:这里return null,并且struts.xml文件不用写<result>标签,只写<action>标签配置。

 

 

 

2.struts.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts  PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
                         "http://struts.apache.org/dtds/struts-2.3.dtd"
>

<struts>
        <constant value="false" name="struts.enable.DynamicMethodInvocation"/>
        <constant value="false" name="struts.devMode"/>
        <constant name="struts.i18n.encoding" value="UTF-8"/>
          <package name="default" extends="struts-default"><!--需要将struts-default改为--> 
              <action name="jsonaction" class="com.SMS.testAction.text">
                  
             </action>
           </package>    
</struts>

 

 

3.web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 

 

另外,前端要读取json数据的值,本例可以直接用json对象·属性(key)读取。

代码如下:

$.ajax({
                        async:true,
                        url:"jsonaction",
                        dataType:"json",
                        type:"GET",
                        success:function(data){
                            alert(data.text);                 /*此处data为json对象,text为属性名*/
                        },
                        error:function(xhr,status,err){
                            alert("失败"+"——"+xhr.responseText+“——”+err.toString());
                        }
  });

转载于:https://my.oschina.net/fycool/blog/796379

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值