关于Struts传递json给easyui的随笔
今天在公司写测试代码,由于公司用的是ssh框架做的商城项目,我想先实现下简单的增删改查,奈何没有很好的后台页面(毕竟不能测试代码直接在他的项目里改啊)
所以想到了淘淘商城中有这个后台的管理页面,打算一试,奈何struts没学好,琢磨好几小时如何把json数据回传给easyui的页面,这里还是推荐大家用谷歌
后台页面使用的是easyui,直接放其中Customer添加页面和后台action的代码吧
customer-add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<link
href="${fileUrlConfig.fileServiceUploadRoot}/zcg/js/kindeditor-4.1.10/themes/default/default.css"
type="text/css" rel="stylesheet">
<script type="text/javascript" charset="utf-8"
src="${fileUrlConfig.fileServiceUploadRoot}/zcg/js/kindeditor-4.1.10/kindeditor-all-min.js"></script>
<script type="text/javascript" charset="utf-8"
src="${fileUrlConfig.fileServiceUploadRoot}/zcg/js/kindeditor-4.1.10/lang/zh_CN.js"></script>
<div style="padding:10px 10px 10px 10px">
<!-- 这是个需要提交的表单,可以用来增加商品 -->
<form id="itemAddForm" class="itemForm" method="post">
<table cellpadding="5">
<!-- <tr>
<td>商品类目:</td>
<td>
<a href="javascript:void(0)" class="easyui-linkbutton selectItemCat">选择类目</a>
<input type="hidden" name="cid" style="width: 280px;"></input>
</td>
</tr> -->
<tr>
<td>登录用户名:</td>
<td><input class="easyui-textbox" type="text" name="loginName"
data-options="required:true" style="width: 280px;"></input></td>
</tr>
<tr>
<td>用户密码:</td>
<td><input class="easyui-textbox" type="password"
name="password" data-options="required:true" style="width: 280px;"></input></td>
</tr>
<tr>
<td>昵称:</td>
<td><input class="easyui-textbox" type="text" name="nickName"
data-options="required:true" style="width: 280px;"></input></td>
</tr>
<tr>
<td>手机号:</td>
<td><input class="easyui-textbox" type="text" name="phone"
data-options="required:true" style="width: 280px;"></input></td>
</tr>
<tr>
<td>邮箱:</td>
<td><input class="easyui-textbox" type="text" name="email"
data-options="required:true" style="width: 280px;"></input></td>
</tr>
<tr>
<td>头像地址:</td>
<td><input class="easyui-textbox" type="text" name="photoUrl"
data-options="required:true" style="width: 280px;"></input></td>
</tr>
<!-- <tr>
<td>上传头像:</td>
<td><a href="javascript:void(0)"
class="easyui-linkbutton picFileUpload">上传图片</a> <input
type="hidden" name="image" /></td>
</tr> -->
<tr>
<td style="text-align:left;">会员类型:</td>
<td style="text-align:left">
<span class="radioSpan">
<input type="radio" name="type" value="1">采购商</input>
<input type="radio" name="type" value="2">供应商</input>
</span>
</td>
</tr>
<tr>
<td style="text-align:left;">分享类型:</td>
<td style="text-align:left">
<span class="radioSpan">
<input type="radio" name="shareType" value="1">普通会员</input>
<input type="radio" name="shareType" value="2">超级终端</input>
<input type="radio" name="shareType" value="3">个人分销商</input>
<input type="radio" name="shareType" value="4">县市分销商</input>
<input type="radio" name="shareType" value="5">省级分销商</input>
<input type="radio" name="shareType" value="6">操盘手(店铺代运营)</input> </span>
</td>
</tr>
<tr>
<td style="text-align:left;">商品交易状态:</td>
<td style="text-align:left">
<span class="radioSpan">
<input type="radio" name="isCanBuy" value="1">可以采购</input>
<input type="radio" name="isCanBuy" value="2">不采购</input>
</span>
</td>
</tr>
<tr>
<td>支付密码:</td>
<td><input class="easyui-textbox" type="password"
name="payPassword" data-options="required:true" style="width: 280px;"></input></td>
</tr>
<tr>
<td>微信公众号:</td>
<td><input class="easyui-textbox" type="text" name="openid"
data-options="required:true" style="width: 280px;"></input></td>
</tr>
</table>
<input type="hidden" name="itemParams" />
</form>
<div style="padding:5px">
<a href="javascript:void(0)" class="easyui-linkbutton"
onclick="submitForm()">提交</a> <a href="javascript:void(0)"
class="easyui-linkbutton" onclick="clearForm()">重置</a> </div>
</div>
<script type="text/javascript">
//提交表单
function submitForm() {
debugger;
//有效性验证
if (!$('#itemAddForm').form('validate')) {
$.messager.alert('提示', '表单还未填写完成!');
return;
}
$.post("/zcg/customersave.action", $("#itemAddForm").serialize(), function(data) {
if (data.status == 200) {
$.messager.alert('提示', '新增用户成功!');
}
});
} function clearForm() {
$('#itemAddForm').form('reset');
itemAddEditor.html('');
}
</script>
如上述代码可见,我这里使用了ajax提交了表单之后等待后台回传个带有状态码的json数据,这样就能调用easyui页面中的ajax响应弹窗,从而完成交互
但是在网上查了好久都没找到几个靠谱的方法,要么讲的太乱……
action的代码
package shop.hellxz.action; import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map; import javax.json.Json; import org.apache.struts2.json.JSONUtil;
import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import cn.emay.slf4j.helpers.Util;
import shop.zhangchenguang.pojo.Customer2;
import shop.zhangchenguang.service.CustomerService;
import util.action.BaseAction;
import util.other.Utils; /**
* 测试代码Action
* @author Hellxz
*
*/
public class CustomerAction extends BaseAction{ //注入service层
private CustomerService customerServiceImpl;
//需要写get、set方法
public CustomerService getCustomerServiceImpl() {
return customerServiceImpl;
}
public void setCustomerServiceImpl(CustomerService customerServiceImpl) {
this.customerServiceImpl = customerServiceImpl;
}
//跳转到主页
public String index() throws IOException{
return "success";
}
//保存用户信息
public void customerSave() throws IOException{
//获取输出流
response.setContentType("json/application;charset=UTF-8");
PrintWriter out = response.getWriter();
//获取传入数据对象
Customer2 customer = new Customer2();
customer.setLoginName(request.getParameter("loginName"));
customer.setPassword(request.getParameter("password"));
customer.setNickName(request.getParameter("nickName"));
customer.setPhone(request.getParameter("phone"));
customer.setEmail(request.getParameter("email"));
customer.setPhotoUrl(request.getParameter("photoUrl"));
customer.setType(Integer.parseInt(request.getParameter("type")));
customer.setShareType(Integer.parseInt(request.getParameter("shareType")));
customer.setIsCanBuy(Integer.parseInt(request.getParameter("isCanBuy")));
customer.setPayPassword(request.getParameter("payPassword"));
customer.setOpenId(request.getParameter("openid"));
//补全数据……还没写
//调用service保存对象
Object obj = customerServiceImpl.saveOrUpdateObject(customer);
/**
* 如果保存的对象是非空的,那么已经保存成功
* 如果为空,则保存失败
* 无论保存成功那个与否,都要把json对象写回给客户端,进行判断
*/
if(Utils.objectIsNotEmpty(obj)){
out.println(JSON.toJSONString(checkOK()));
}else{
out.println(JSON.toJSONString(checkFail()));
}
}
/**
* @return json对象状态200
*/
@SuppressWarnings({"unchecked","rawtypes"})
public Object checkOK(){
Map m = new HashMap<>();
m.put("status", 200);
m.put("msg", "添加成功");
m.put("data", null);
return m;
}
/**
* @return json对象状态500
*/
@SuppressWarnings({"unchecked","rawtypes"})
public Object checkFail(){
Map m = new HashMap<>();
m.put("status", 500);
m.put("msg", "添加失败");
m.put("data", null);
return m;
} }
附上struts的配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="zcg" namespace="/zcg" extends="basePackage">
<action name="index" class="shop.hellxz.action.CustomerAction" method="index">
<interceptor-ref name="baseStack"/>
<result name="success">/WEB-INF/hellxz/jsp/index.jsp</result>
</action>
<action name="*-*" class="shop.hellxz.action.SendAction">
<result name="send">/WEB-INF/hellxz/jsp/{1}-{2}.jsp</result>
</action>
<action name="customersave" class="shop.hellxz.action.CustomerAction" method="customerSave"> </action>
</package>
</struts>
到这里大家可能明白是怎么实现的了,老规矩捋一下流程:
1、在struts配置文件中让表单提交的请求响应到action中,不需要定义result,
2、响应进来之后,我们定义的方法需要设置void返回值,在方法体就可以通过老办法 request.getParameter()方法获取这些表单中的参数,然后放到pojo中持久化
3、持久化成功会返回一个新的对象,判断这个对象是否为空,然后通过这个结果来对应应该用到的检查方法,这里使用了alibaba的Fastjson中的JSON对象的toJsonString()方法来实现把对象转换成json串
4、通过response.getWriter()方法拿到的输出流,我们使用println()方法打印出来那个json串给浏览器端
5、浏览器端的ajax收到带有状态码200的json串,弹窗提示用户存储成功
说着简单,其实就是jsp和servlet时候常用的方法,springmvc用习惯了,反而忘了最基本的方法,罪过罪过。
关于Struts传递json给easyui的随笔的更多相关文章
- 用easyui从servlet传递json数据到前端页面的两种方法
用easyui从servlet传递json数据到前端页面的两种方法 两种方法获取的数据在servlet层传递的方法相同,下面为Servlet中代码,以查询表中所有信息为例. //重写doGet方法 p ...
- Struts的JSON机制
需要加入jar包 Struts的JSON帮助我们自动将对象解析为JSON对象,不用我门借助第三方进行JSON的解析 .具体的使用机制如下: 1.Action类 package StrutsJSON; ...
- 《项目经验》--通过js获取前台数据向一般处理程序传递Json数据,并解析Json数据,将前台传来的Json数据写入数据库表中
先看一下我要实现的功能界面: 这个界面的功能在图中已有展现,课程分配(教师教授哪门课程)在之前的页面中已做好.这个页面主要实现的是授课,即给老师教授的课程分配学生.此页面实现功能的步骤已在页面 ...
- 通过js获取前台数据向一般处理程序传递Json数据,并解析Json数据,将前台传来的Json数据写入数据库表中
摘自:http://blog.csdn.net/mazhaojuan/article/details/8592015 通过js获取前台数据向一般处理程序传递Json数据,并解析Json数据,将前台传来 ...
- jQuery调用WCF服务传递JSON对象
下面这个示例使用了WCF去创建一个服务端口从而能够被ASP.Net页面通过jQuery的AJAX方法访问,我们将在客户端使用Ajax技术来 与WCF服务进行通信.这里我们仅使用jQuery去连接Web ...
- Jquery调用Webservice传递Json数组
Jquery由于提供的$.ajax强大方法,使得其调用webservice实现异步变得简单起来,可以在页面上传递Json字符串到Webservice中,Webservice方法进行业务处理后,返回Js ...
- WebApi传递JSON参数
开发过程中经常进行JSON的传递,在WebApi中传递JSON字串时,会发现服务器端接收到不参数值,看下面代码 服务端: public void Post([FromBody]string value ...
- 从Python传递JSON到JavaScript
OS: Windows 8.1 with update 关键字:Python 3.4,HTML5,JSON,JavaScript 1.LocalServer.py,启动server,打开网页,传递JS ...
- Jquery Ajax方法传递json到action
ajax向后台传入json需要设置option,如下 contentType:'application/json' data:Json.Stringify(jsObj) 后台处理复杂json对象(不知 ...
随机推荐
- 关于模拟登陆微博(PC)
微博模拟登陆 1.基类对象的方法建立一个类__init__初始化方法,接收username和password. class launcher(): def __init__(self, usernam ...
- Sql Server中的nvarchar(n)和varchar(n)
刚才有幸看了下 nvarchar(n)和varchar(n),感觉以前的认知有误. nvarchar(n):n指的是字符个数,范围是1-4000,存储的是可变长度的Unicode字符数据. 按字符存储 ...
- Asp,NET控制文件上传的大小
在web.config中的system.web 节点下添加如下代码: 第2行的maxRequestLength="8192",这里限制最大为8MB,可以自行设置.execution ...
- 用C#实现微信“跳一跳”小游戏的自动跳跃助手
一.前言: 前段时间微信更新了新版本后,带来的一款H5小游戏“跳一跳”在各朋友圈里又火了起来,类似以前的“打飞机”游戏,这游戏玩法简单,但加上了积分排名功能后,却成了“装逼”的地方,于是很多人花钱花时 ...
- lambda 与内置函数,以及一些补充
插播几条小知识: 1. lambda 表达式 对于简单的函数,我们可以用 lamdba 表达式来执行,一句话就够用
- 一个IC软件工程师的2017年终工作总结
相比2016年的波澜起伏,2017多了一份平静和清淡.不过,平静的生活下,总有一颗飞向远方的心. 在这一年将近结束的时候,总结一下自己的工作,生活和学习.也顺便展望一下未来的2018,看看有哪些 美好 ...
- Java内存分配以及GC
转自http://www.cnblogs.com/hnrainll/archive/2013/11/06/3410042.html 写的太棒了,简单易懂 Java垃圾回收概况 Java GC(Gar ...
- linux apache虚拟主机配置(基于ip,端口,域名)
配置环境: linux版本:Centos6.4 httpd版本: [root@centos64Study init.d]# pwd/etc/init.d[root@centos64Study init ...
- LeetCode第[16]题(Java):3Sum Closest 标签:Array
题目难度:Medium 题目: Given an array S of n integers, find three integers in S such that the sum is closes ...
- [译]Pandas常用命令对照清单
我们在内容中使用以下简写: df pandas的DataFrame对象 s pandas的Series对象 导入以下包开始 import pandas as pd import numpy as np ...