欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-06 21:22:56
easyui框架 使用ajax提交注册信息的实现代码 一、服务器代码: @controller @scope("prototype") public cla...

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>

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