Lecture10-Java servlet、JSP、JDBC

The goal of this lecture

• Web Server vs Servlet Container vs Database Server

A Web Server(Static content), Servlet Container(Dynamic content), and Database Server are three common types of servers in web applications.

  • A Web Server is used to handle HTTP requests and responses, typically responsible for handling static content such as HTML, CSS, JavaScript, and images. Common Web Servers include Apache and Nginx.
  • A Servlet Container is an extension of a Web Server that provides the ability to handle dynamic content such as Java Servlets, JavaServer Pages (JSP), etc. The Servlet Container can compile Java Servlets and JSP into Java bytecode and dynamically generate HTML and other content at runtime, which is then sent to the client. Common Servlet Containers include Tomcat and Jetty.
  • A Database Server is used to store and manage data, providing efficient data storage and access. Common Database Servers include MySQL, Oracle, SQL Server, etc.
    In a web application, the Web Server and Servlet Container are typically used together, with the Web Server handling static content and the Servlet Container handling dynamic content. The Database Server is used for data storage and management. These three servers are often run on different physical servers to improve application scalability and performance.

• Servlet vs JSP vs HTML/CSS vs Javascript
Servlets, JSP, HTML/CSS, and JavaScript are all technologies used in web development, but they serve different purposes.

  • Servlets are Java classes that are used to handle HTTP requests and responses on the server-side. They are typically used for processing data, interacting with databases, and generating dynamic content.
  • JSP (JavaServer Pages) is a technology that allows developers to create dynamic web pages using HTML, Java code, and JSP tags. JSP pages are compiled into Java Servlets, so they are essentially a higher-level abstraction of Servlets.
  • HTML (Hypertext Markup Language) and CSS (Cascading Style Sheets) are used to create the structure and style of web pages. HTML is used to define the content and structure of the page, while CSS is used to define the visual style and layout.
  • JavaScript is a programming language used to add interactivity and dynamic behavior to web pages. It can be used to manipulate the HTML and CSS on a page, interact with the user, and communicate with servers.
    In summary, Servlets and JSP are used for dynamic content generation on the server-side, while HTML/CSS and JavaScript are used for creating the structure, style, and interactivity of web pages on the client-side.

• Cookie vs HttpSession
Cookies and HttpSession are two mechanisms used to maintain state in web applications.

  • Cookies are small text files stored on the client-side that can be accessed and modified by the client. They are often used to store user preferences, login information, and shopping cart items.
  1. Cookies are extracted from the client’s data sent to the servlet.They are sent back to the client and stored at the client side.
  2. A cookie are included with an age.When the age expires, it will be removed.
  3. The cookies are included in the header of request and sent to the servlet together with request. And new cookies are sent back browser via response.
  4. The servlet can analyze cookies and response to the requests accordingly.
    请添加图片描述
    Problems with Cookies
    • Cookies also have limited size (around 300 cookies in total, 20 cookies per
    server/domain and 4K bytes of data per cookie); while session data has no
    limit of size.

    • Due to security reason, some browsers don’t support cookies (or they can be turned off).
  • HttpSession is a server-side mechanism that allows developers to store user-specific information across multiple HTTP requests.
  1. HttpSession is a similar technology as the Cookie for the same purpose
    but the data is stored in server side.(Different)
  2. Session tracking is built on top of Cookies. It generates a session ID and
    stores it in cookie. Thus data maintained in the associated session can be
    retrieved from server transparently.
  3. When a user first accesses a web application, the server creates a unique HttpSession object and assigns it a session ID. The session ID is then sent to the client as a cookie, and the client sends the session ID back to the server with each subsequent request.
    HttpSession objects are typically used to store user authentication information, shopping cart items, and other user-specific data.

• JSP Exception Handling
A way of handling errors is provided by the JSP specification in the form of programmer-designated error pages.
• To associate an error page with the current JSP, we make use of the
errorPage attribute of the page directive.
<%@ page errorPage=“MyErrorPage.jsp” %>
• It defines the URL of another JSP that reports on Java unchecked runtime
exceptions.
• Then, in the designated error page, you add this:
<%@ page isErrorPage=“true” %>
• If this is true, the page is allowed to access the implicit “exception” object
to get error information.

• SQL commands via JDBC

  • JDBC(java database connectivity) application interface(API:in java.sql)defines a standard way of accessing a relational database from a java application
    (Regardless of where the application is running and where the database is)
  • An important component of a JDBC implementation is JDBC Driver .The driver establishes the connection to the database,and implements any protocol required to move queries and data between the client and the server.
  • Most JDBC programs do the followings:
  1. Load a JDBC driver
  2. Establish a connection to a database.
  3. Construct an SQL statement object and send
    queries.
  4. Process query results
  5. Close the connection after all transactions are
    completed

Some JDBC driver supports multiple connections per client. The client application
can open several connections and perform concurrent transactions on separate threads.Hence, the implementation of the database server class should be thread-safe.
To connect to MySQL from Java you have touse the JDBC driver from MySQL. The
MySQL JDBC driver is called MySQL Connector/J.

JDBC DriverManager
The DriverManager class manages the establishment of Connections.
• A database URL specifies where the database is.

The general syntax:

•jdbc:subprotocol_name://host:port/db_name
• Derby – jdbc:derby://localhost:1527/simpsons
• MySQL - jdbc:mysql://localhost:3306/imdb

• So, to get a database connection:

// effectively register the Java DB driver in DriverManagerString url = "jdbc:mysql://localhost:3306/testdb";String user = ”test";String password =1234";Connection con = DriverManager.getConnection(url, user, password);
Querying Database

We may submit queries (in the form of SQL statements) to the database server through a Statement object, or a PreparedStatement object.
• To create a Statement object, we invoke the createStatement() method of
the Connection object.
• Then, we can access the database using the executeQuery() method
or the executeUpdate() method.
• executeQuery() will return a ResultSet, whereas executeUpdate() will
return an integer which corresponds to the number of records affected.

Statement stmt1 = conn.createStatement();Statement stmt2 = conn.createStatement();ResultSet result = stmt1.executeQuery("select * from book");int rows = stmt2.executeUpdate("delete from category where 
type = ‘programming’");
Result Set

The ResultSet is similar to a database table.
• We may retrieve the meta data (e.g. number of columns, and attribute
types) and data of the ResultSet.
• To traverse the ResultSet, we use the next() method. Initially, the
current row pointer points to the row preceding the first row.
• The executeQuery() method returns a ResultSet object. When the
associated Statement object submits another query, the previous
ResultSet object will no longer be accessible.
• You should explicitly close Statement, ResultSet, and Connection
when you no longer need them.
• When a Statement object is closed, its associated ResultSet will also be
closed automatically.
多次查询提高效率可用这个
请添加图片描述

  • 14
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值