Using Servlet Development Enterprise Three-Floor Web Application (2) Realizing Intermediate Layers

zhaozj2021-02-11  259

Utilizing Servlet development enterprise three-layer web application (2)

Huang Wei, Shen Gangyu

3. Implementation of the intermediate layer as an example of BOOKSERVLET, explaining how to implement the servlet of the intermediate layer. (1) Initialization Servlet public class BookServlet extends HttpServlet {protected Connection dbConnection; protected PrepareStatement readQuery; protected PrepareStatement writeQuery; protected String dbName = "jdbc: odbc: BookDatabase"; protected String bookName; protected String bookISBN; public void init (ServletConfig config) throws ServletExecption {try {Class.forName ( "sun.jdbc.odbc.JdbcOdbcDriver"); dbConnection = DriverManager.getConnection (dbName, "", "");} catch (Exception e) {System.out.println ( "Can NOT INITIALIZE DATABASE ");}} Servlet's init () function is called when servlet is initially activated, for BookServlet, in init () we create its connection to the book database (of course, you should already define BookDatabase in ODBC), It is used here that the Connection object in the Java JDBC API is used. (2) Implementing the service () operation When the client requests to the servlet, the service () function of the servlet is called, and we should implement all the features of the intermediate layer in service (). public void service (HttpServletRequest request, HttpServletResponse reponse) throws ServletException, IOException {bookName = request.getParameter ( "BookName"); bookISBN = request.getParameter ( "BookISBN"); if (bookName == null && bookISBN == null) doQueryBook (Request, Reponse); Else DonewBook ​​(Request, Reponse);} First, we obtain the client's input parameters through the parameter httpservletRequest, which is entered in the editing box in the HTML page, and then we will library according to the needs of users. The operation of the query or library update. ◆ Query the database information and return the result page to the browser, querying the database information, first constructs a SQL statement according to the query condition (this example only returns all records), then set the prepaerstateterial object, by running its executeQuery () to the background database server Request results. After obtaining the results of the query, servlet generates a result HTML page to the browser via HTTPSERVLETRESPONSE.

转载请注明原文地址:https://www.9cbs.com/read-3537.html

New Post(0)