EXT4提交表单到struts2返回json数据并跳转页面

来源:互联网 发布:mac itunes使用教程 编辑:程序博客网 时间:2024/05/29 14:27

新手学习ext,提交表单的时候总是不能返回正确的json数据,在网上找了相关资料终于发现了问题,记录下以供大家参考

这里说明下,我用的是ext的form提交,要求必须返回json格式的数据

Ext.require([    'Ext.form.*',    'Ext.layout.container.Absolute',    'Ext.window.Window']);Ext.onReady(function() {Ext.QuickTips.init();Ext.form.Field.prototype.msgTarget = 'side';     var form = new Ext.form.Panel({     layout: 'absolute',         defaultType: 'textfield',         border: false,         url: basePath + 'user!login.action',        items: [{            fieldLabel: '用户名',            name: 'user.name',            allowBlank : 'false',            x: 80,            y: 60        },{            fieldLabel: '密码',            name: 'user.password',            allowBlank : 'false',            x: 80,            y: 100        }]    });    new Ext.window.Window({        autoShow: true,        title: '用户登录',        width: 500,        height:300,        minWidth: 300,        minHeight: 200,        layout: 'fit',        plain: true,        closable : false,        dragglable : false,        items: form,        buttons: [{            text: '注册'        },{            text: '登录',            handler : function(){                    form.submit({                        success: function(form, action) {                         if(action.result.success){                            location.href = basePath + 'app/main.jsp';                            }                        },                        failure: function(form, action) {                            if(action.result.success == false){                                Ext.Msg.alert("Failed","登录失败!")                            }                    });                }        }]    });});

下面是action代码

public class UserAction extends ActionSupport {private User user;private UserService userService; private Map<String,Object> dataMap;  public String login() throws Exception{ dataMap = new HashMap<String, Object>(); if(userService.queryUserInfo(user)){dataMap.put("success", true);return "main";}else{dataMap.put("success", false);return "index";}}@JSON(serialize=false)public User getUser() {return user;}public void setUser(User user) {this.user = user;}@JSON(serialize=false)public UserService getUserService() {return userService;}public void setUserService(UserService userService) {this.userService = userService;}public Map<String, Object> getDataMap() {return dataMap;}public void setDataMap(Map<String, Object> dataMap) {this.dataMap = dataMap;}}

把要返回的状态数据放到map里面并生成get set方法,这里struts2会自动把以get开头的方法序列化成json数据,不需要的就在前面加上注解@JSON(serialize=false),表示不会转成json,在struts.xml做如下配置
<struts><package name="json"  extends="struts-default,json-default"><action name="user" class="userAction"><result name="main" type="json"><param name="root">dataMap</param>  </result><result name="index" type="json"><param name="root">dataMap</param>  </result></action></package></struts>

这里name="root"表示从根节点开始, 要返回的json数据在dataMap中

0 0
原创粉丝点击