struts中json机制与普通页面跳转机制混用(全局结果集配置返回json)

package继承json-default与struts-default

  返回结果是add的话将addResult属性转换为json返回(addResult属性有getter,setter方法),返回结果是查询是正常的页面跳转。

  如果配置中不写param,默认会将所要带get,set的属性转为JSON。

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 
 6 <struts>
 7 
 8     <!-- <constant name="devMode" value="true"></constant> -->
 9     <constant name="struts.enable.DynamicMethodInvocation" value="true" />
10     <constant name="struts.action.extension" value="action" />
11     <constant name="struts.objectFactory" value="spring"></constant>
12 
13     <package name="liuyan" namespace="/" extends="struts-default,json-default">
14         <action name="liuyan_*" class="liuyanAction" method="{1}">
15             <result name="add" type="json">
16                 <param name="root">addResult</param>
17             </result>
18             <result name="chaxun">/liuyan.jsp</result>
19         </action>
20     </package>
21 
22 </struts>

 

2.Action代码(处理增加与查询请求)

package cn.qlq.action;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.opensymphony.xwork2.ActionSupport;

import cn.qlq.bean.Liuyan;
import cn.qlq.service.LiuyanService;
import cn.qlq.service.impl.LiuyanServiceImpl;
import cn.qlq.utils.PageBean;

@Controller
@Scope("prototype")
@SuppressWarnings("all")
public class LiuyanAction extends ActionSupport {

    @Resource
    private LiuyanService liuyanService;
    private String currentPage;
    private Map result;
    private String addResult;
    private Liuyan liuyan;

    // 增加,用ajax+json交互
    public String addLiuyan() throws SQLException {
        liuyan.setRiqi(new Date());
        boolean result = liuyanService.addLiuyan(liuyan);
        addResult = result ? "留言成功" : "添加失败";
        return "add";
    }

    // 查询留言
    public String getLiuyans() throws SQLException {
        result = new HashMap();
        Map condition = new HashMap<>();
        if (currentPage == null) {
            condition.put("currentPage", 1);
        } else {
            condition.put("currentPage", Integer.valueOf(currentPage));
        }
        condition.put("currentCount", 8);
        PageBean<Liuyan> pageBean = liuyanService.getPageBeanPage(condition);
        result.put("pageBean", pageBean);
        return "chaxun";
    }

    public LiuyanService getLiuyanService() {
        return liuyanService;
    }

    public void setLiuyanService(LiuyanService liuyanService) {
        this.liuyanService = liuyanService;
    }

    public Map getResult() {
        return result;
    }

    public void setResult(Map result) {
        this.result = result;
    }

    public String getAddResult() {
        return addResult;
    }

    public void setAddResult(String addResult) {
        this.addResult = addResult;
    }

    public Liuyan getLiuyan() {
        return liuyan;
    }

    public void setLiuyan(Liuyan liuyan) {
        this.liuyan = liuyan;
    }

    public String getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(String currentPage) {
        this.currentPage = currentPage;
    }
}

 

3.JS函数(ajax提交表单)

/**
 * 
 * Created by liqiang on 2017/10/1.
 */
$(function() {
    /**
     * 提交按钮点击事件,内容不为空 的时候打开模态框输入姓名
     */
    $("#fabiao").click(function() {
        editor.sync();
        // 判断内容区是否为空
        if (editor.isEmpty()) {
            alert("内容不能为空!");
            return;
        }
        $("#tijiaomotai").modal();
    });
    $("#tijiao").click(function() {
        $("input[name='liuyan.name']").val($("input[name='name']").val());
        $.ajax({
            url : 'myBlog/liuyan_addLiuyan.action',
            data : {
                'liuyan.content' : editor.html(),
                'liuyan.name' : $("input[name='name']").val()
            },
            type : 'POST',
            async : true,
            success : function(data) {
                alert(data);
                window.location.href = 'liuyan_getLiuyans.action';
            },
            error : function() {

            }
        });
    });

});

 

-------------------------------------------------------配置全局结果集返回json------------------------------------------

 1.可以配置一个全局结果集,将所有回传的数据装入一个map中(对于json机制超级有用,且容易理解)

  也就是所有的访问都将map转为json返回给前台。全局结果集如果不写参数将所有的带get,set的属性转为json返回前台。

struts配置:

<?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>
    <package name="exam" namespace="/" extends="json-default,struts-default">
        <!-- 全局结果集,将response转换为json传到前台 -->
        <global-results>
            <result name="success" type="json">
                <param name="root">response</param>
            </result>
        </global-results>

        <!-- 生成部门树 -->
        <action name="exam_*" class="addExamAction" method="{1}"></action>


    </package>
</struts>

 

Action代码:

package cn.xm.exam.action.exam.exam;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

import cn.xm.exam.service.employee.in.DepartmentService;

/**
 * 增加考试Action
 * 
 * @author QiaoLiQiang
 * @time 2017年10月14日下午4:55:27
 */
@Controller
@Scope("prototype")
@SuppressWarnings("all")
public class AddExamAction extends ActionSupport {
    private Logger logger = Logger.getLogger(AddExamAction.class);
    @Autowired
    private DepartmentService departmentService;// 内部部门(用于生成部门树)
    private Map response;// 用于包装所有回传的ajax数据

    public String getDepartmentTree() {
        response = new HashMap();
        List<Map<String, Object>> departmentTrees = null;
        try {
            departmentTrees = departmentService.getDepartmentTreeForExam();
        } catch (SQLException e) {
            logger.error("查询内部部门树出错!", e);
        }
        response.put("departmentTrees", departmentTrees);
        return SUCCESS;
    }

    public Map getResponse() {
        return response;
    }

    public void setResponse(Map response) {
        this.response = response;
    }

}

 

JS中ajax访问:

  response与后台的response对应。可以快速的理解为js的response参数与后台的response参数等价。(也是一种好的编程习惯,便于快速理解与使用)

    $.ajax({
        url : '/Exam/exam_getDepartmentTree.action',
        async : true,
        dataType : 'json',
        success : function(response) {
            var departmentTrees = response.departmentTrees;
        },
        error : function() {
            alert("查询内部部门树失败!!!")
        }
    });

 

 

 

结果:

{"departmentTrees":[{"departmentId":"10","departmentName":"厂级-1"},{"departmentId":"10001","departmentName":"部门1_10","upDepartmentId":"10"},{"departmentId":"10001001","departmentName":"班组1_10001","upDepartmentId":"10001"},{"departmentId":"10002","departmentName":"部门2_10","upDepartmentId":"10"},{"departmentId":"10002001","departmentName":"班组2_10002","upDepartmentId":"10002"},{"departmentId":"10003","departmentName":"部门3_10","upDepartmentId":"10"},{"departmentId":"11","departmentName":"厂级-2"},{"departmentId":"11001","departmentName":"部门1_11","upDepartmentId":"11"},{"departmentId":"12","departmentName":"厂级-3"}]}

 

posted @ 2017-10-10 22:53  QiaoZhi  阅读(210)  评论(0编辑  收藏  举报