Java之web项目中下拉框的封装

42 篇文章 5 订阅

第一步:封装公共的vo

package com.gx.vo;

public class DropDownFrame {
	private int id;
	private String name;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

第二步:封装一个连接MySQL的工具类

package com.gx.util;

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

public class DBUtil {
	private static String username = null;
	private static String password = null;
	private static String url = null;
	private static String driver = null;

	static {
		try {
			Properties pro = new Properties();
			InputStream in = DBUtil.class.getClassLoader().getResourceAsStream(
					"jdbc.properties");
			pro.load(in);// 加载流//抛异常
			// getProperty获取
			username = pro.getProperty("username");
			password = pro.getProperty("password");
			url = pro.getProperty("url");
			driver = pro.getProperty("driver");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		Connection con = null;
		try {
			Class.forName(driver);// 加载驱动//抛异常
			con = DriverManager.getConnection(url, username, password);// 获取连接// 抛异常
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}
	
	//关闭资源
	public static void close(Connection con,PreparedStatement ps,ResultSet rs){
		try {
			if (con!=null) {
				con.close();
			}			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (ps!=null) {
				ps.close();
			}			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (rs!=null) {
				rs.close();
			}			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

第三步:封装公用的方法

package com.gx.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gx.vo.DropDownFrame;

/**
 * 下拉框的封装公用方法
 * @author Administrator
 *
 */
public class SelectOptionUtil {
	
	private static Connection con = null;
	private static PreparedStatement ps = null;
	private static ResultSet rs = null;
	
	public static List<?> addDropDownFrame(String TableName, String id, String name) {
		List<DropDownFrame> frames = new ArrayList<DropDownFrame>();
		DropDownFrame frame = null;
		StringBuffer sql = new StringBuffer("select * from " + TableName);
		try {
			con = DBUtil.getConnection();
			ps = con.prepareStatement(sql.toString());
			rs = ps.executeQuery();
			while(rs.next()){
				frame = new DropDownFrame();
				frame.setId(rs.getInt(id));
				frame.setName(rs.getString(name));
				frames.add(frame);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(con, ps, rs);
		}
		return frames;
	}

}

上面代码的获取,就调用到第二步中封装的工具类(DBUtil),否则只能按照获取mysql是连接一步一步的编码实现连接:

第四步:封装公共的servlet方法

package com.gx.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import com.gx.util.SelectOptionUtil;
import com.gx.util.ToJsonUtil;

public class JiBenDangAnServlet extends HttpServlet {	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

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

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String type = request.getParameter("type");
		if ("selectArea".equals(type)) {
			selectArea(request, response);
		} 
		else {
			response.sendRedirect("../main.jsp");
		}		
	}
	
	public void selectArea(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//请求解决乱码
		request.setCharacterEncoding("utf-8");
		//响应解决乱码
		response.setCharacterEncoding("utf-8");       
		String TableName = request.getParameter("TableName");
		String ID = request.getParameter("id");
		String Name = request.getParameter("name");
		List<?> areas = (List<?>) SelectOptionUtil.addDropDownFrame(TableName, ID, Name);
		PrintWriter out = response.getWriter();
		out.write(ToJsonUtil.toJson(areas));
	}
}

第五步:封装调用的插件

注意的插件更改;里面的插件代码如下:

//为下拉框添加选项
function appendOption(id, url) {
    $.getJSON(url, function (d) {
    	var data=d.data;
        $("#" + id).empty();
        $("#" + id).append("<option value=" + 0 + ">" + "----请选择----" + "</option>");
        //console.log(data);
        $.each(data, function (i) {
            $("#" + id).append("<option value=" + data[i].id + ">" + data[i].name + "</option>");
        });
    });
}

更改完插件后需要引入插件才可以使用;如:

<script src="${ctx}/Content/js/combobox.js"></script>

第六步:页面代码的调用格式:

appendOption(“select下拉框的id”, “路径&表名参数=表名&id参数=id&名称参数=名称”)
例如:
appendOption("CheXing", "${ctx}/servlet/JiBenDangAnServlet?type=selectArea&TableName=B_CarType&id=CarTypeID&name=CarTypeName");

上面绑定获取的路径是绝对路径,前提是你的jsp页面的代码上面加上了以下两句标签;

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set value="${pageContext.request.contextPath}" scope="page" var="ctx"></c:set>

附ToJsonUtil工具类:

package com.gx.util;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class ToJsonUtil implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public static String toJson(Collection<?> lists){
		JSONObject json = new JSONObject();
		JSONArray jsonArray=new JSONArray();
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(
				Date.class,
				new JsonValueProcessor(){
					@Override
					public Object processObjectValue(String key,
							Object value, JsonConfig config) {
						  	String str = new SimpleDateFormat("yyyy-MM-dd").format((java.util.Date) value);
		                    return str;
					}
					
					@Override
					public Object processArrayValue(Object arg0,
							JsonConfig arg1) {
						return null;
					}
				});
		config.registerJsonValueProcessor(
				Timestamp.class,
				new JsonValueProcessor(){
					@Override
					public Object processObjectValue(String key,
							Object value, JsonConfig config) {
						  	String str = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format((java.sql.Timestamp) value);
		                    return str;
					}
					
					@Override
					public Object processArrayValue(Object arg0,
							JsonConfig arg1) {
						return null;
					}
				});
		if(lists!=null && lists.size()>0){
			
			jsonArray.addAll(lists,config);
			json.put("count",lists.size());
			json.put("data",jsonArray);
		}else{
			
			json.put("count", 0);
		}
		return json.toString();
	}
	
	public static String toJson(String str){
		JSONObject json = new JSONObject();
		JSONArray jsonArray=new JSONArray();
		JsonConfig config = new JsonConfig();
		jsonArray.add(str,config);
		json.put("data",jsonArray);
		return json.toString();
	}
	
		public static String toJson(Object t){
			JSONObject json = new JSONObject();
			JSONArray jsonArray=new JSONArray();
			JsonConfig config = new JsonConfig();
			jsonArray.add(t,config);
			json.put("data",jsonArray);
			return json.toString();
		}
		public static String toJson(Integer curPage,Integer totalRows,Collection<?> lists,boolean success){
			JSONObject json = new JSONObject();
			JSONArray jsonArray=new JSONArray();
			JsonConfig config = new JsonConfig();
			config.registerJsonValueProcessor(
					Date.class,
					new JsonValueProcessor(){
						@Override
						public Object processObjectValue(String key,
								Object value, JsonConfig config) {
							  	String str = new SimpleDateFormat("yyyy-MM-dd").format((java.util.Date) value);
			                    return str;
						}
						
						@Override
						public Object processArrayValue(Object arg0,
								JsonConfig arg1) {
							return null;
						}
					});
			if(lists!=null && lists.size()>0){
				
				jsonArray.addAll(lists,config);
				json.put("success",success);
				json.put("totalRows",totalRows);
				json.put("curPage",curPage);
				json.put("data",jsonArray);
			}else{
				
				json.put("curPage", 0);
			}
			return json.toString();
		}
}

  • 2
    点赞
  • 3
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:终极编程指南 设计师:CSDN官方博客 返回首页

打赏作者

程序yang

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值