Ajax
Typical Applications Three Level Linkages Requirements and Preparedness
-
First create new employees.jsp under WebContent to forward to employees.jsp page under pages folder
-
<!-- This method can also go directly. listLocations page <jsp:forward page="EmployeeServlet?method=listLocations"></jsp:forward> --> <% response.sendRedirect("EmployeeServlet?method=listLocations"); %>
-
-
(2) New com.atguigu.ajax.app.dao package with BaseDao.java and DBManager.java under src
-
BaseDao.java
import java.sql.Connection; import java.util.List; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; /* * Because there is no transaction in the application, get Connection directly in the method and close Connection */ public class BaseDao { private static final QueryRunner runner=new QueryRunner(); public <T> List<T> getForList(String sql,Class<T> clazz,Object ...args){ List<T> list=null; Connection conn=null; try { conn=DBManager.getInstance().getConnection(); list=runner.query(conn, sql, new BeanListHandler<T>(clazz),args); } catch (Exception e) { throw new RuntimeException(e); }finally { DbUtils.closeQuietly(conn); } return list; } public <T> T get(String sql,Class<T> clazz,Object...args) { T result=null; Connection conn=null; try { conn=DBManager.getInstance().getConnection(); result=runner.query(conn, sql, new BeanHandler<T>(clazz),args); } catch (Exception e) { throw new RuntimeException(e); }finally { DbUtils.closeQuietly(conn); } return result; } }
-
DBManager.java
import java.sql.Connection; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DBManager { private static DataSource dataSource; static{ dataSource= new ComboPooledDataSource("ajaxApp"); } public Connection getConnection() { Connection conn=null; if(dataSource!=null) { try { conn=dataSource.getConnection(); } catch (Exception e) { throw new RuntimeException(e); } } return conn; } private DBManager() {}; private static DBManager instance=new DBManager(); static DBManager getInstance() { return instance; } }
-
-
(3) New beans under com.atguigu.ajax.app.beans package
-
Department.java
public class Department { private Integer departmentId; private String departmentName; public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } }
-
Employee.java
public class Employee { private Integer employeeId; private String lastName; private String email; private double salary; public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } }
-
Location.java
public class Location { private Integer locationId; private String city; public Integer getLocationId() { return locationId; } public void setLocationId(Integer locationId) { this.locationId = locationId; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
-
-
(4) Add a new EmployeeServlet.java servlet under com.atguigu.ajax.app.servlets package
-
EmployeeServlet.java
import java.io.IOException; import java.lang.reflect.Method; 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.atguigu.ajax.app.beans.Department; import com.atguigu.ajax.app.beans.Location; import com.atguigu.ajax.app.dao.BaseDao; import com.fasterxml.jackson.databind.ObjectMapper; public class EmployeeServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String methodName=request.getParameter("method"); try { Method method=getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); method.invoke(this, request,response); } catch (Exception e) { e.printStackTrace(); } } private BaseDao baseDao=new BaseDao(); protected void listLocations(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sql="SELECT location_id locationId,city FROM locations"; List<Location> locations=baseDao.getForList(sql, Location.class); request.setAttribute("locations",locations); request.getRequestDispatcher("/WEB-INF/pages/employees.jsp").forward(request, response); } protected void listDepartments(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String locationId=request.getParameter("locationId"); String sql="SELECT department_id departmentId," +" department_name departmentName " + " FROM departments d WHERE d.location_id=?"; List<Department> departments=baseDao.getForList(sql, Department.class,Integer.parseInt(locationId)); ObjectMapper mapper=new ObjectMapper(); String result=mapper.writeValueAsString(departments); response.setContentType("text/javascript"); response.getWriter().print(result); } }
-
web.xml configuration
<servlet> <description></description> <display-name>EmployeeServlet</display-name> <servlet-name>EmployeeServlet</servlet-name> <servlet-class>com.atguigu.ajax.app.servlets.EmployeeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>EmployeeServlet</servlet-name> <url-pattern>/EmployeeServlet</url-pattern> </servlet-mapping> </web-app>
-
-
_Add the following jar packages to the lib directory
c3p0-0.9.1.2.jar
commons-dbutils-1.7.jar
jackson-annotations-2.2.1.jar
jackson-core-2.2.1.jar
jackson-databind-2.2.1.jar
jstl.jar
mysql-connector-java-5.1.46-bin.jar
standard.jar -
_New c3p0-config.xml under src
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <named-config name="ajaxApp"> <!-- Specify the basic attributes for connecting data sources --> <property name="user">xuefeng</property> <property name="password">1234</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/myemployees?useUnicode=true&characterEncoding=UTF-8</property> <!-- If the number of connections in the database is insufficient, How many connections are requested to the database server at a time --> <property name="acquireIncrement">2</property> <!-- Number of connections when initializing database connection pool --> <property name="initialPoolSize">2</property> <!-- Minimum number of database connections in database connection pool --> <property name="minPoolSize">2</property> <!-- Maximum number of database connections in the database connection pool --> <property name="maxPoolSize">3</property> <!-- C3P0 The database connection pool is maintainable Statement Number of --> <property name="maxStatements">5</property> <!-- Each connection can be used at the same time Statement Number of objects --> <property name="maxStatementsPerConnection">2</property> </named-config> </c3p0-config>
-
_Create a new pages folder under WEB-INF with employees.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="scripts/jquery-blockUI.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.9.1.min.js"></script> <!-- 1.Obtain#city, add change function 2.send#department keeps only one option child node 3.Obtain #The value chosen by city, if it is ", means that the value chosen is"Please select..."At this time, no Ajax request needs to be sent. 4.If the value is not"",The facts of the explanation city Change, preparation Ajax request 4.1 url:EmployeeServlet?method=listDepartments 4.2 args:locationId,time 5.The return is a JSON array 5.1 If the element in the returned array is 0: Tips "There are no departments in the city at present." 5.2 If the element in the returned array is not zero: Traversal Creation<option value="departmentId">departmentName</option> //And add the newly created option node to the child of # department --> <script type="text/javascript"> $(function() { $("#city").change(function() { $("#department option:not(:first)").remove(); var city=$(this).val(); if(city != ""){ var url="EmployeeServlet?method=listDepartments"; var args={"locationId":city,"time":new Date()}; $.getJSON(url,args,function(data){ if(data.length == 0){ alert("There are no departments in the city at present."); }else{ for (var i = 0; i < data.length; i++) { var deptId=data[i].departmentId; var deptName=data[i].departmentName; $("#department").append("<option value=' " +deptId+"'>" + deptName+ "</option>"); } } }) } }); }); </script> </head> <body> <img alt=" " id="loading" src="images/loading.gif" style="display:none"> <center> <br><br> City: <select id="city"> <option value="">Please choose...</option> <c:forEach items="${locations }" var="location"> <option value="${location.locationId }">${location.city }</option> </c:forEach> </select> Department: <select id="department"> <option value="">Please choose...</option> </select> Employee: <select id="employee"> <option value="">Please choose...</option> </select> <br><br> <table id="empdetails" border="1" cellspacing="0" cellpadding="5" style="display:none"> <tr> <th>Id</th> <th>Name</th> <th>Email</th> <th>Salary</th> </tr> <tr> <td id="id"></td> <td id="name"></td> <td id="email"></td> <td id="salary"></td> </tr> </table> </center> </body> </html>
-
Effect page
Using BlockUI
-
Use BlockUI: Ajax requests are executed at the time of issuance and $. unblock UI is executed at the time of delivery of Ajax responses
(document). ajaxStart ((document). ajaxStart ((document). ajaxStart (. blockUI). ajaxStop (. unblock UI); style can be modified: need to put. unblock UI; Styles can be modified: you need to include. unblock UI; you can modify styles: you need to include. block UI in a function(){}$(document).ajaxStart(function(){ $.blockUI({ message:$('#loading'), css:{ top: ($(window).height() - 400 )/2 +'px', left: ($(window).width() -400)/2 + 'px', width: '400px', border: 'none' } overlayCSS:{backgroundColor: '#fff'} }) }).ajaxStop($.unblockUI);
See the documentation for specific effects.
-
employees.jsp with BlockUI
<script type="text/javascript"> $(function() { //Using blockUI $(document).ajaxStart(function(){ $.blockUI({ message:$('#loading'), css:{ top: ($(window).height() - 400 )/2 +'px', left: ($(window).width() -400)/2 + 'px', width: '400px', border: 'none' }, overlayCSS:{backgroundColor: '#fff'} }) }).ajaxStop($.unblockUI); $("#city").change(function() { $("#department option:not(:first)").remove(); var city=$(this).val(); if(city != ""){ var url="EmployeeServlet?method=listDepartments"; var args={"locationId":city,"time":new Date()}; $.getJSON(url,args,function(data){ if(data.length == 0){ alert("There are no departments in the city at present."); }else{ for (var i = 0; i < data.length; i++) { var deptId=data[i].departmentId; var deptName=data[i].departmentName; $("#department").append("<option value=' " +deptId+"'>" + deptName+ "</option>"); } } }) } }); }); </script>
-
Design sketch