JavaWeb Final Exam Review Summary - Dark Horse Programmer

Key review chapters and knowledge points:

Chapter 3 Summary of Key Memory: (Distribution of topics: short answer , program)

  1. Have a deep understanding of the meaning, life cycle, deployment and invocation of servlet programs.

Servlet is a Java applet running on the server side , which is a set of specifications (interfaces) provided by Sun to process client requests and respond to dynamic resources of the browser. But the essence of servlet is java code, which dynamically outputs content to the client through java API .

servlet specification: contains three technical points

  1 ) servlet technology

  2 ) filter technology --- filter

  3 ) listener technology --- listener

The Servlet API ( life cycle ) is divided into three phases, namely the initialization phase, the running phase and the destruction phase

1 ) Initialization phase

By calling the init () method to achieve the initialization of the Servlet . In the entire lifetime of a Servlet , its init () method is called only once.

2 ) Run phase

During the entire life cycle of the Servlet , for each access request of the servlet , the servlet container will call the service () method of the servlet once , and create new ServletRequest and ServletResponse objects , that is to say, the service () method is used throughout the entire life of the Servlet It will be called multiple times during the cycle.

3 ) Destruction stage

When the server is shut down or the Web application is moved out of the container, the Servlet is destroyed along with the Web application . Before destroying the Servlet , the Servlet container will call the Servlet 's destroy() method to allow the Servlet object to release the resources it occupies . In the entire life cycle of the Servlet , its destroy () method is only called once .

Servlet deployment and access

Open the [ servers ] tab, select the Tomcat server where the web application is deployed , right-click and select the [ Add and Remove ] option to enter the web application deployment interface, select " chapter03 ", and click the [ Add ] button to add the chapter03 project Go to the Tomcat server and click the [ finish ] button to complete the deployment of the web application.

Next, start the Tomcat server in eclipse , and enter the address " http://localhost:8080/chapter03/TestServlet01 " in the address bar of the browser to access TestServlet01

1. Please list the methods in the Servlet interface, and explain the characteristics and functions of these methods respectively.

There are five methods in the  Servlet interface: init , service , destroy , getServletConfig and getServletInfo . The characteristics and functions of these methods are as follows:

1 ) The init(ServletConfig config) method, which is called when the server visits the Servlet for the first time, is responsible for the initialization of the Servlet . Executed only once in the life cycle of a Servlet . This method receives a parameter of type ServletConfig , and the Servlet container can pass initialization configuration information to the Servlet through this parameter .

2 ) service(ServletRequest request , ServletResponse response) method, which is responsible for responding to the user's request . When the container receives a request from the client to access the Servlet object, it will call this method.

3 ) The destroy() method is responsible for releasing the resources occupied by the Servlet object . The container calls this method when the Servlet object is destroyed.

4 ) getServletConfig() method, which returns the ServletConfig object passed to the Servlet when the container calls the init(ServletConfig config) method .

5 ) getServletInfo() method, which returns a string containing information about the Servlet , such as author, version and copyright.

2. Briefly describe the three main functions of the ServletContext interface.

1 ) Get the initialization parameters of the web application

2 ) Implement multiple Servlet objects to share data

3 ) Read the resource files under the web application

    2. <!-- Configure Servlet -->

            <servlet>

                    <servlet-name>xxx</servlet-name>

                    <servlet-class>xxx.xxx.xxx</servlet-class>

            </servlet>

        <!-- Configure Servlet mapping path -->

            <servlet-mapping>

                    <servlet-name>xxx</servlet-name>

                    <url-pattern>/xxx</url-pattern>

            </servlet-mapping>

3. Deployment and use in the program.

Chapter 4 Summary of Key Memory: (Distribution of topics: fill in the blank, choice, short answer )

  1. Deeply understand the meaning of the 9 built-in objects, as well as the method and storage range of key objects

The meaning of the 9 built-in objects:

1. request : The object is mainly used to process client requests , used in (page forwarding, cookie acquisition)

2. response : used to process and respond to client requests , used in (page redirection)

3.session : called a session in the network , a session is a call between the browser and the server (when saving the login status)

4.application : Just like a global variable, it is used to save the common data in the application (get the real path when uploading)

5.out : The object is used to output information in the web browser . After the data is output, the output stream should be closed in time

6.pageContext : used to obtain the context of the page , through which other 8 built-in objects of the page can be obtained

7.config: Used to obtain server configuration information

8.page: represents the jsp itself, only legal in the jsp page

9.exception: Used to handle exceptions that occur on jsp pages

The following seems to be the key object

pageContext JSP page container --> the current page is valid

request request object --> the same request is valid (request forwarding is still valid, redirection [two requests] is invalid)

session session object --> the same session is valid (as long as the browser is not closed or switched)

Application global object-->globally valid (valid for the entire project, valid for switching browsers, invalid for closing the server, and invalid for other items)

1. The similarities and differences between request forwarding and redirection are as follows:

  1. Both request forwarding and redirection can realize turning to the current application resource when accessing a resource
  2. Request forwarding is one request and one response, while redirection is two requests and two responses

3 ) In general, request forwarding should be used to reduce browser access to the server and reduce server pressure

4 ) If you need to change the browser's address bar, or change the function of the browser's refresh button, you need to use redirection

    2、Request

        Request.setCharacterEncoding=“UTF-8”;

        String request.getParameter(String name);

        String[] request.getParameterValue(String name);

        RequestDispatcher request.getRequestDispatcher(String path);

        request.getRequestDispatcher.forward(request,response);

        Public void setAttribute(string name,object );

        Public object getAttribute(string name);

        Public void removeAttribute(string name);

    3、response

        response.setHeader("refresh","2");

        response.setHeader("refresh","3;URL=hello.jsp") ;

        response.sendRedirect(String location) ;

        response.addCookie(Coolie cookie) ;

       

Chapter 5 Summary of Key Memory: (Distribution of topics: fill in the blank, choice, short answer )

  1. Deeply understand the relationship between cookie and session.

1.Cookie

In layman's terms, it is some website-related information stored locally after visiting certain websites, and some steps will be reduced in the next visit. A more accurate statement is: Cookies are small pieces of text stored by the server on the local machine and sent to the same server with each request, and are a solution to maintain state on the client side .

The main contents of the cookie include: name, value, expiration time, path and domain.

2.Session

There is a HashTable-like structure used to store user data in the server .

When the browser sends a request for the first time, the server automatically generates a HashTable and a Session ID to uniquely identify the HashTable , and sends it to the browser through a response. The second request sent by the browser will put the Session ID in the previous server response into the request and send it to the server. The server extracts the Session ID from the request and compares it with all the saved Session IDs to find the user. The corresponding HashTable .

Generally, this value will have a time limit, and the value will be destroyed after the timeout. The default is 30 minutes.

When the user jumps between web pages of the application , the variables stored in the Session object will not be lost but will always exist in the entire user session.

The implementation of Session has a certain relationship with Cookie . A session id is generated when a connection is established .

The main differences between Cookie and Session are as follows:

1 ) Cookie and HttpSession are technologies for saving session-related data . Among them, Cookie stores information on the browser side and is a client-side technology. Session stores data on the server side and is a server-side technology.

2 ) Cookie works based on the Set-Cookie response header and Cookie request header in the HTTP protocol

3 ) By default HttpSession works based on a special cookie named JSESSIONID

4 ) The browser has strict restrictions on cookies , and there is a limit to how many cookies a website can save in the browser

5 ) HttpSession operates based on Cookie by default .

2、cookie

        Public Cookie(string name,string value)

        Public string getName()

        Public string getValue()

        Public void setMaxAge(int expiry)

        Public void addCookie(Cookie cookie)

        Public Cookie[] getCookies()

    3、session

        public String getId()

        public boolean isNew()

        public void setMaxInactiveInterval(int interval)

        public int getMaxInactiveInterval()

        public long getCreationTime()

        public long getLastAccessedTime()

        public void setAttribute(String name, Object value) 

        public Object getAttribute(String name)

        public void removeAttribute(String name)

        public void invalidate()

第6章重点记忆归纳:(题目分布:填空、选择)

    1、JSP基本结构:java程序段、声明、输出表达式

        <% java程序段  %>

        <%! 声明  %>

        <%= %>相当于out.print()

        out.println()和out.print()效果是一样的。如果要换行</br>

   2、JSP注释:<!-- HTML注释 -->、//java语句注释、/* java程序段注释...*/、<%--  jsp注释  --%>

    3、文档UTF-8设置

        打开Eclisps软件时整体设置--属性;

        项目属性设置;

        request.setCharacterEncoding="UTF-8";;

        response.setCharacterEncoding="UTF-8";

    4、重点JSP指令:

        <%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8" %>

        <%@ page errorPage="..." iserrorPage="true" %>

        <%@ page import="..." %>

        <%@ include file="..." %>

        Action command:

        <jsp:include page="..." flush="true"/>

        <jsp:include page="..." flush="true">

            <jsp:param name="..." value="...">

        </jsp:include>

       

        <jsp:forward page="...">

            <jsp:param name="..." value="..." />

        <jsp:forward>

       

        Jump method:

        <a href="...?param=...&param1=...&...">

       

        Redirection : (Twice request, changes can be seen in the address bar, data loss)

        response.sendRedirect ("relative path");

        Request forwarding: (one request, no changes can be seen in the address bar, data will not be lost, you can getParameter data, you can also getAttribute data)

        request.getRequestDispatcher ("relative path").forward(request,response);

Chapter 7 Summary of Key Memory: (Distribution of topics: fill in the blanks, choose)

  1. JavaBean technology concept and use.
  2. Basic use of EL expressions and JSTL tag libraries.

Chapter 8 Summary of Key Memory: (Distribution of topics: short answer , program)

  1. Understand concepts, principles, and master configuration.

filter

Filter is called a filter or interceptor, and its basic function is to intercept the process of calling the Servlet by the Servlet container , so as to realize some special functions before and after the Servlet responds.

Filter working principle (execution process)       

       When the client sends a request for web resources, the web server checks according to the filter rules set in the application configuration file. If the client request meets the filter rules, the client request/response is intercepted, and the request header and request data are checked or modified. , and pass through the filter chain in turn, and finally pass the request/response to the requested Web resource for processing. The request information can be modified in the filter chain, and the request can not be sent to the resource handler according to the conditions, and a response can be sent back directly to the client. When the resource processor finishes processing the resources, the response information will be returned step by step. Also in this process, the user can modify the response information to complete certain tasks.

listener

The Servlet listener is used to monitor the occurrence of some important events , and the listener object can do some necessary processing before and after the event occurs.

2. Briefly describe the function of the Servlet event listener . (write three points)

1 ) Monitor the creation and destruction process of domain objects such as ServletContext , HttpSession and ServletRequest in the web application .

2 ) Monitor the modification of domain object attributes such as ServletContext , HttpSession and ServletRequest .

3 ) Perceive the state bound to an object in the HttpSession domain .

  1. Filter processing: filter requests and responses; release data .

        3. Filter is a class that implements the javax.servlet.Filter interface:

            Implement three core methods: init(), destroy(), doFilter();

            Among them, the principle and execution timing of init() and destroy() are the same as those of Servlet;

            In order to realize who to filter, the filter needs to configure who to intercept, and the process is similar to servlet;

                Intercept path or wildcard intercept;

                Filter chain: Multiple filters can be configured, and the sequence of filters is determined by the position of <filter-mapping>.

                Dispatcher request method:

                    request: intercept HTTP request get post;

                    forward: only intercept requests through request forwarding;

            Handle interception through doFilter(), and release through chain.doFilter(request, response);

4. The deployment and use in the program, the use of the website Unicode filter.

Chapter 9 Summary of Key Memory: (Distribution of topics: short answer , program)

    1. Understand the meaning, concept and principle of JDBC .

       

The full name of JDBC is Java Database Connectivity ( Java Database Connectivity ), which is a set of Java API for executing SQL statements . Applications can connect to relational databases through this set of APIs , and use SQL statements to complete the processing of querying, updating, and deleting data in the database.

The implementation steps of JDBC are as follows:

1 ) Load and register the database driver

2 ) Get the database connection through DriverManager

3 ) Obtain the Statement object through the Connection object

4 ) Use Statement to execute SQL statements

5 ) Operation ResultSet result set

6 ) Close the connection and release resources

    2. Main functions of JDBC API: realized through the following classes/interfaces

        DriverManager: Manage jdbc drivers

        Connection: connection (generated by DriverManager)

        Statement (PreparedStatement): CRUD (generated by Connection)

        CallableStatement: Call the stored procedure/stored function in the database (generated by Connection)

        Result: The returned result set (generated by Statement, PreparedStatement)

    3. The specific steps for jdbc to access the database:

        a. Import the driver and load the specific driver class

        b. Establish a connection with the database

        c. Send sql, execute

        d. Processing the result set (query)

e. close

    4. It is recommended to use PreparedStatement: the reasons are as follows:

        1. The coding is simple and not easy to make mistakes

        String name="ls";

        String password="1234";

        stmt:

        String sql="insert into user(name,password)values('"+name+"','"+password+"')";

        stmt.executeUpdate(sq1);

        pstmt:

        String sql="insert into user(name,password) values(?,?)";

        pstmt=connection.prepareStatement(sq1);//Precompile SQL

        pstmt.setString(1,name);

        pstmt.setString(2,password);

        2. High performance and fast pre-compilation.

        3. Effectively prevent SQL injection vulnerabilities.

        stmt: There is a risk of being injected by sq1

        (Example: enter username: any value' or 2=2-- password: any value)

        select count(*)from user where name='"+name+"' and password='"+password+"';

        select count(*)from user where name='ls'and password='1234’;

        select count(*)from user where name='任意值’or 2=2--'and password='任意值’;

        select count(*)from user where name='任意值’or 2=2;

        select count(*)from user;

        pstmt:有效防止sql注入

第10章重点记忆归纳:(题目分布:填空、简答

  1. 重点概念、原理。

数据库连接池在初始化时将创建一定数量的数据库连接放到连接池中,应用程序访问数据库时并不是直接创建Connection,而是向连接池“申请”一个Connection。如果连接池中有空闲的Connection,则将其返回,否则创建新的Connection。使用完毕后,连接池会将该Connection回收,并交付其他的线程使用,以减少创建和断开数据库连接的次数,提高数据库的访问效率。

2、不用连接池

        Class.forName();

        Connection connection =DriverManager.getConnection();//连接指向数据库

        3、用连接池的核心:将连接的指向数据源而不是数据库。

        ...->DataSource ds=….

        Connection connection =ds.getConnection();//指向的是数据源的连接

        Database access core->pstmt/stmt->connection->1. Direct database 2. Data source

Chapter 11 Key memory induction: (topic distribution: program)

  1. Focus on the principle and use process of JSP Model1 and JSP Model2.

Chapter 12 Summary of Key Memory: (Distribution of topics: fill in the blanks, choose)

  1. Focus on understanding the principles of file upload and download. ,

The page instruction of a JSP page is mainly used to set various attributes of the page, and the function of the language attribute of the page instruction is:

Specifies the scripting language used by JSP pages, the default is Java

The role of Servlet is to process client requests and respond . Servlet is a java program that conforms to specific specifications and is a web component based on java technology that runs on the server side.

Servlet's life cycle methods include init() , service() , destroy()

Add the <load-on-startup> element to the <servlet> element to specify the loading order of the Servlet when the container starts

Use the JDBC statement to access the database in JSP, and the correct statement to import the SQL class library is:

<%@ page import="java.sql.*" %>

The root element of the JSP application configuration file is <web-app> , the implicit annotation in JSP is: <%-- annotation content --%> , if you want to import java.util.* package in JSP, you need to use pageinstruction                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

JSP file requests need to go through three stages : translation stage, compilation stage, execution stage

The abstract class GenericServlet implements the Servlet interface and the ServletConfig interface

When writing a Servlet, you only need to rewrite the doGet() or doPost() method according to the needs of the application.

To store data in the request scope, you can use the setAttribute(String, Object) method of the request object, and to get data, you can use the getAttribute(String) method

The relationship between JSP and Servlet is: JSP will be translated into Servlet

Forwarding will not generate a new request object, redirection is to send a new request, and sending a request will generate a response and request object

The method through which the request object obtains the submitted data according to the component name : getParameter()

In JSP, which of the following methods can correctly get the value of a checkbox : request.getParameterValues()

In the Servlet, use the getParameter() method to obtain the requested parameter value , and use the request.getParameterValues() method for multiple parameters with the same name

Which of the following objects provides a way to access and place shared data on a page: session

In JSP, the session technology is most suitable for realizing the storage of the shopping cart

In a JSP page, the following ( ) expression statement can get the content of the text box named title in the page request:

<%=request.getParameter("title")%>

The role of cookies is manifested in the following ways:

1. Tracking of specific objects , such as the number of visits of visitors, last visit time, path, etc.

2. Count the number of page views .

3. During the validity period of the cookie , record the user login information .

4. Realize various personalized services , such as displaying different content in different styles for different users.

The server assigns a session to each browser, but the session will not be destroyed when the browser is closed, it will only be destroyed when it expires or the server is closed. When releasing the session object, use the invalidate () method of the session object

Invented by Netscape Corporation, cookies are the most commonly used way of tracking user sessions. It is generated by the server and client and sent to the browser

When we access the server for the first time, if we only connect to a jsp page through a request without submitting any information, which event will be triggered: establish a session

Session tracking technology can be implemented through which of the following technologies : cookie , session

Configure filters using <filter> and <filter-mapping> tags in web.xml

In the MVC pattern, M refers to the model Model , V refers to the view View , and C refers to the controller Controller

In the MVC pattern, the components corresponding to the model are: JavaBean

MVC模式中,视图对应的组件是:JSPHTML文件

MVC模式中,控制器的作用是:控制器负责转发请求,对请求进行处理

M(模型层)指的是:实体类、Service层、dao

MVC模式的优点有:各司其职,互不干涉、利于分工、利于重用和扩展

Model1模式下的程序流程控制是在JSP页面中实现的,这使得JSP页面中的嵌入大量的Java代码,Model1模式是JSP + JavaBean的结合,在JSP技术发展的初识阶段被广泛使用,Model2模式(MVC)是在JSP+JavaBean的设计模式基础上加入Servlet来实现程序控制层

整个MVC的流程就是:用户发送一个请求,首先由控制层接收,然后根据请求去调用模型层处理并返回数据,接着调用相应的视图层把数据响应给用户

第3章重点记忆归纳:(题目分布:简答、程序)

  1. 深刻理解servlet程序的含义、生存周期、部署及调用。

Servlet is a Java applet running on the server side . It is a set of specifications (interfaces) provided by sun company to process client requests and respond to dynamic resources of the browser. But the essence of servlet is java code, which dynamically outputs content to the client through java API .

servlet specification: contains three technical points

  1 ) servlet technology

  2 ) filter technology --- filter

  3 ) listener technology --- listener

The Servlet API ( life cycle ) is divided into three phases, namely the initialization phase, the running phase and the destruction phase

1 ) Initialization phase

By calling the init () method to achieve the initialization of the Servlet . In the entire lifetime of a Servlet , its init () method is called only once.

2 ) Run phase

During the entire life cycle of the Servlet , for each access request of the servlet , the servlet container will call the service () method of the servlet once , and create new ServletRequest and ServletResponse objects , that is to say, the service () method is used throughout the entire life of the Servlet It will be called multiple times during the cycle.

3 ) Destruction stage

When the server is shut down or the Web application is moved out of the container, the Servlet is destroyed along with the Web application . Before destroying the Servlet , the Servlet container will call the Servlet 's destroy() method to allow the Servlet object to release the resources it occupies . In the entire life cycle of the Servlet , its destroy () method is only called once .

Servlet deployment and access

打开【servers】选项卡,选中部署web应用的Tomcat服务器,右键单击并选择【Add and Remove】选项,进入部署web应用的界面,选中“chapter03”,单击【Add】按钮,将chapter03项目添加到Tomcat服务器中,单击【finish】按钮,完成web应用的部署。

接下来启动eclipse中的Tomcat服务器,在浏览器的地址栏上输入地址“http://localhost:8080/chapter03/TestServlet01访问TestServlet01

1、请列举Servlet接口中的方法,并分别说明这些方法的特点及其作用。

There are five methods in the Servlet interface: init , service , destroy , getServletConfig and getServletInfo . The characteristics and functions of these methods are as follows:

1 ) The init(ServletConfig config) method, which is called when the server visits the Servlet for the first time , is responsible for the initialization of the Servlet . Executed only once in the life cycle of a Servlet . This method receives a parameter of type ServletConfig , and the Servlet container can pass initialization configuration information to the Servlet through this parameter .

2 ) service(ServletRequest request , ServletResponse response) method, which is responsible for responding to the user's request . When the container receives a request from the client to access the Servlet object, it will call this method.

3 ) The destroy() method, which is responsible for releasing the resources occupied by the Servlet object . The container calls this method when the Servlet object is destroyed.

4 ) getServletConfig() method, which returns the ServletConfig object passed to the Servlet when the container calls the init(ServletConfig config) method .

5 ) getServletInfo() method, which returns a string containing information about the Servlet , such as author, version and copyright.

2. Briefly describe the three main functions of the ServletContext interface.

1 ) Get the initialization parameters of the web application

2 ) Implement multiple Servlet objects to share data

3 ) Read the resource files under the web application

1. Get the context path of the web 2. Get global parameters

3. Use as a domain object 4. Request forwarding

5. Read the resource file of the web project

    2. <!-- Configure Servlet -->

           <servlet>

                   <servlet-name>xxx</servlet-name>

                   <servlet-class>xxx.xxx.xxx</servlet-class>

           </servlet>

        <!-- Configure Servlet mapping path -->

           <servlet-mapping>

                   <servlet-name>xxx</servlet-name>

                   <url-pattern>/xxx</url-pattern>

           </servlet-mapping>

3. Deployment and use in the program.

Chapter 4 Summary of Key Memory: (Distribution of topics: fill in the blank, choice, short answer )

  1. Deeply understand the meaning of the 9 built-in objects, as well as the method and storage range of key objects

The meaning of the 9 built-in objects:

1) out: mainly used for page output;

2) request: used to obtain user request information ;

3) response: Indicates the response information from the server to the client ;

4) config: contains server configuration information , you can use this object to obtain Servlet initialization parameters ;

5) session: mainly used to save user information ;

6) application: contains the shared information of all users ;

7) page: refers to the instance of the Servlet class after the conversion of the current page ;

8) pageContext: indicates the JSP page container , which provides access to all objects and namespaces in the JSP page ;

9) exception:: Indicates the exception that occurs on the JSP page , and it only works in the error page .

pageContext JSP page container --> the current page is valid

request request object --> the same request is valid (request forwarding is still valid, redirection [two requests] is invalid)

session session object --> the same session is valid (as long as the browser is not closed or switched)

Application global object-->globally valid (valid for the entire project, valid for switching browsers, invalid for closing the server, and invalid for other items)

    2、Request

The request object is an object of type javax.servlet.httpServletRequest.

This object represents the request information of the client, and is mainly used to accept the data transmitted to the server through the HTTP protocol. (Including header information, system information, request method and request parameters, etc.). The scope of the request object is a request.

        Request.setCharacterEncoding=“UTF-8”;

        String request.getParameter(String name);

        String[] request.getParameterValues(String name);

        RequestDispatcher request.getRequestDispatcher(String path);

        request.getRequestDispatcher.forward(request,response);

        Public void setAttribute(string name,object );

        Public object getAttribute(string name);

        Public void removeAttribute(string name);

    3、response

Response represents the response to the client, mainly to transfer the object processed by the JSP container back to the client.

The response object also has scope, it is only valid within the JSP page.

        response.setHeader("refresh","2");

        response.setHeader("refresh","3;URL=hello.jsp") ;

        response.sendRedirect(String location) ;

        response.addCookie(Coolie cookie) ;

Chapter 5 Summary of Key Memory: (Distribution of topics: fill in the blank, choice, short answer )

  1. Deeply understand the relationship between cookie and session.

1.Cookie

In layman's terms, it is some website-related information stored locally after visiting certain websites, and some steps will be reduced in the next visit. A more accurate statement is: Cookies are small pieces of text stored by the server on the local machine and sent to the same server with each request, and are a solution to maintain state on the client side .

The main contents of the cookie include: name, value, expiration time, path and domain.

2.Session

There is a HashTable-like structure used to store user data in the server .

When the browser sends a request for the first time, the server automatically generates a HashTable and a Session ID to uniquely identify the HashTable , and sends it to the browser through a response. The second request sent by the browser will put the Session ID in the previous server response into the request and send it to the server. The server extracts the Session ID from the request and compares it with all the saved Session IDs to find the user. The corresponding HashTable .

Generally, this value will have a time limit, and the value will be destroyed after the timeout. The default is 30 minutes.

When the user jumps between the web pages of the application , the variables stored in the Session object will not be lost but will always exist in the entire user session. The implementation of Session has a certain relationship with Cookie . A session id is generated when a connection is established .

Briefly what is conversational technology?

会话过程类似于生活中的打电话过程,它指的是一个客户端(浏览器)与Web服务器之间连续发生的一系列请求和响应过程。在Servlet技术中,提供了两个用于保存会话数据的对象,分别是CookieSession

CookieSession主要有如下区别:

1CookieHttpSession保存会话相关数据的技术,其中Cookie将信息存储在浏览器端,是客户端技术Session将数据保存在服务器端,是服务器端技术

2Cookie基于HTTP协议中的Set-Cookie响应头和Cookie请求头进行工作的

3 ) By default HttpSession works based on a special cookie named JSESSIONID

4 ) The browser has strict restrictions on cookies , and there is a limit to how many cookies a website can save in the browser

5 ) HttpSession operates based on Cookie by default .

2、cookie

        Public Cookie(string name,string value)

        Public string getName()

        Public string getValue()

        Public void setMaxAge(int expiry)

        Public void addCookie(Cookie cookie)

        Public Cookie[] getCookies()

    3、session

        public String getId()

        public boolean isNew()

        public void setMaxInactiveInterval(int interval)

        public int getMaxInactiveInterval()

        public long getCreationTime()

        public long getLastAccessedTime()

        public void setAttribute(String name, Object value) 

        public Object getAttribute(String name)

        public void removeAttribute(String name)

        public void invalidate()

Chapter 6 Summary of Key Memory: (Distribution of topics: fill in the blanks, choose)

JSP operating principle (.jsp file à translated into .java file à compiled into .class file)

Please briefly describe the operating principle of JSP .

  1. The client sends a request to access the jsp file
  2. The JSP container first converts the JSP file into a java source file (java servlet source program). During the conversion process, if any grammatical errors are found in the jsp file, the conversion process is immediately interrupted and an error message is returned to the server and client.
  3. If the conversion is successful, the JSP container compiles the generated java source file into a .class file . This class file is a servlet, and the servlet container will process it like other servlets.
  4. The converted servlet class (.class file) is loaded by the Servlet container, an instance of the servlet is created, and the init() method in the servlet is executed to initialize the instance.
  5. Call the service() method in the servlet to handle client requests .
  6. If the jsp file is modified, the server will judge whether the file needs to be recompiled according to the modified content, and if necessary, the recompiled result replaces the resident servlet in the memory, and continues the above process.
  7. After execution, call the destroy() method in the servlet to destroy the servlet instance created above
  8. Complete the request processing, generate a response object received by the jsp container, and send back to the client in HTML format.

    1. The basic structure of JSP: java program segment, statement, output expression

        <% java program segment %> local variable

        The <%! declaration %> is valid for the entire page

        <%= %> is equivalent to out.print()  // Output variables or expressions: <%=……%>, ${……} in EL expressions

        out.println() and out.print() have the same effect. If you want to wrap</br>

   2. JSP comment: <!-- HTML comment -->, //java statement comment, /* java program segment comment...*/, <%-- jsp comment --%>

    3. Document UTF-8 setting

        When opening the Eclipse software, the overall setting-properties;

        Project property settings;

        request.setCharacterEncoding="UTF-8";;

        response.setCharacterEncoding="UTF-8";

    4. Key JSP instructions:

        <%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8" %>

        <%@ page errorPage="..." iserrorPage="true" %>

        <%@ page import="..." %>

        <%@ include file="..." %>

        Action command:

        <jsp:include page="..." flush="true"/>

        <jsp:include page="..." flush="true">

           <jsp:param name="..." value="...">

        </jsp:include>

   

        <jsp:forward page="...">

           <jsp:param name="..." value="..." />

        <jsp:forward>

       

        Jump method:

        <a href="...?param=...&param1=...&...">

       

Redirection : (Twice request, the address bar can see the change, the data is lost)

        response.sendRedirect ("relative path");

Request forwarding: (one request, the address bar will not change, the data will not be lost, you can getParameter data, you can also getAttribute data)

        request.getRequestDispatcher ("relative path"). forward (request, response);

1. The similarities and differences between request forwarding and redirection are as follows:

  1. Both request forwarding and redirection can realize turning to the current application resource when accessing a resource
  2. Request forwarding is one request and one response, while redirection is two requests and two responses

3 ) In general , request forwarding should be used to reduce browser access to the server and reduce server pressure

4 ) If you need to change the browser's address bar , or change the function of the browser's refresh button, you need to use redirection

Chapter 7 Summary of Key Memory: (Distribution of topics: fill in the blanks, choose)

  1. JavaBean technology concept and use.

Javabean is a reusable software component in the Java development language , which is essentially a Java class.

The <jsp:useBean> tag is used to declare JavaBean objects

JSP provides tags for accessing JavaBean properties. If you want to output a certain property of JavaBean to a web page, you can use the <jsp:getProperty> tag. If you want to assign a value to a property of JavaBean, you can use the <jsp:setProperty> tag

  1. Basic use of EL expressions and JSTL tag libraries.

EL expression definition rules: start with the $ symbol, and the content is written in {}, for example: $(test)

Invisible variables of EL expressions:

pageContext : The invisible object used to access JSP.

pageScope : Map of page objects

requestScope : Map of request objects

sessionScope : the MAP of the session object

applicationScope : the MAP of the application object

param : A string MAP containing the requested parameters

cookie : Store the MAP with the cookie attached to the request by name

Suppose we want the name value in the session, then we can use: ${sessionScope.name},

request.getParamter(name) is equivalent to ${param.name}

If we want to get an array of parameters, we can use: ${paramValues.name}, of course, what is returned is an array object.

Briefly describe what are the Javabean specifications ?

1 ) It must have a public, parameterless construction method , which can be the default construction method automatically generated by the compiler.

2 ) It provides public setter methods and getter methods for external programs to set and obtain properties of JavaBean .

3 ) It is a public class .

4 ) Usually need to implement java.io.Serializable for serialization.

Briefly describe the specification that defines EL identifiers.

  1. Can consist of uppercase and lowercase letters, numbers, and underscores in any order
  2. cannot start with a number
  3. Cannot be reserved words in EL , such as and , or , gt ;
  4. Cannot be an EL implicit object , such as pageContext ;
  5. Cannot contain special characters such as single quotes ( ' ), double quotes ( " ), minus signs ( - ), and forward slashes

Chapter 8 Summary of Key Memory: (Distribution of topics: short answer , program)

  1. Understand concepts, principles, and master configuration.

filter

Filter is called a filter or interceptor, and its basic function is to intercept the process of calling the Servlet by the Servlet container , so as to realize some special functions before and after the Servlet responds.

Filter working principle (execution process)       

       When the client sends a request for web resources, the web server checks according to the filter rules set in the application configuration file. If the client request meets the filter rules, the client request/response is intercepted, and the request header and request data are checked or modified. , and pass through the filter chain in turn, and finally pass the request/response to the requested Web resource for processing. The request information can be modified in the filter chain, and the request can not be sent to the resource handler according to the conditions, and a response can be sent back directly to the client. When the resource processor finishes processing the resources, the response information will be returned step by step. Also in this process, the user can modify the response information to complete certain tasks.

  1. Filter processing: filter requests and responses; release data .

        3. Filter is a class that implements the javax.servlet.Filter interface:

           Implement three core methods: init(), destroy(), doFilter();

           Among them, the principle and execution timing of init() and destroy() are the same as those of Servlet;

           In order to realize who to filter, the filter needs to configure who to intercept, and the process is similar to servlet;

               Intercept path or wildcard intercept;

               Filter chain: Multiple filters can be configured, and the sequence of filters is determined by the position of <filter-mapping> .

               Dispatcher request method:

               request : Intercept HTTP request get post;

               forward: only intercept requests through request forwarding;

          Handle interception through doFilter(), and release through chain.doFilter(request, response);

4. The deployment and use in the program, the use of the website Unicode filter.

Chapter 9 Summary of Key Memory: (Distribution of topics: short answer , program)

    1. Understand the meaning, concept and principle of JDBC .

Concept: Java DataBase Connectivity: The technology of using Java code to send sql statements is jdbc technology

Function: establish a connection with the data, so that java can realize the operation on the database.

Please briefly describe what is JDBC .

The full name of JDBC is Java Database Connectivity ( Java Database Connectivity ), which is a set of Java API for executing SQL statements . Applications can connect to relational databases through this set of APIs , and use SQL statements to complete the processing of querying, updating, and deleting data in the database.

Briefly describe the implementation steps of JDBC .

The implementation steps of JDBC are as follows:

1 ) Load and register the database driver

2 ) Get the database connection through DriverManager

3 ) Obtain the Statement object through the Connection object

4 ) Use Statement to execute SQL statements

5 ) Operation ResultSet result set

6 ) Close the connection and release resources

Please write a JDBC program for reading the information of the users table in the database, and it is required to obtain the values ​​of the fields id , name , password and email respectively.

public class Example01 {

public static void main(String[] args) throws SQLException {

    // 1. Register the driver of the database

    DriverManager.registerDriver(new com.mysql.jdbc.Driver());

Class.forName("com.mysql.jdbc.Driver");

    // 2. Get the database connection through DriverManager

    String url = "jdbc:mysql://localhost:3306/jdbc";

    String username = "root";

    String password = "itcast";

    Connection conn = DriverManager.getConnection(url, username, password);

    // 3. Obtain the Statement object through the Connection object

    Statement stmt = conn.createStatement();

    // 4. Use Statement to execute SQL statement.

    String sql = "select * from users";

    ResultSet rs = stmt.executeQuery(sql);

    // 5. Operate the ResultSet result set

    System.out.println("id | name   | password | email  |");

    while (rs.next()) {

        int id = rs.getInt("id"); // Get the value of the specified field through the column name

        String name = rs.getString("name");

        String psw = rs.getString("password");

        String email = rs.getString("email");

        System.out.println(id + " | " + name + " | " + psw + " | " + email);

    }

    // 6. Recycle database resources

    rs.close();

    stmt.close();

    conn.close();

}

}

    2. Main functions of JDBC API: realized through the following classes/interfaces

        DriverManager: Manage jdbc drivers

        Connection: connection (generated by DriverManager)

        Statement (PreparedStatement): CRUD (generated by Connection)

        CallableStatement: Call the stored procedure/stored function in the database (generated by Connection)

        Result: The returned result set (generated by Statement, PreparedStatement)

    3. The specific steps for jdbc to access the database:

       a. Import the driver and load the specific driver class

       b. Establish a connection with the database

       c. Send sql, execute

       d. Processing the result set (query)

e. close

    4. It is recommended to use PreparedStatement: the reasons are as follows:

        1. The coding is simple and not easy to make mistakes

        String name="ls";

        String password="1234";

        stmt:

        String sql="insert into user(name,password)values('"+name+"','"+password+"')";

        stmt.executeUpdate(sq1);

        pstmt:

        String sql="insert into user(name,password) values(?,?)";

        pstmt=connection.prepareStatement(sq1) ;//Precompile SQL

        pstmt.setString(1,name);

       pstmt.setString(2,password);

        2. High performance and fast pre-compilation.

        3. Effectively prevent SQL injection vulnerabilities.

        stmt: There is a risk of being injected by sq1

        (Example: enter username: any value' or 2=2-- password: any value)

        select count(*)from user where name='"+name+"' and password='"+password+"';

        select count(*)from user where name='ls'and password='1234’;

        select count(*) from user where name='any value' or 2=2--'and password='any value';

        select count(*)from user where name='any value' or 2=2;

        select count(*)from user;

        pstmt: effectively prevent sql injection

Chapter 10 Summary of Key Memory: (Distribution of topics: fill in the blank, short answer )

  1. Key concepts and principles.

What is a connection pool and the role of a connection pool

The data connection pool is responsible for allocating, managing, and releasing database connections , which allows applications to reuse existing database connections instead of establishing connections .

The role of the connection pool: the connection pool is to save the created connection in the pool, and when a request comes, directly use the created connection to access the database. This omits the process of creating and destroying connections. This improves performance.

Please think about the working mechanism of the database connection pool?

When the database connection pool is initialized, a certain number of database connections will be created and placed in the connection pool. When the application accesses the database, it does not directly create a Connection , but "applies" to the connection pool for a Connection . If there is an idle Connection in the connection pool , it is returned, otherwise a new Connection is created . After use, the connection pool will recycle the Connection and deliver it to other threads to reduce the number of database connection creation and disconnection and improve database access efficiency.

Briefly describe the difference between the getConnection() method in DriverManager and DataSource .

The difference between the getConnection() method in DriverManager and DataSource is as follows:

1 ) DriverManager will initialize a new connection every time it calls the getConnection method , while DataSource 's getConnection just takes out an existing connection from the pool

2 ) The close() of DriverManager is to release the Connection , while the close() of DataSource will only return the Connection to the connection pool .

2. No connection pool

        Class.forName(); The function is to ask the JVM to find and load the specified class, which means that the JVM will execute the static code segment of the class.

        Connection connection = DriverManager.getConnection();//The connection points to the database

        3. Use the core of the connection pool: point the connection to the data source instead of the database.

        ...->DataSource ds=….

        Connection connection = ds.getConnection();//points to the connection of the data source

        Database access core->pstmt/stmt->connection->1. Direct database 2. Data source

Chapter 11 Key memory induction: (topic distribution: program)

  1. Focus on the principle and use process of JSP Model1 and JSP Model2.

Model1 applies two technologies in JavaWeb development, namely JSP and JavaBean technology, so Model1 is the JSP+JavaBean mode. Among them, JSP needs to respond to the user's request independently and return the processing result to the user, and also needs to complete the process control processing; while JavaBean provides assistance, such as saving the data queried from the database.

The Model 2 architecture pattern is a method of combining JSP and Servlet to realize dynamic content service, so Model 2 is the JSP+Servlet+JavaBean pattern. It absorbs the outstanding advantages of the two technologies, uses JSP to generate the content of the expression layer, and uses Servlet to complete deep-level processing tasks. In Model 2, Servlet acts as a controller, responsible for managing the processing of requests, creating JavaBean and objects required by JSP pages, and deciding which JSP page to send to the user according to the user's actions. In particular, it should be noted that there is no processing logic in the JSP page, it is only responsible for retrieving the object or JavaBean originally created by the Servlet, and then extracting dynamic content from the Servlet and inserting it into the static template for page display.

Briefly describe what is the MVC design pattern.

The MVC design pattern is a software design pattern of a programming language that provides a method of dividing software into modules by function . The MVC design pattern divides the software program into three core modules: model (Model) , view (View) and controller (Controller) .

Briefly describe the role of the Model module in the MVC design pattern .

The role of the Model module in the MVC design pattern is as follows:

  1. Manage the application's business data .
  2. Define access control and business rules for modifying this data .
  3. When the state of the model changes , it notifies the view of the change and provides a way for the view to query the state of the model .

Chapter 12 Summary of Key Memory: (Distribution of topics: fill in the blanks, choose)

  1. Focus on understanding the principles of file upload and download.    

<form enctype=”multipart/form-data” method=”post”>

   

Nine built-in objects (also called hidden objects)

object type

built-in object name

type

Object Profile

I/O objects

request   

HttpServletRequest

Encapsulates various information from clients and browsers.

response

HttpServletResponse

Encapsulates the response information of the server.

out

JspWriter

Used to output data to clients and browsers.

communication control object

application

ServletContext

Represents the context of the current application.

Information can be shared between different users.

session

HttpSession

Used to save session information. That is, it is possible to share data between different requests from the same user.

pageContext

PageContext

Provides access to all objects and namespaces of jsp pages.

Servlet object

page

Object(this)

Points to the current jsp program itself.

config

ServletConfig

Encapsulates the configuration information of the application.

error handling object

exception

Throwable

Encapsulates exceptions and error messages that occur during the execution of a JSP program.

Commonly used built-in objects are: request , response , session , application , out , etc.

page(pageContext): Only save attributes in one page . Invalid after the jump.

request: Valid only in one request , valid after the server jumps. Client hop invalid

session: valid in another session . Both server jump and client jump are valid. Closing and reopening the web page doesn't work

application: saved on the entire server and available to all users. Doesn't work after restarting the server

Four Domain Objects

Role: save data and get data for data sharing.

ServletContext

context area

Can only be used within the same web application (global)

HttpServletRequet

request field

Can only be used in the same request (forwarding)

HttpSession

session area

Can only be used in the same session (session object) (private)

PageContext

page area

Can only be used in the current jsp page (current page)

Guess you like

Origin blog.csdn.net/Vivien_CC/article/details/118413888