검색 기능 추가

이 인 스 턴 스 는 제 가 발표 한 "Extjs4 - grid + servlet 페이지 조회" 에 추 가 된 검색 기능 입 니 다. 기본 기능 은 이미 실현 되 었 으 나, 난 코드 문제 가 존재 하 므 로, 마스터 의 지도 로 난 코드 문 제 를 해결 하 기 를 바 랍 니 다.
Extjs 4 에서 검색 구성 요 소 는 플러그 인 형식 으로 나타 나 고 실현 도 매우 간단 합 니 다. 검색 구성 요 소 는 examples / ux / form 디 렉 터 리 에 있 고 JS 파일 은 SearchField. js 입 니 다.
Grid 에서 검색 기능 을 불 러 옵 니 다. 주의해 야 할 것 은:
1. 로드 지연, 즉 Ext. Loader. setConfig ({enabled: true});
2. 플러그 인의 디 렉 터 리 설정: Ext. Loader. setPath ('Ext. ux', '../../examples/ux'); ,플러그 인 이 있 는 디 렉 터 리 는 반드시 정확 해 야 합 니 다. 그렇지 않 으 면 불 러 오 는 데 실패 하고 필요 한 기능 을 실현 할 수 없습니다.
html 코드:
"Extjs4 - grid + servlet 페이지 조회" 코드 와 같 으 면 붙 이지 않 습 니 다.
searchGrid. js 코드:
//         ,    404  
Ext.Loader.setConfig({enabled:true});
//  searchGrid ext4      ,           "../"
Ext.Loader.setPath('Ext.ux','../ext4_example/ext4/examples/ux');

//   
Ext.require(
		[
		 	'Ext.grid.*',
		 	'Ext.toolbar.Paging',
		 	'Ext.util.*',
		 	'Ext.data.*',
		 	//    
		 	'Ext.ux.form.SearchField'
		 ]
		 
);

Ext.onReady(
		function(){
			//  Model
			Ext.define(
					'User',
					{
						extend:'Ext.data.Model',
						fields:[
						        {name:'name',mapping:'name'},
						        {name:'sex',mapping:'sex'},
						        {name:'age',mapping:'age'}
						]
					}
			)
			//     
			var store = Ext.create(
					'Ext.data.Store',
					{
						model:'User',
						
						//      
						pageSize:5,
						proxy: {
					        type: 'ajax',
					        url : 'users',
					        reader: {
								//     json
					            type: 'json',
					            root: 'bugs',
					            //      
					            totalProperty: 'totalCount'
					        }
					    },
						autoLoad:true
					}
			);
			
			//  grid
			var grid = Ext.create('Ext.grid.Panel',{
					store:store,
					columns:[
					         {text:'  ',width:120,dataIndex:'name',sortable:true},
					         {text:'  ',width:120,dataIndex:'sex',sortable:true},
					         {text:'  ',width:120,dataIndex:'age',sortable:true}
					],
					height:200, 
			        width:480, 
			        x:20, 
			        y:40, 
			        title: 'ExtJS4 Grid        ', 
			        renderTo: 'grid', 
			       
			        dockedItems:[
			                     //      
			                     {
			                    	 dock: 'top', 
                    	             xtype: 'toolbar', 
                    	             items: { 
                    	                 width: 200, 
                    	                 fieldLabel: '    ', 
                    	                 labelWidth: 70, 
                    	                 xtype: 'searchfield', 
                    	                 store: store 
			                     	}
			                     },{ 
                    	             dock: 'bottom', 
                    	             xtype: 'pagingtoolbar', 
                    	             store: store, 
                    	             displayInfo: true, 
                    	             displayMsg: '   {0} - {1}  ,   {2}  ', 
                    	             emptyMsg: '    ' 
			                    }
			        ],
				}
			)
			store.loadPage(1); 
		}
)


백그라운드 Servlet. 자바 코드
package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * @author   
 */

public class Servlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//                  
		req.setCharacterEncoding("UTF-8");
		//System.out.println(req.getCharacterEncoding());
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String start = req.getParameter("start");
		String limit = req.getParameter("limit");
		StringBuilder sb = null;
		String query = req.getParameter("query");
//       ,     		
System.out.println(query);
		//    
		int total = 0;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/user", "root", "123456");

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//sql  
		String countSql = "select count(*) from users";
		String selectSql = "select * from users limit " + start + ", " + limit;
		//               sql   
		if(query!=null){
			countSql+=" where name='"+query+"'";
			selectSql="select * from users where name='"+query+"' limit " + start + ", " + limit;
		}
		
		//    
		try {
			pstmt = con.prepareStatement(countSql);
			rs = pstmt.executeQuery();
			while(rs.next()){
				total = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		//    
		try {
			pstmt = con.prepareStatement(selectSql);
			rs = pstmt.executeQuery();
			sb = new StringBuilder();
			//  json    
			sb.append("{totalCount:"+total+",bugs:[");
			while (rs.next()) {
				sb.append("{");
				sb.append("name:" + "\'" + rs.getString(1) + "\',");
				sb.append("sex:" + "\'" + rs.getString(2) + "\',");
				sb.append("age:" + "\'" + rs.getString(3) + "\'");
				sb.append("},");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		String json = sb.substring(0, sb.length() - 1);
		json += "]}";
		
System.out.println(json);
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		try {
			resp.getWriter().write(json);
			resp.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

효과 그림:
이름 이 "1" 인 것 을 조회 합 니 다.

좋은 웹페이지 즐겨찾기