标签:
大家都知道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)实例应用
标签:
原文地址:http://www.cnblogs.com/heyesp/p/4414495.html