溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

EasyUI框架 使用Ajax提交注冊信息的實(shí)現(xiàn)代碼

發(fā)布時間:2020-09-11 06:53:57 來源:腳本之家 閱讀:118 作者:CharlinGod 欄目:web開發(fā)

EasyUI框架 使用Ajax提交注冊信息的實(shí)現(xiàn)代碼

一、服務(wù)器代碼:

@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;// 每頁顯示的記錄數(shù)
  private String page;// 當(dāng)前第幾頁
  private Map<String, Object> josnMap = new HashMap<>();

  // 查詢出所有學(xué)生信息
  public String list() throws Exception {
    return "list";
  }

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

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

  // 轉(zhuǎn)化為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的實(shí)例
      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('驗(yàn)證失敗');
       }
    }); 
  </script>
</head>
<body class="easyui-layout">
  <div data-options="region:'north',split:true" >aa</div>
  <!-- <div data-options="region:'south',split:true" >bb</div>-->
  <div data-options="region:'east',title:'East',split:true" >cc</div> 
  <div data-options="region:'west',title:'West',split:true" >dd</div>
  <div data-options="region:'center',title:'center title'" >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:'確認(rèn)密碼不能為空',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>
  <!-- 配置為開發(fā)模式 -->
  <constant name="struts.devMode" value="true" />
  <!-- 配置擴(kuò)展名為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攔截器棧,需要先判斷權(quán)限 -->
      <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,當(dāng)與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>
      <!-- 跳轉(zhuǎn)到添加與修改頁面 -->
      <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>

如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI