---
title: "Extjs登录（用到DB）"
author: "piperzero"
date: "2013-02-20T16:30:00Z"
tags: []
slug: "extjs-db"
draft: false
lastmod: "2013-02-21T19:57:10Z"
id: 1811737
url: "https://piperzero.iteye.com/blog/1811737"
---

这是第一次用Extjs ，肯定很多漏洞，写给自己的，万一忘记了。。 演示-------------如下：

![](http://img.my.csdn.net/uploads/201211/07/1352257733_4229.png)

**\[plain]** [view plain](http://blog.csdn.net/shutingwang/article/details/6691205 "view plain")[copy](http://blog.csdn.net/shutingwang/article/details/6691205 "copy")[print](http://blog.csdn.net/shutingwang/article/details/6691205 "print")[?](http://blog.csdn.net/shutingwang/article/details/6691205 "?")

001. Extjs版本：3.3.0
002. 1建表
003. useBarcode
004. /\*(此表為了測試自己添加)
005. EL\_User:表名
006. Id自動增長類型的主鍵
007. UserName用戶名
008. Password密碼
009. NickName昵稱
010. Level級別（普通用戶或管理員）
011. \*/
012. droptableEL\_User
013. createtableEL\_User(
014. Idintidentity(1,1)primarykey,
015. UserNamenvarchar(30),
016. Passwordnvarchar(20),
017. NickNamenvarchar(30),
018. Levelint
019. )
020. insertintoEL\_Uservalues('舒婷','123456','微笑釋懷',1)--level級別0代表普通用戶，1
021. 代表高級用戶
022. insertintoEL\_Uservalues('Tom','123123','BigMan',0)
023. insertintoEL\_Uservalues('dog','111111','玫瑰男人',0)
024. 2登录界面login.jsp
025. &lt;%@pagelanguage="java"import="java.util.\*"pageEncoding="UTF-8"%&gt;
026. &lt;%
027. Stringpath=request.getContextPath();
028. StringbasePath=request.getScheme()+"://"+request.getServerName
029. ()+":"+request.getServerPort()+path+"/";
030. %&gt;
031. &lt;!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"&gt;
032. &lt;html&gt;
033. &lt;head&gt;
034. &lt;basehref="&lt;%=basePath%&gt;"&gt;
035. &lt;metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"&gt;
036. &lt;metahttp-equiv="description"content="thisismypage"&gt;
037. &lt;metahttp-equiv="content-type"content="text/html;charset=UTF-8"&gt;
038. &lt;linkrel="stylesheet"type="text/css"href="Extjs/3.3.0/resources/css/ext-
039. all.css"/&gt;
040. &lt;scripttype="text/javascript"src="Extjs/3.3.0/adapter/ext/ext-base.js"&gt;&lt;/script&gt;
041. &lt;scripttype="text/javascript"src="Extjs/3.3.0/ext-all.js"&gt;&lt;/script&gt;
042. &lt;scripttype="text/javascript"&gt;
043. Ext.onReady(function(){
044. Ext.QuickTips.init();
045. Ext.form.Field.prototype.msgTarget="qtip";
046. varloginform=newExt.form.FormPanel({
047. renderTo:'container',
048. title:'用戶登陆',
049. labelSeparator:":",
050. collapsible:true,
051. width:300,
052. height:150,
053. id:'login',
054. labelWidth:80,
055. bodyStyle:'padding:5px5px00',
056. border:false,
057. name:'login',
058. frame:true,
059. defaults:{width:178,xtype:'textfield'},
060. items:[
061. newExt.form.TextField({
062. frame:true,
063. fieldLabel:"用户名",
064. name:'userName',
065. allowBlank:false,
066. blankText:'用户名不能为空'
067. }),{
068. fieldLabel:"密码",
069. name:'password',
070. allowBlank:false,
071. inputType:'password',
072. blankText:'密码不能为空'
073. }],
074. keys:{
075. key:13,
076. fn:login
077. },
078. buttons:[{
079. text:'提交',
080. handler:login
081. },{
082. text:'重置',
083. handler:functionreset(){
084. loginform.form.reset();
085. }
086. }]
087. });
088. functionlogin(){
089. varform=Ext.getCmp("login").getForm();
090. form.submit({
091. //clientValidation:true,
092. url:"/Env\_1/BarCode/selectUser.action",
093. params:{
094. },
095. success:function(form,action){
096. Ext.Msg.alert('Success',"恭喜，登陆成功！");
097. location.href='index.jsp';
098. },
099. failure:function(form,action){
100. switch(action.failureType){
101. caseExt.form.Action.CLIENT\_INVALID:
102. Ext.Msg.alert('Failure','Formfieldsmaynotbesubmittedwith
103. invalidvalues');
104. break;
105. caseExt.form.Action.CONNECT\_FAILURE:
106. Ext.Msg.alert('Failure','Ajaxcommunicationfailed');
107. break;
108. caseExt.form.Action.SERVER\_INVALID:
109. Ext.Msg.alert('Failure',"您的输入有误，请核实后重新输入");
110. loginform.form.reset();
111. }
112. }
113. });
114. }
115. })
116. &lt;/script&gt;
117. &lt;/head&gt;
118. &lt;body&gt;
119. &lt;divid="outer"align="center"&gt;
120. &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;
121. &lt;divid="container"&gt;&lt;/div&gt;
122. &lt;/div&gt;
123. &lt;/body&gt;
124. &lt;/html&gt;
125. 3Model下的EL\_User.java（实体类）
126. packagecom.barcode.Model;
127. importjavax.persistence.Column;
128. importjavax.persistence.Entity;
129. importjavax.persistence.Id;
130. importjavax.persistence.Table;
131. @Entity
132. @Table(name="EL\_User")
133. publicclassEL\_User{
134. privateintId;
135. privateStringUserName;
136. privateStringPassword;
137. privateStringNickName;
138. privateintlevel;
139. @Id
140. @Column(name="Id")
141. publicintgetId(){
142. returnId;
143. }
144. publicvoidsetId(intid){
145. Id=id;
146. }
147. @Column(name="UserName")
148. publicStringgetUserName(){
149. returnUserName;
150. }
151. publicvoidsetUserName(StringuserName){
152. UserName=userName;
153. }
154. @Column(name="Password")
155. publicStringgetPassword(){
156. returnPassword;
157. }
158. publicvoidsetPassword(Stringpassword){
159. Password=password;
160. }
161. @Column(name="NickName")
162. publicStringgetNickName(){
163. returnNickName;
164. }
165. publicvoidsetNickName(StringnickName){
166. NickName=nickName;
167. }
168. @Column(name="Level")
169. publicintgetLevel(){
170. returnlevel;
171. }
172. publicvoidsetLevel(intlevel){
173. this.level=level;
174. }
175. }
176. dao层
177. @Repository
178. publicclassELLoginDao{
179. privateHibernateTemplatehibernateTemplate;
180. @SuppressWarnings("unused")
181. @Autowired
182. privatevoidsetHibernateTemplate(SessionFactorysessionFactory){
183. this.hibernateTemplate=newHibernateTemplate(sessionFactory);
184. }
185. @SuppressWarnings("unchecked")
186. publicListisHaveUser(Stringusername,Stringpassword){
187. Stringhql="fromELUseruwhereu.userName='"+username+"'and
188. u.password='"+password+"'";
189. System.out.println("hql"+hql);
190. returnthis.hibernateTemplate.find(hql);
191. }
192. }
193. 4service层
194. packagecom.barcode.Service;
195. importjava.util.Iterator;
196. importjava.util.List;
197. importorg.springframework.beans.factory.annotation.Autowired;
198. importorg.springframework.stereotype.Service;
199. importorg.springframework.transaction.annotation.Transactional;
200. importcom.barcode.DAO.EL\_UserDAO;
201. importcom.barcode.Model.EL\_User;
202. @Service
203. publicclassEL\_UserService{
204. @SuppressWarnings("unused")
205. privateEL\_UserDAOel\_UserDAO;
206. @Autowired
207. publicvoidsetEl\_UserDAO(EL\_UserDAOel\_UserDAO){
208. this.el\_UserDAO=el\_UserDAO;
209. }
210. @Transactional("barcode")
211. publicbooleanselectUser(Stringusername,Stringpassword){
212. List&lt;EL\_User&gt;list=this.el\_UserDAO.selectUser(username,password);
213. if(list.size()==0){
214. returnfalse;
215. }else{
216. returntrue;
217. }
218. }
219. }
220. 5web层
221. packagecom.barcode.Web;
222. importjava.util.Enumeration;
223. importjava.util.HashMap;
224. importjava.util.Map;
225. importjavax.servlet.http.HttpServletRequest;
226. importorg.springframework.beans.factory.annotation.Autowired;
227. importorg.springframework.stereotype.Controller;
228. importorg.springframework.web.bind.annotation.ModelAttribute;
229. importorg.springframework.web.bind.annotation.RequestMapping;
230. importorg.springframework.web.bind.annotation.ResponseBody;
231. importcom.barcode.Model.EL\_User;
232. importcom.barcode.Service.EL\_UserService;
233. @Controller
234. publicclassEL\_UserController{
235. privateEL\_UserServiceel\_UserService;
236. @Autowired
237. publicvoidsetEl\_UserService(EL\_UserServiceel\_UserService){
238. this.el\_UserService=el\_UserService;
239. }
240. @ModelAttribute("user")
241. publicEL\_UserformbackObject(Integerid,HttpServletRequestrequest)throws
242. Exception{
243. //獲得更改的各項屬性
244. Enumerationenumeration=request.getParameterNames();
245. System.out.println(enumeration.hasMoreElements());
246. while(enumeration.hasMoreElements()){
247. StringparamName=(String)enumeration.nextElement();
248. System.out.println("requestparameter\["+paramName+"]="+
249. request.getParameter(paramName));
250. }
251. EL\_Useruser=null;
252. if(id!=null&&id!=0){
253. //ug=us.getUsefulGroup(id);
254. }else{
255. user=newEL\_User();
256. }
257. returnuser;
258. }
259. @SuppressWarnings("unchecked")
260. @RequestMapping(value="BarCode/selectUser.action")
261. public@ResponseBodyMap&lt;String,?extendsObject&gt;selectUser(@ModelAttribute
262. ("user")EL\_Useruser,HttpServletRequestrequest){
263. System.out.println(user.getUserName());
264. System.out.println(user.getPassword());
265. Stringusername=user.getUserName();
266. Stringpassword=user.getPassword();
267. booleanboo=this.el\_UserService.selectUser(username,password);
268. Mapmap=newHashMap&lt;String,Object&gt;();
269. if(boo){
270. map.put("data",user);
271. map.put("success",true);
272. map.put("message","Youaresuccessful!!");
273. }else{
274. map.put("failure",false);
275. map.put("message","usernameorpasswordiserror!");
276. }
277. returnmap;
278. }
279. }

```
 
Extjs版本：3.3.0
 
1 建表
use  Barcode
/*        (此表為了測試自己添加)
          EL_User :表名
          Id 自動增長類型的主鍵
          UserName 用戶名
          Password 密碼
          NickName 昵稱
          Level 級別（普通用戶或管理員）
*/
drop table EL_User 
create table EL_User(
          Id int identity(1,1)primary key,
          UserName nvarchar(30),
          Password nvarchar(20),
          NickName nvarchar(30),
          Level int     
)
insert into EL_User values('舒婷','123456','微笑釋懷',1) --level級別 0代表普通用戶，1


代表高級用戶
insert into EL_User values('Tom','123123','BigMan',0)
insert into EL_User values('dog','111111','玫瑰男人',0)
2 登录界面 login.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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%>">
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
       <link rel="stylesheet" type="text/css" href="Extjs/3.3.0/resources/css/ext-


all.css"/>
    <script type="text/javascript" src="Extjs/3.3.0/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="Extjs/3.3.0/ext-all.js"></script>
    
<script type="text/javascript">
 Ext.onReady(function(){  
     Ext.QuickTips.init();  
     Ext.form.Field.prototype.msgTarget="qtip";  
     var loginform = new Ext.form.FormPanel({  
         renderTo:'container',  
         title:'用戶登陆',  
         labelSeparator:":",  
         collapsible :true,  
         width:300,  
         height:150,  
         id:'login',  
         labelWidth: 80,  
         bodyStyle: 'padding:5px 5px 0 0',  
         border: false,  
         name:'login',  
         frame:true,  
         defaults:{width:178,xtype:'textfield'},  
         items:[  
             new Ext.form.TextField({  
             frame:true,  
             fieldLabel:"用户名",  
             name:'userName',  
             allowBlank:false,  
             blankText:'用户名不能为空'  
         }),{  
             fieldLabel:"密码",  
             name:'password',  
             allowBlank:false,  
             inputType:'password',  
             blankText:'密码不能为空'  
         }], 
         keys:{  
             key: 13,  
             fn:login  
         },  
         buttons:[{  
             text:'提 交',  
             handler:login  
         },{  
            text:'重 置',
            handler:function reset(){  
               loginform.form.reset();  
            }  
         }]  
     });  
     function login(){
        var form=Ext.getCmp("login").getForm();
        form.submit({
          //clientValidation: true,
          url:"/Env_1/BarCode/selectUser.action",
          params:{
          
          },
          success: function(form, action) {
          Ext.Msg.alert('Success', "恭喜，登陆成功！");
              location.href = 'index.jsp';
          },
          failure: function(form, action) {
            switch (action.failureType) {
                case Ext.form.Action.CLIENT_INVALID:
                    Ext.Msg.alert('Failure', 'Form fields may not be submitted with 


invalid values');
                    break;
                case Ext.form.Action.CONNECT_FAILURE:
                    Ext.Msg.alert('Failure', 'Ajax communication failed');
                    break;
                case Ext.form.Action.SERVER_INVALID:
                   Ext.Msg.alert('Failure', "您的输入有误，请核实后重新输入");
                   loginform.form.reset();  
            }
          }
        });
     }         
 }) 
</script>
  </head>
<body>
  <div id="outer" align="center">
  <br><br><br><br><br><br><br><br> 
    <div id="container"></div>
  </div>
  </body>
</html>


3 Model下的EL_User.java（实体类）


package com.barcode.Model;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="EL_User")
public class EL_User {
    private int Id;
    private String UserName;
    private String Password;
    private String NickName;
    private int level;
    @Id
    @Column(name="Id")
    public int getId() {
        return Id;
    }
    public void setId(int id) {
        Id = id;
    }
    @Column(name="UserName")
    public String getUserName() {
        return UserName;
    }
    public void setUserName(String userName) {
        UserName = userName;
    }
    @Column(name="Password")
    public String getPassword() {
        return Password;
    }
    public void setPassword(String password) {
        Password = password;
    }
    @Column(name="NickName")
    public String getNickName() {
        return NickName;
    }
    public void setNickName(String nickName) {
        NickName = nickName;
    }
    @Column(name="Level")
    public int getLevel() {
        return level;
    }
    public void setLevel(int level) {
        this.level = level;
    }
}
dao层
@Repository
public class ELLoginDao {
 
 
          private HibernateTemplate hibernateTemplate;
          @SuppressWarnings("unused")
          @Autowired
          private void setHibernateTemplate (SessionFactory sessionFactory){
                    this.hibernateTemplate =new HibernateTemplate(sessionFactory);
          }
          
          @SuppressWarnings("unchecked")
          public List isHaveUser(String username,String password){
                    String hql = "from ELUser u where u.userName = '"+username+"' and 


u.password = '"+password+"'";
                    System.out.println("hql"+hql);
                     return this.hibernateTemplate.find(hql);
                    
           
                    
          }
}
 
4 service层
package com.barcode.Service;
 
import java.util.Iterator;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import com.barcode.DAO.EL_UserDAO;
import com.barcode.Model.EL_User;
 
@Service
public class EL_UserService {
    @SuppressWarnings("unused")
    private EL_UserDAO el_UserDAO;
    @Autowired
    public void setEl_UserDAO(EL_UserDAO el_UserDAO) {
        this.el_UserDAO = el_UserDAO;
    }
    @Transactional("barcode")
    public boolean selectUser(String username,String password){
        List<EL_User>list= this.el_UserDAO.selectUser(username,password);
        if(list.size()==0){
            return false;
        }else{
            return true;
        }
    }
}


5 web层


package com.barcode.Web;
 
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.barcode.Model.EL_User;
import com.barcode.Service.EL_UserService;
 
@Controller
public class EL_UserController {
    
    private EL_UserService el_UserService;
    @Autowired
     public void setEl_UserService(EL_UserService el_UserService) {
        this.el_UserService = el_UserService;
    }
    @ModelAttribute("user")
    public EL_User formbackObject(Integer id, HttpServletRequest request) throws 


Exception{
        //獲得更改的各項屬性
        Enumeration enumeration = request.getParameterNames();
        System.out.println(enumeration.hasMoreElements());
        while (enumeration.hasMoreElements()) {
             String paramName = (String) enumeration.nextElement();
             System.out.println("request parameter [" + paramName + "]=" +
             request.getParameter(paramName));
        }
        EL_User user=null;
        if(id!=null&&id!=0){
            //ug = us.getUsefulGroup(id);
        }else{
            user = new EL_User();
        }
        return user;
    }
    
    @SuppressWarnings("unchecked")
    @RequestMapping(value="BarCode/selectUser.action")
    public @ResponseBody Map<String,? extends Object> selectUser(@ModelAttribute


("user") EL_User user,HttpServletRequest request){
        System.out.println(user.getUserName());
        System.out.println(user.getPassword());
        String username=user.getUserName();
        String password=user.getPassword();
        boolean boo=this.el_UserService.selectUser(username,password);
        Map map=new HashMap<String,Object>();
        if(boo){
        map.put("data",user);
        map.put("success",true);
        map.put("message","You are successful !!");
        }else{
            map.put("failure", false);
            map.put("message","username or password is error!");
        }
        return map;
    }
}
```