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

发布时间 - 2026-01-11 03:25:44    点击率:

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>

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


# EasyUI框架  # 使用Ajax提交注册信息  # EasyUI  # Ajax提交注册的实现方法  # MVC+EasyUI+三层架构简单权限管理系统  # jquery easyui 结合jsp简单展现table数据示例  # 12个常用前端UI框架集合汇总  # SSM框架整合JSP中集成easyui前端ui项目开发示例详解  # 为空  # 拦截器  # 如有  # 每页  # 希望能  # 自定义  # 谢谢大家  # 转化为  # 跳转到  # 注册成功  # 疑问请  # ModelDriven  # DepartmentService  # ForumService  # oa  # service  # oppo  # UserService  # StudentService  # fastjson 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 如何在IIS中配置站点IP、端口及主机头?  原生JS获取元素集合的子元素宽度实例  七夕网站制作视频,七夕大促活动怎么报名?  Laravel如何处理CORS跨域请求?(配置示例)  Laravel如何理解并使用服务容器(Service Container)_Laravel依赖注入与容器绑定说明  再谈Python中的字符串与字符编码(推荐)  移动端脚本框架Hammer.js  微信小程序 wx.uploadFile无法上传解决办法  专业商城网站制作公司有哪些,pi商城官网是哪个?  INTERNET浏览器怎样恢复关闭标签页_INTERNET浏览器标签恢复快捷键与方法【指南】  高防服务器如何保障网站安全无虞?  Laravel如何创建自定义Facades?(详细步骤)  如何快速打造个性化非模板自助建站?  Win11摄像头无法使用怎么办_Win11相机隐私权限开启教程【详解】  Laravel Sail是什么_基于Docker的Laravel本地开发环境Sail入门  Laravel怎么解决跨域问题_Laravel配置CORS跨域访问  香港服务器网站搭建教程-电商部署、配置优化与安全稳定指南  中山网站制作网页,中山新生登记系统登记流程?  如何在景安服务器上快速搭建个人网站?  如何在万网利用已有域名快速建站?  Python结构化数据采集_字段抽取解析【教程】  实现点击下箭头变上箭头来回切换的两种方法【推荐】  韩国网站服务器搭建指南:VPS选购、域名解析与DNS配置推荐  如何在不使用负向后查找的情况下匹配特定条件前的换行符  MySQL查询结果复制到新表的方法(更新、插入)  Laravel如何实现用户角色和权限系统_Laravel角色权限管理机制  Laravel如何使用模型观察者?(Observer代码示例)  大连网站制作公司哪家好一点,大连买房网站哪个好?  如何在景安云服务器上绑定域名并配置虚拟主机?  bootstrap日历插件datetimepicker使用方法  如何获取PHP WAP自助建站系统源码?  详解Android——蓝牙技术 带你实现终端间数据传输  如何用狗爹虚拟主机快速搭建网站?  nodejs redis 发布订阅机制封装实现方法及实例代码  如何快速查询域名建站关键信息?  独立制作一个网站多少钱,建立网站需要花多少钱?  Laravel Admin后台管理框架推荐_Laravel快速开发后台工具  Laravel控制器是什么_Laravel MVC架构中Controller的作用与实践  如何用好域名打造高点击率的自主建站?  EditPlus中的正则表达式 实战(4)  jquery插件bootstrapValidator表单验证详解  香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化  详解Oracle修改字段类型方法总结  邀请函制作网站有哪些,有没有做年会邀请函的网站啊?在线制作,模板很多的那种?  如何在腾讯云服务器快速搭建个人网站?  Laravel如何清理系统缓存命令_Laravel清除路由配置及视图缓存的方法【总结】  Python文本处理实践_日志清洗解析【指导】  Google浏览器为什么这么卡 Google浏览器提速优化设置步骤【方法】  开心动漫网站制作软件下载,十分开心动画为何停播?  Laravel如何使用Sanctum进行API认证?(SPA实战)