1. 程式人生 > >表單POST請求伺服器,通過多條件查詢獲取資料庫資料

表單POST請求伺服器,通過多條件查詢獲取資料庫資料

package com.jekin.common;

import java.io.IOException;

public class FindServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;character=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		Map<String, String> map = new HashMap<String, String>();
		map.put("接入號碼", request.getParameter("phone"));
		map.put("ICCID", request.getParameter("iccid"));
		map.put("裝置號", request.getParameter("number"));
		//查詢語句
		StringBuffer stringBuffer = new StringBuffer("SELECT `接入號碼`,ICCID,`裝置號`,`總流量(G)`,`使用流量(M)` FROM sim_info ");
		//獲取查詢欄位名
		Set<String> keys = map.keySet();
		//判斷條件語句是否第一個,是新增where頭部,否則新增and
		boolean isFrist = true;
		for (String key : keys) {
			String value = map.get(key);
			if(!value.equals("") && value != null){
				if(isFrist){
					stringBuffer.append("WHERE " + key + " = " + map.get(key));
					isFrist = false;
				}else{
					stringBuffer.append(" AND " + key + " = " + map.get(key));
				}
			}
		}
		//時間段
		String start_time_form = request.getParameter("start_time");
		String end_time_form = request.getParameter("end_time");
		if(!start_time_form.equals("") && !end_time_form.equals("")){
			if(isFrist){
				stringBuffer.append("WHERE `時間` BETWEEN '" + start_time_form + "' AND '" + end_time_form + "'");
			}else{
				stringBuffer.append(" AND `時間` BETWEEN '" + start_time_form + "' AND '" + end_time_form + "'");
			}
		}
		MysqlUtil mysqlUtil = new MysqlUtil();
		List<SimInfo> simInfos = new ArrayList<SimInfo>();
		try {
			ResultSet rs = mysqlUtil.execSQL(stringBuffer.toString());
			while (rs.next()) {
				String accessPhone = rs.getString("接入號碼").trim();
				String iccid = rs.getString("ICCID").trim();
				String deviceNumber = rs.getString("裝置號").trim();
				int allFolw = Integer.valueOf(rs.getString("總流量(G)").trim());
				int useFlow = Integer.valueOf(rs.getString("使用流量(M)").trim());
				SimInfo simInfo = new SimInfo(accessPhone, iccid, deviceNumber, allFolw, useFlow);
				simInfos.add(simInfo);
			}
			JSONArray jsonArray = JSONArray.fromObject(simInfos);
			PrintWriter printWriter = response.getWriter();
			printWriter.write(jsonArray.toString());
			printWriter.flush();
			printWriter.close();
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			mysqlUtil.closeSQLConnect();
		}

	}
}
資料庫操作類: