EasyUI框架 使用Ajax提交注册信息的实现代码


Posted in Javascript onSeptember 27, 2017

EasyUI框架 使用Ajax提交注册信息的实现代码

一、服务器代码:

@Controller
@Scope("prototype")
public class StudentAction extends BaseAction<Student> {
  private static final long serialVersionUID = -2612140283476148779L;

  private Logger logger = Logger.getLogger(StudentAction.class);
  private String rows;// 每页显示的记录数
  private String page;// 当前第几页
  private Map<String, Object> josnMap = new HashMap<>();

  // 查询出所有学生信息
  public String list() throws Exception {
    return "list";
  }

  public String regUI() throws Exception {
    return "regUI";
  }

  // 查询出所有学生信息
  public String listContent() throws Exception {
    List<Student> list = studentService.getStudentList(page, rows);
    System.out.println("list==" + list);
    toBeJson(list, studentService.getStudentTotal());
    return "toJson";
  }

  // 转化为Json格式
  public void toBeJson(List<Student> list, int total) throws Exception {
    josnMap.put("total", total);
    josnMap.put("rows", list);
    JSONParser.writeJson(josnMap);// 自定义的工具类
  }

  public String reg(){
    logger.error("kkk");
    try {
      studentService.save(model);
      josnMap.put("success", true);
      josnMap.put("msg", "注册成功!");
    } catch (Exception e) {
      e.printStackTrace();
      josnMap.put("success", false);
      josnMap.put("msg", "注册失败!");
    }
    try {
      ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
      ServletActionContext.getResponse().setCharacterEncoding("utf-8");
      ServletActionContext.getResponse().getWriter().print(JSON.toJSONString(josnMap));
    } catch (IOException e) {
      e.printStackTrace();
    }

    return "toJson";
  }

  public void setRows(String rows) {
    this.rows = rows;
  }

  public void setPage(String page) {
    this.page = page;
  }

  public Map<String, Object> getJosnMap() {
    return josnMap;
  }

  public void setJosnMap(Map<String, Object> josnMap) {
    this.josnMap = josnMap;
  }



}

二、BaseAction代码:

import java.lang.reflect.ParameterizedType;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;

import cn.oppo.oa.service.DepartmentService;
import cn.oppo.oa.service.ForumService;
import cn.oppo.oa.service.PrivilegeService;
import cn.oppo.oa.service.RoleService;
import cn.oppo.oa.service.StudentService;
import cn.oppo.oa.service.UserService;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T> {

  /**
   * 
   */
  private static final long serialVersionUID = 1L;
  @Resource
  protected RoleService roleService;
  @Resource
  protected DepartmentService departmentService;
  @Resource
  protected UserService userService;
  @Resource
  protected PrivilegeService privilegeService;

  @Resource
  protected ForumService forumService;

  @Resource
  protected StudentService studentService;

  protected T model;

  @SuppressWarnings("unchecked")
  public BaseAction() {
    try {
      // 得到model的类型信息
      ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
      Class<T> clazz = (Class<T>) pt.getActualTypeArguments()[0];

      // 通过反射生成model的实例
      model = (T) clazz.newInstance();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public void writeJson(Object object){
    try {
      String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
      ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
      ServletActionContext.getResponse().setCharacterEncoding("utf-8");
      ServletActionContext.getResponse().getWriter().write(json);
      ServletActionContext.getResponse().getWriter().flush();
      ServletActionContext.getResponse().getWriter().close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public T getModel() {
    return model;
  }
}

三、页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
  <title>EasyUI框架</title>
  <%@ include file="/WEB-INF/jsp/public/common.jspf" %>
  <script type="text/javascript">
     $(function(){
       if(${"#easyui_regForm"}.form('validate')){
         $.ajax({
           url:'${pageContext.request.contextPath}/student_reg.action',
           data:${"#easyui_regForm"}.serialize(),
           dataType:'json',
           success:function(obj,status,jqXHR){
             if(obj.success){
               $("#easyui_regDialog").dialog('close');
             }
             $.message.show({
              title:'提示',
              msg:obj.msg
             });
           }
         });
       }else{
         alert('验证失败');
       }
    }); 
  </script>
</head>
<body class="easyui-layout">
  <div data-options="region:'north',split:true" style="height:100px;">aa</div>
  <!-- <div data-options="region:'south',split:true" style="height:100px;">bb</div>-->
  <div data-options="region:'east',title:'East',split:true" style="width:200px;">cc</div> 
  <div data-options="region:'west',title:'West',split:true" style="width:200px;">dd</div>
  <div data-options="region:'center',title:'center title'" style="padding:5px;background:#eee;">kk</div>

  <div class="easyui-dialog" data-options="title:'登陆', modal:true,
      closable:false,
      toolbar:[{
        text:'Edit',
        iconCls:'icon-edit',
        handler:function(){alert('edit')}
      },{
        text:'Help',
        iconCls:'icon-help',
        handler:function(){alert('help')}
      }],
      buttons:[{
        text:'登陆',
        handler:function(){alert('登陆')}
      },{
        text:'注册',
        handler:function(){
          $('#easyui_regForm input').val('');
          $('#easyui_regDialog').dialog('open');
        }
      }]" >
    <table>
      <tr>
        <td>登陆名称:</td>
        <td><input type="text" name="name"/></td>
      </tr>
      <tr>
        <td>登陆密码:</td>
        <td><input type="password" name="password"/></td>
      </tr>
    </table>
  </div>

  <div id="easyui_regDialog" class="easyui-dialog" data-options="title:'注册', modal:true,
      closable:true,
      closed:true,
      buttons:[{
        text:'注册',
        handler:function(){
          $('#easyui_regForm').form('submit',{
          url : '${pageContext.request.contextPath}/student_reg.action',
          success : function(data) {
            var obj = jQuery.parseJSON(data);
            if (obj.success) {
              $('#easyui_regDialog').dialog('close');
            }
            $.messager.show({
              title : '提示',
              msg : obj.msg
            });
          }
      });
        }
      },{
        text:'取消',
        handler:function(){alert('注册')}
      }]" >
    <form id="easyui_regForm" method="post">
    <table>
      <tr>
        <td>登陆名称:</td>
        <td><input type="text" name="loginName" class="easyui-validatebox" data-options="required:true,missingMessage:'用户名称不能为空'"/></td>
      </tr>
      <tr>
        <td>登陆密码:</td>
        <td><input id="reg_pwd" type="password" name="password" class="easyui-validatebox" data-options="required:true,missingMessage:'用户密码不能为空'"/></td>
      </tr>
      <tr>
        <td>确定密码:</td>
        <td><input type="password" name="repassword" class="easyui-validatebox" data-options="required:true,missingMessage:'确认密码不能为空',validType:'equals[\'#reg_pwd\']'" /></td>
      </tr>
    </table>
    </form>
  </div>
</body>
</html>

四、struts2.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>
  <!-- 配置为开发模式 -->
  <constant name="struts.devMode" value="true" />
  <!-- 配置扩展名为action -->
  <constant name="struts.action.extension" value="action" />
  <!-- 配置主题 -->
  <constant name="struts.ui.theme" value="simple" />

  <package name="default" namespace="/" extends="json-default">

    <interceptors>
      <!-- 声明一个拦截器 -->
      <interceptor name="checkePrivilege" class="cn.oppo.oa.interceptor.CheckPrivilegeInterceptor"></interceptor>

      <!-- 重新定义defaultStack拦截器栈,需要先判断权限 -->
      <interceptor-stack name="defaultStack">
        <interceptor-ref name="checkePrivilege" />
        <interceptor-ref name="defaultStack" />
      </interceptor-stack>
    </interceptors>


    <!-- 配置全局的Result -->
    <global-results>
      <result name="loginUI">/WEB-INF/jsp/user/loginUI.jsp</result>
      <result name="noPrivilegeError">/noPrivilegeError.jsp</result>
    </global-results>


    <!-- 测试用的action,当与Spring整合后,class属性写的就是Spring中bean的名称 -->
    <action name="test" class="testAction">
      <result name="success">/test.jsp</result>
    </action>


    <action name="*_*" class="{1}Action" method="{2}">
      <result name="{2}">/WEB-INF/jsp/{1}/{2}.jsp</result>
      <!-- 跳转到添加与修改页面 -->
      <result name="saveUI">/WEB-INF/jsp/{1}/saveUI.jsp</result>
      <!-- 返回list页 -->
      <result name="toList" type="redirectAction">{1}_list?parentId=${parentId}</result>
      <!-- 返回主页 -->
      <result name="toIndex" type="redirect">/index.jsp</result>
      <!-- 返回论坛主题 -->
      <result name="toShow" type="redirectAction">topic_show?id=${id}</result>
      <result name="toTopicShow" type="redirectAction">topic_show?id=${topicId}</result>
      <!-- json解析 -->
      <result name="toJson" type="json">
        <param name="root">josnMap</param>
      </result>

      <result name="reg">/easyui.jsp</result>


    </action>

  </package>

</struts>

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Javascript 相关文章推荐
jquery实现图片左右间隔滚动特效(可自动播放)
May 08 Javascript
setInterval()和setTimeout()的用法和区别示例介绍
Nov 17 Javascript
javascript将相对路径转绝对路径示例
Mar 14 Javascript
JavaScript数字和字符串转换示例
Mar 26 Javascript
jQuery简单实现QQ空间点赞已经取消点赞
Apr 02 Javascript
JavaScript里实用的原生API汇总
May 14 Javascript
js文字横向滚动特效
Nov 11 Javascript
AngularJS中run方法的巧妙运用
Jan 04 Javascript
javascript监听页面刷新和页面关闭事件方法详解
Jan 09 Javascript
React组件内事件传参实现tab切换的示例代码
Jul 04 Javascript
js+springMVC 提交数组数据到后台的实例
Sep 21 Javascript
vue.js watch经常失效的场景与解决方案
Jan 07 Vue.js
angular内置provider之$compileProvider详解
Sep 27 #Javascript
详解Node.js利用node-git-server快速搭建git服务器
Sep 27 #Javascript
微信小程序 循环及嵌套循环的使用总结
Sep 26 #Javascript
Node.js dgram模块实现UDP通信示例代码
Sep 26 #Javascript
深入理解ES6 Promise 扩展always方法
Sep 26 #Javascript
微信小程序开发之IOS和Android兼容的问题
Sep 26 #Javascript
Thinkphp5微信小程序获取用户信息接口的实例详解
Sep 26 #Javascript
You might like
Yii2框架数据验证操作实例详解
2018/05/02 PHP
PHP基于pdo的数据库操作类【可支持mysql、sqlserver及oracle】
2018/05/21 PHP
定义select的边框颜色
2008/04/28 Javascript
csdn 博客的css样式 v3
2009/02/24 Javascript
JavaScript中出现乱码的处理心得
2009/12/24 Javascript
js String对象中常用方法小结(字符串操作)
2012/01/27 Javascript
JavaScript简介
2015/02/15 Javascript
jQuery插件zoom实现图片全屏放大弹出层特效
2015/04/15 Javascript
实例讲解js验证表单项是否为空的方法
2016/01/09 Javascript
vue-router 路由基础的详解
2017/10/17 Javascript
深入浅出vue图片路径的实现
2019/09/04 Javascript
Typescript的三种运行方式(小结)
2019/09/18 Javascript
element-ui 实现响应式导航栏的示例代码
2020/05/08 Javascript
vue 路由meta 设置导航隐藏与显示功能的示例代码
2020/09/04 Javascript
[50:58]2018DOTA2亚洲邀请赛 4.1 小组赛 B组 Mineski vs EG
2018/04/03 DOTA
python实现根据用户输入从电影网站获取影片信息的方法
2015/04/07 Python
在Python中处理字符串之isdecimal()方法的使用
2015/05/20 Python
python 获取指定文件夹下所有文件名称并写入列表的实例
2018/04/23 Python
详解Python字典小结
2018/10/20 Python
Python telnet登陆功能实现代码
2020/04/16 Python
Python常用外部指令执行代码实例
2020/11/05 Python
REN Clean Skincare官网:英国本土有机护肤品牌
2019/02/23 全球购物
阿联酋手表和配饰购物网站:Rivolishop
2019/11/25 全球购物
纯净、自信、100%的羊绒服装:360Cashmere
2021/02/20 全球购物
建筑公司文秘岗位职责
2013/11/29 职场文书
中学生期末评语
2014/02/03 职场文书
医疗器械售后服务承诺书
2014/05/21 职场文书
护理专业自荐书
2014/06/04 职场文书
小学运动会班级口号
2014/06/09 职场文书
慈善捐赠倡议书
2014/08/30 职场文书
2014年党员自我评议对照检查材料
2014/09/20 职场文书
质量保证书怎么写
2015/02/27 职场文书
高中体育课教学反思
2016/02/16 职场文书
2016年“我们的节日·清明节”活动总结
2016/04/01 职场文书
解决Goland 同一个package中函数互相调用的问题
2021/05/06 Golang
Java Socket实现多人聊天系统
2021/07/15 Java/Android