Jquery、 ajax和struts2+Hibernate查詢資料庫驗證使用者名稱是否存在,表單禁止提交等!

來源:互聯網
上載者:User

最近學習了ajax的非同步呼叫和重新整理技術,就實踐了一把。也借鑒了別人的方法,再加入自己的思路,就有了下面的東東```有任何疑問,就留言吧````

首先是前台的jsp頁面

關於jquery的post方法大家可以去看看這個,寫的很詳細:http://www.itivy.com/jquery/archive/2011/7/6/jquery-get-post-getjson-ajax.html

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib uri="/struts-tags" prefix="s"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'register.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><script type="text/javascript" src="jquery-1.9.1.js"></script>//引進Jquery庫 <script type="text/javascript">       jQuery(function()    {          $("#username").blur(function()        {              var username= $.trim($("#username").val());               $.post("checkusername.action",{username:username},function(date,state)        {           if(date.result=="ok")           {           $("#span1").html("<font color=\"red\">使用者名稱可以使用</font>");           document.getElementById("submit").removeAttribute("disabled");                      }else           {           $("#span1").html("<font color=\"red\">使用者名稱不可以使用</font>");           document.getElementById("submit").disabled = "true";            }                      //alert(date.result);警告不好看,太嚇人了                return false;},'json');          });    });       </script>    </head>    <body>   <form action="savePerson.action" method="post" >        username:<input type="text" name="username" size="20" id="username">    <span id="span1"></span>      <br>        password:<input type="password" name="password" size="20"><br>    age: <input type="text" name="age" size="20"><br>        <input type="submit" value="提交" id="submit"  disabled="disabled">                         </form>     </body></html>

因為是使用的是struts2架構所以struts2裡面加上如下代碼:因為資料是採用接送傳輸的所以要寫成extends="json-default"

<package name="strutsjson" extends="json-default">          <action name="checkusername"         class="com.liumin.action.CheckUsername"  method="CheckPerson">               <result type="json"></result>          </action>      </package>  

action裡面的代碼如下

 

 

package com.liumin.action;import java.util.List;import com.liumin.model.Person;import com.liumin.service.impl.CheckService;import com.opensymphony.xwork2.ActionSupport;public class CheckUsername extends ActionSupport{private String username;//前台傳來的資料usernamepublic String getUsername(){return username;}public void setUsername(String username){this.username = username;}private String result; public String getResult(){return result;}public void setResult(String result){this.result = result;}public String CheckPerson() throws Exception{CheckService checkService = new CheckService();String str="select * from person where username='"+username+"'" ;//組建sql語句    List<Person> list=(List<Person>)checkService.getUser(str);//取得資料    if(list.isEmpty())//安條件查詢後,判斷list是否為空白?{         this.result = "ok"; }else{             this.result = "no";}        return SUCCESS;}}

service和dao層的我寫到了一塊:

 

package com.liumin.service.impl;import java.util.List;import org.hibernate.Session;import org.hibernate.Transaction;import com.liumin.model.Person;import com.liumin.util.HibernateUtil;public class CheckService{@SuppressWarnings("unchecked")public List<Person> getUser(String str){Session session = HibernateUtil.openSession();Transaction tx = session.beginTransaction();List<Person> list = null;try{list = session.createSQLQuery(str).addEntity(Person.class).list();//查詢資料tx.commit();}catch (Exception e){if (null != tx){tx.rollback();}}finally{HibernateUtil.close(session);}return list;}}

util裡面的資料如下:

 

 

package com.liumin.util;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil{private static SessionFactory sessionFactory;static{try{sessionFactory = new Configuration().configure().buildSessionFactory();}catch (Exception ex){ex.printStackTrace();}}public static Session openSession(){Session session = sessionFactory.openSession();return session;}public static void close(Session session){if(null != session){session.close();}}}

Hibernate的cfg和hbm代碼就不用貼出來了!

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.