Everyone knows that javabean+servlet+jsp is the simplest MVC pattern. Indeed, in a small project, this model is fully sufficient.
It is elegant and concise. Plus the perfect display of the jQueryUI, making this pattern look very suitable. Of course, this is an essential part of Ajax and JSON format applications.
1. First obtain the result set from the database (SQL Server) and encapsulate it in JavaBean. Before you do this, define the bean classes you need.
/** Query Branch*/ PublicArraylist<branch>selbranch (Connection Connection) {Branch Branch=NULL; ArrayList<Branch> list=NewArraylist<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=NewBranch (); BRANCH.SETBRANCHCD (Rs.getint (1)); Branch.setbranchname (Rs.getstring (2)); List.add (branch); } ps.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally { Try{connection.close (); Connection=NULL; } Catch(SQLException e) {e.printstacktrace (); } } returnlist; }
2. Then create the servlet
/** * @seeHttpservlet#doget (httpservletrequest request, httpservletresponse response)*/ protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method StubDoPost (request, response); } /** * @seeHttpservlet#dopost (httpservletrequest request, httpservletresponse response)*/ protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method StubResponse.setcontenttype ("Text/json; Charset=utf-8 "); Sqlhandletool Sqlhandletool=NewSqlhandletool (); Sqlconnecttool Connection=NewSqlconnecttool (); ArrayList<Branch> list =Sqlhandletool.selbranch (Connection.getsql2008connection ()); Jsonarray Jsonarray=jsonarray.fromobject (list); PrintWriter out=Response.getwriter (); Out.println (Jsonarray); }
3, finally the application of Ajax in JS
functionLoadbranch () {$.ajax ({URL:"Branchslist.do", DataType:"JSON", //Async:false,Successfunction(data) {varOptions = []; for(vari=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) instance application