標籤:
大家都知道Javabean+servlet+JSP是最簡單的MVC模式。的確,在一個小型的項目中,這個模式完全夠用。
它優雅並且簡潔。加上jQueryui的完美展示效果,讓這個模式看起來非常合適。當然這其中必不可少的是ajax和json格式的應用。
1、首先從資料庫(sqlserver)中擷取結果集並封裝到Javabean中。在此之前要定義你所需要的bean類。
/* * 查詢Branch */ public ArrayList<Branch> selBranch(Connection connection){ Branch branch=null; ArrayList<Branch> list=new ArrayList<Branch>(); if (connection == null) { return null; } String sql="select distinct mb.BRANCH_CD,mb.BRANCH_NM from BRANCH mb"; try { PreparedStatement ps=connection.prepareStatement(sql); ResultSet rs=ps.executeQuery(); while(rs.next()){ branch =new Branch(); branch.setBranchCD(rs.getInt(1)); branch.setBranchName(rs.getString(2)); list.add(branch); } ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { connection.close(); connection = null; } catch (SQLException e) { e.printStackTrace(); } } return list; }
2、然後建立Servlet
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/json; charset=utf-8"); SqlHandleTool sqlHandleTool=new SqlHandleTool(); SqlConnectTool connection=new SqlConnectTool(); ArrayList<Branch> list = sqlHandleTool.selBranch(connection.getSql2008Connection()); JSONArray jsonArray=JSONArray.fromObject(list); PrintWriter out = response.getWriter(); out.println(jsonArray); }
3、最後在js中應用ajax
function loadBranch(){ $.ajax({ url: "BranchsList.do", dataType:"json", //async: false, success:function(data){ var options = []; for(var i=0;i<data.length;i++){ options.push(‘<option value="‘ + data[i].branchCD + ‘">‘ + data[i].branchName + ‘</option>‘); } $("#sel5").empty() .html(options.join("")) .attr("loaded", true); count++; exec(); }, error:function(){ } });}
Javabean+servlet+JSP(html)執行個體應用