Summary of important knowledge points for Java Web programming final review

Table of contents

foreword

1. What is Java Web?

Two, install eclipse, jdk, tomcat server

1. Install eclipse

2. Set eclipse to Chinese

3. Install jdk

4. Install tomcat

5. Set the encoding format

Three, walk into JSP

1. Overview of JPS

2. Command label

(1) page command

(2) include directive

(3) taglib instruction

3. Embed Java code

(1) code snippet

(2) Declaration

(3) JSP expression

4. Notes

5. JSP common objects

(1) request object

(2) response object

(3) session object

(4) application object

Four, Servlet technology

1. Servlet basics

(1) Servlet and Servlet container

(2) Technical characteristics of Servlet

2. Servlet configuration

3. Commonly used interfaces and classes of Servlet

(1) Servlet interface

(2) GenericServlet class

(3) HttpServlet class

4. Servlet filter

(1) Filter interface

(2) Filter configuration

Five, database technology - JDBC

1. Overview of JDBC

2. JDBC driver

3. Commonly used interfaces in JDBC

4. Connect to the database

(1) Load the JDBC driver

(2) Create a database connection

(3) Execute SQL statements

(4) Obtain query results

(5) close the connection

5. Database operation technology



foreword

Near the end of the term, I will make a simple review and summary of the JavaWeb studied this semester, and I hope it will be helpful to the newcomers. This article focuses on summarizing the knowledge points, and the practical exercise project code is related to other articles in my "Java Web Programming" category column.

1. What is Java Web?

Java Web is a technology stack that uses Java technology to solve related web and Internet fields. The web includes two parts: the web server and the web client. The application of Java on the client side includes Java Applet, but it is rarely used. The application of Java on the server side is very rich, such as Servlet, JSP, third-party framework and so on. Java technology has injected a powerful impetus into the development of the Web field.

Two, install eclipse, jdk, tomcat server

1. Install eclipse

First open the eclipse official website, the home page address of the official website is:

Enabling Open Innovation & Collaboration | The Eclipse Foundation

After entering the official website, click Download to download

Click Download Packages to choose the version you need

After selecting the version, click to enter the following interface, select the Windows system to download, the eclipse example here is the 2020-09 version

 Here select Download to download

Then select the location you want to download and download it. Don’t worry about the following interface, Eclipse is free software , just wait for the download to complete!

After the download is complete, open the downloaded compressed file and decompress it to a suitable location. After the decompression is complete, find the installation package, click Install and follow the prompts to install. The installation location should be the c drive by default. It is recommended to change to other drives, including the installation package, and try to put it on other drives. Don’t put everything in the c drive by default. This is good for you The computer is better.

When Eclipse starts for the first time, it will ask the user to select a workspace (afterwards, the projects created in Eclipse will be automatically created in the folder you choose, and the Use this as the... Change the folder where the workspace is located and waste some time) The location of the workspace is best not to be in the C drive to avoid wasting space on the C drive (if the C drive is not the system drive, it can also be set to the C drive), the author sets the workspace It is set on the D drive. Also, when you just entered the software, the following interface should be all in English. I have loaded the Chinese plug-in package. If you want to set it to Chinese, you can go to my resources to download the Chinese package, and then follow my instructions below to set it to Chinese. . As shown below

 After clicking Start, the following interface will appear. Don’t worry about this page, just cross it out. Of course, you are welcome in English.

2. Set eclipse to Chinese

After downloading the Chinese package in my CSDN blog resource, unzip it to get the following file (1 is my Chinese compressed package; 2 is the file I got after decompression, and 3 is my eclipse software installation directory)

 

 Click to enter the eclipse folder in the 2 files I obtained after decompression

Copy the eclipse folder to the dropins folder in the eclipse software installation directory (D:\Professional Study\Java web\Development Tools\eclipse\dropins), if there is the same content, choose to replace it. Then restart the software to set up successfully.

3. Install jdk

Go to the official website to download jdk, find the downloaded jdk installation package, and double-click to install it. The installation of JDK is a brainless installation, which is one step at a time until it is completed. By default, it is installed in the Program Files directory under the C drive. If you want to change the installation directory, please remember the installation directory, otherwise you will not know where to find the jdk installation directory when you configure the environment variables later.

Java Downloads | Oracle

The installation is very simple. If Mengxin finds it troublesome, just use the default location. I will also use the default location of jdk installation to demonstrate how to configure environment variables. Find Computer, right-click, and click Properties.

After entering, click on advanced system settings

Then click on Environment Variables

Click New in the system variable, the new variable name is "JAVA_HOME", and the variable value is the jdk installation path, here is "C:\Program Files\Java\jdk-11.0.5". For win10 and win11, you can click Browse Directory to select the jdk installation path. For win7, you need to go to the computer to find the jdk installation directory and copy the path.

browse catalog

 After the above settings are completed, the Path is still found in the system variables. In our windows system, the path variable is built-in. We need to configure the bin directory under jdk to the path. So select edit here:

Then create a new one twice, and configure the bin directory under jdk and the bin directory in jre under jdk.

 After configuration, be sure to click OK, OK, OK, and these configurations will take effect.

 Test whether the installation is successful

Open a terminal:

Method 1: Start|Windows System|Command Prompt

Method 2: Search directly in the search box: command prompt or cmd (Command)

Method 3: Shortcut key: win+R key, then enter cmd

Note: If you have opened the dos window before configuring the environment variable, you need to reopen the dos window after configuring the environment variable.

Test 1: java -version

Test 2: javac

4. Install tomcat

First of all, let me briefly introduce the main interface of Eclipse, that is, the workbench window of Eclipse. Eclipse's workbench is mainly composed of menu bar, toolbar, perspective toolbar, perspective, project explorer view, outline view, editor and other views. It can be understood with the picture below.

(1) Open eclipse, select the "Servers" server view in other views of the eclipse workbench, click the right mouse button in the blank area of ​​this view, and select the "New"/"Server" menu item in the pop-up shortcut menu, The "New Server" dialog box will open. In this dialog box, expand the Apache node and select the "Tomcat v9.0 Server" subnode under this node. (Of course, you can also select other versions of the server) Others use the default.

 I have a 9.0 server in the server view here because I have configured and used it, and readers should not have it at the beginning. Also, if the reader downloads the server in my CSDN resources, then choose version 9.0, if you download other versions by yourself, you can choose the corresponding version.

 (2) Click the "Next" button, and a dialog box for specifying the installation path of the Tomcat server will open. Click the "Browse" button to select the installation path of Tomcat, and use the default for others. After setting, click "Finish" to complete.

 (3) Then double-click label 1 in the server view, select label 2, and then press the shortcut key "Ctrl+s" to save the settings, and finally close this interface and the Tomcat server is set.

(4) Let's write an html and run it on the server to test it.

In the upper left corner of the file, click New to create a new Dynamic Web Project project, choose the project name as you like, and then click Finish.

 

 Create a new HTML File on the WebContent of the new project, and choose the name yourself.

 

  

 Finally, copy my code or simply write a running test to see if there is any problem

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<table width="270" border="1">
 <tr>
  <th>用户注册</th>
 </tr>
 <tr>
  <td align="left">用户名:</td>
  <th align="right"><input type="text">*</th>
 </tr>
 <tr>
  <td align="left">密码:</td>
  <td align="right"><input type="text">*</td>
 </tr>
 <tr>
  <td align="left">确认密码:</td>
  <td align="right"><input type="text">*</td>
 </tr>
 <tr>
  <td align="left">电话:</td>
  <td align="right"><input type="text">*</td>
 </tr>
 <tr>
  <td align="left">邮箱:</td>
  <th align="right"><input type="text">*</th>
 </tr>
  <tr>
  <th align="left"></th>
  <th align="center"><input type="submit" value="提交">  <input type="submit" value="重置"></th>
 </tr>
</table>
</body>
</html>

Run to our configured server.

If the form can run like me, it will be fine.

 

 5. Set the encoding format

Find "Preferences" in the window, then find the Web

 Set the code of the three characters underlined to UTF-8 to avoid garbled characters. Finally click Apply and Close.

Three, walk into JSP

1. Overview of JPS

        JSP (Java Server Pages) is a dynamic web technology standard initiated by Sun and established with the participation of many companies. It embeds Java code fragments (Scriptlet) and JSP tags in HTML codes to form a JSP web page. When receiving a user request, the server will process the Java code fragment, then generate an HTML page of the processing result and return it to the client, and the client's browser will present the final page effect.

JSP features:

Cross-platform, business code separation, component reuse, precompilation, inheritance of Java Servlet functions

2. Command label

(1) page command

language attribute

This attribute is used to set the language used by the JSP page, and the default value is Java.

extends attribute

This attribute is used to set the Java class inherited by the JSP page. This attribute is not commonly used and may affect the performance optimization of the server.

import attribute

This attribute is used to set the class package imported by JSP. JSP pages can embed Java code fragments, and these Java codes need to import the corresponding class package when calling the API.

pageEccoding attribute

This attribute is used to define the encoding format of the JSP page, that is, specify the file encoding.

contentType attribute

This attribute is used to set the MIME type and character encoding of the JSP page, and the browser will display the content of the web page accordingly.

(2) include directive

        The include directive is used for file inclusion. This directive can include the content of another file in the JSP page, but it only supports static inclusion , that is to say, all the content in the included file is included in the JSP page as it is; if there is code in the included file, it will be is not enforced. The included file can be a piece of Java code, HTML code, or another JSP page.

(3) taglib instruction

        This command is used to load user-defined tags, which will be explained in the following chapters. The tags loaded using this directive can be used directly in JSP pages. Its syntax format is as follows:

<%@taglib prefix="view" uri="/WEB-INF/tags/view.tld" %>

3. Embed Java code

(1) code snippet

        Java code snippets are enclosed between "<%" and "%>" tags. You can write single-line or multi-line Java code, and the statement ends with ";", and its writing format is the same as that of Java class code.

(2) Declaration

Define global variables:

<%! long startTime = System.nanoTime();%>

Define a global method:

<%!

   int getMax(int a, int b) {

   int max = a > b ? a : b;

      return max;

   }

%>

(3) JSP expression

        JSP expressions can directly output Java expression results to JSP pages. The final operation result of the expression will be converted to a string type, because the text displayed on the webpage is all strings. The syntax of a JSP expression is as follows:

Pi is: <%=Math.PI %>

4. Notes

category grammar

HTML comments

<!-- comment text -->

JSP comments

<%-- comment text --%>

dynamic comment

<!-- <%= variable value %> -->

code comment

<%

//single line comment

/*

multiline comment

*/

/**JavaDoc comments for member comments*/

%>

5. JSP common objects

(1) request object

Get the request parameter value:

String request.getParameter(String parameter)

Get the information of the Form form

String[] request. getParameterValues(String parameter)

Get request client information

 Manage properties in scope

Object request.setAttribute(String name ,Object value)

(2) response object

Common methods of the response object

method

return value

illustrate

addHeader(String name,String value)

void

Add an HTTP file header, overwriting if a header with the same name exists

setHeader(String name,String value)

void

Set the value of the header of the file with the specified name, overwriting if it exists

addCookie(Cookie cookie)

void

Add a cookie object to the client

sendError(int sc,String msg)

void

Send an error message to the client. For example: 404 page not found

sendRedirect(String location)

void

Send a request to another specified location

getOutputStream()

ServletOutputStream

Get the client output stream object

setBufferSize(int size)

void

set buffer size

(3) session object

        session is a session object related to the request, which is a java.servlet.http.HttpSession object, which is used to save and store the request information of the page.

        The setAttribute() method of the session object can save information in the session range, and the getAttribute() method can obtain the information stored in the session range.

(4) application object

        The application object can save information in the server until the server is closed, otherwise the information saved in the application object will be valid throughout the application. Compared with the session object, the application object has a longer life cycle, similar to the "global variables" of the system.

Common methods of the application object

method

return value

illustrate

getAttribute(String name)

Object

Return the information stored in the application object by keyword

getAttributeNames()

Enumeration

Get the property names used by all application objects

setAttribute(String key,Object obj)

void

Save an object in the application object by the specified name

getMajorVersion()

int

Get the Servlet version number supported by the server

getServerInfo()

String

Returns information about the JSP engine

removeAttribute(String name)

void

Delete the attribute with the specified name in the application object

getRealPath()

String

Returns the real path of the virtual path

getInitParameter(String name)

String

获取指定nameapplication对象属性的初始值

四、Servlet技术

1、Servlet基础

(1)Servlet与Servlet容器

        Servlet是使用Java Servlet接口(API)运行在Web应用服务器上的Java程序。

        Servlet容器也就是指Web容器,如Tomcat、Jboss、Resin、WebLogic等,它们对Servlet进行控制。

(2)Servlet技术特点

方便、实用的 API 方法
高效的处理方式
更加灵活、扩展
跨平台
安全性

2、Servlet配置

(1)声明Servlet对象

<servlet>

<servlet-name>SimpleServlet</servlet-name>

<servlet-class>com.lyq.SimpleServlet</servlet-class>

</servlet>

(2)映射Servlet

<servlet-mapping>

<servlet-name>SimpleServlet</servlet-name>

<url-pattern>/SimpleServlet</url-pattern>

</servlet-mapping>

3、Servlet 常用的接口和类

(1)Servlet接口

Servlet接口中的方法及说明

   

   

public void init(ServletConfig config)

Servlet实例化后,Servlet容器调用此方法来完成初始化工作

public void service(ServletRequest request,
ServletResponse response)

此方法用于处理客户端的请求

public void destroy()

当Servlet对象应该从Servlet容器中移除时,容器调用此方法,以便释放资源

public ServletConfig getServletConfig()

此方法用于获取Servlet对象的配置信息,返回ServletConfig对象

public String getServletInfo()

此方法返回有关Servlet的信息,它是纯文本格式的字符串,如作者、版本等

ServletConfig接口

   

   

public String getInitParameter(String name)

此方法返回String类型名称为name的初始化参数值

public Enumeration getInitParameterNames()

获取所有初始化参数名的枚举集合

public ServletContext getServletContext()

用于获取Servlet上下文对象

public String getServletName()

返回Servlet对象的实例名

HttpServletRequest接口

   

   

public String getContextPath()

返回请求的上下文路径,此路径以“/”开关

public Cookie[] getCookies()

返回请求中发送的所有cookie对象,返回值为cookie数组

public String getMethod()

返回请求所使用的HTTP类型,如getpost

public String getQueryString()

返回请求中参数的字符串形式,如请求MyServlet?username=mr,则返回username=mr

public String getRequestURI()

返回主机名到请求参数之间部分的字符串形式

public StringBuffer getRequestURL()

返回请求的URL,此URL中不包含请求的参数。注意此方法返回的数据类型为StringBuffer

public String getServletPath()

返回请求URI中的Servlet路径的字符串,不包含请求中的参数信息

public HttpSession getSession()

返回与请求关联的HttpSession对象

HttpServletResponse接口

   

   

public void addCookie(Cookie cookie)

向客户端写入cookie信息

public void sendError(int sc)

发送一个错误状态码为sc的错误响应到客户端

public void sendError(int sc, String msg)

发送一个包含错误状态码及错误信息的响应到客户端,参数sc为错误状态码,参数msg为错误信息

public void sendRedirect(String location)

使用客户端重定向到新的URL,参数location为新的地址

(2)GenericServlet类

        GenericServlet类是一个抽象类,分别实现了Servlet接口与ServletConfig接口。此类实现了除service()之外的其他方法,在创建Servlet对象时,可以继承GenericServlet类来简化程序中的代码,但需要实现service()方法。

(3)HttpServlet类

        HttpServlet类继承了GenericServlet类,通过其对GenericServlet类的扩展,可以很方便地对HTTP请求进行处理及响应。

4、Servlet过滤器

(1)过滤器接口

Filter接口

   

   

public void init(FilterConfig filterConfig)

过滤器的初始化方法,容器调用此方法完成过滤的初始化。对于每一个Filter实例,此方法只被调用一次

public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)

此方法与Servletservice()方法相类似,当请求及响应交给过滤器时,过滤器调用此方法进行过滤处理

public void destroy()

在过滤器生命周期结束时调用此方法,用于释放过滤器所占用的资源

FilterChain接口

void doFilter(ServletRequest request, ServletResponse response) 

throws IOException , ServletException

        此方法主要用于将过滤器处理的请求或响应传递给下一个过滤器对象。在多个过滤器的Web应用中,可以通过此方法进行传递。

FilterConfig接口

   

   

public String getFilterName()

返回过滤器的名称

public String getInitParameter(String name)

返回初始化名称为name的参数值

public Enumeration getInitParameterNames()

返回所有初始化参数名的枚举集合

public ServletContext getServletContext()

返回Servlet的上下文对象

(2)过滤器的配置

        声明过滤器对象

<filter>

<filter-name>CharacterEncodingFilter</filter-name>

<filter-class>com.lyq.util.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>GBK</param-value>

</init-param>

</filter>

        映射过滤器

<filter-mapping>

<filter-name>CharacterEncodingFilter</filter-name>

<url-pattern>/*</url-pattern>

<dispatcher>REQUEST</dispatcher>

<dispatcher>FORWARD</dispatcher>

</filter-mapping>

五、数据库技术——JDBC

1、JDBC概述

        JDBC代表JAVA DATA bASE Connectivity(Java数据库连接),它是一个标准的Java API,用于Java 编程语言和大量数据库之间的独立于数据库的连接。 JDBC库包括用于下面提到的每个任务的API,这些API通常与数据库使用相关联。 与数据库建立连接。 创建SQL或MySQL语句。

2、JDBC驱动程序

        JDBC(java database connectivity)驱动程序是对JDBC规范完整的实现,它的存在在JAVA程序与数据库系统之间建立了一条通信的渠道。分为以下4种:

  • JDBC-ODBC Bridge
  • JDBC-Native API Bridge
  • JDBC-middleware
  • Pure JDBC Driver

3、JDBC中的常用接口

DriverManager(驱动管理器获得数据库链接)

Connection(数据库链接接口)

Statement(语句接口,用来静态操作SQL语句)

PreparedStatement(预定义语句,用来动态操作SQL语句)

CallableStrtement(可以调用存储过程的预定义语句)

ResultSet(结果集,保存数据记录的结果集合)

ResultSetMetaData(结果集元素数据如:列名、列类型)

DatabaseMetaData(数据元数据:数据库名称、版本)

4、连接数据库

(1)加载JDBC驱动程序

try {

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

} catch (ClassNotFoundException e) {

  System.out.println("加载数据库驱动时抛出异常,内容如下:");

  e.printStackTrace();

}

(2)创建数据库连接

Connection conn = DriverManager.getConnection(

 " jdbc:mysql://127.0.0.1:3306/db_database24", "root", "123456");

(3)执行SQL语句

Statement

该类型的实例只能用来执行静态的SQL语句

PreparedStatement

该类型的实例增加了执行动态SQL语句的功能;

CallableStatement

该类型的实例增加了执行数据库存储过程的功能。

(4)获得查询结果

        通过Statement接口的executeUpdate()或executeQuery()方法,可以执行SQL语句,同时将返回执行结果。

(5)关闭连接

resultSet.close();

statement.close();

connection.close();

5、数据库操作技术

(1)增

Statement stmt=conn.createStatement();

int rtn = stmt.executeUpdate

("insert into tb_user (username, password) values('xinxin','111')");

PreparedStatement pStmt = conn.prepareStatement("insert into tb_user (username, password) values(?,?)");

pStmt.setString(1,"book");

pStmt.setString(2,"111");

int rtn= pStmt.executeUpdate();

(2)删

Statement stmt=conn.createStatement();

int rtn= stmt.executeUpdate("delete tb_user where username ='xinxin'");

PreparedStatement pStmt = conn.prepareStatement("delete from tb_user where username =?");

pStmt.setString(1,"book");

int rtn= pStmt.executeUpdate();

(3)改

Statement stmt=conn.createStatement();

int rtn= stmt.executeUpdate("update tb_user set username='xinxin', password='222' where username='book'");

PreparedStatement pStmt = conn.prepareStatement("update tb_user set username =?, password =? where username =?");

pStmt.setString(1,"book");

pStmt.setString(2,"111");

pStmt.setString(3,"class");

int rtn= pStmt.executeUpdate();

(4)查

try {

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

} catch (ClassNotFoundException e) {

  e.printStackTrace();

}

Connection conn = DriverManager

.getConnection(

"jdbc:mysql://localhost/db_database24?useUnicode=true&characterEncoding=utf8",

"root", "123456");

Statement stmt = conn.createStatement();

ResultSet rs = stmt

.executeQuery("select * from tb_user where username='admin'");

while (rs.next()) {

  out.println("Username: " + rs.getString(2) + "Password: " + rs.getString(3));

}

rs.close();

stmt.close();

conn.close();

Guess you like

Origin blog.csdn.net/BIN_2011464841/article/details/125309499