java,web
1. Basic concepts
1.1 Preface
web development:
- Web means web page
- Static web
- html css
- The data provided to everyone will never change
- Dynamic web
- Everyone sees different information at different times and places
- Technology stack: Servlet/Jsp, Asp, PHP
In java, the technology of dynamic web resource development is called javaWeb
1.2. web application
web application: a program that can be provided for browser access
- a.html xx.html... Integrate multiple web resources, which can be accessed by the outside world and provide services to the outside world
- Any page or resource we can access exists on a computer somewhere in the world
- URL
- These unified web resources will be placed in the same folder, and the web application depends on Tomcat
- A web application consists of several parts (static web, dynamic web)
- html,css,js
- jsp,servlet
- java program
- jar package
- Configuration file (properties)
After the web application is written, if you want to provide access to the outside world: you need a server to manage it uniformly;
1.3. Static web
- *.htm
- *.html
[external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-JnMT5bqP-1643023648900)(JavaWeb learning notes. assets/image-20220117163621075.png)]
- Disadvantages of static web
- The web page cannot be refreshed dynamically. All users see the same page. The following methods can be used to improve it
- Rotation chart
- Click effect: pseudo dynamic
- JavaScript
- Unable to interact with the database (data cannot be persisted and users cannot interact)
- The web page cannot be refreshed dynamically. All users see the same page. The following methods can be used to improve it
1.4 dynamic web
The page will be displayed dynamically: it varies from person to person
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-sl4fx4Na-1643023648903)(JavaWeb learning notes. assets/image-20220117163709379.png)]
shortcoming
- There is an error in the dynamic resources added to the server. We need to write a new background program and republish it
- Shutdown maintenance
advantage
- web pages can be refreshed dynamically, and all users do not see the same page
- Can interact with database (data persistence)
- [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Xa7HW655-1643023648903)(JavaWeb learning notes. assets/image-20220117163729012.png)]
2. web server
2.1 three technologies
ASP
- Microsoft: the earliest popular in China
- Embedded VB script ASP + COM in html
- In ASP development, there are thousands of lines of business code in a page -- > the maintenance cost is high
- Mainly use C#
- IIS
PHP
- PHP development is fast, powerful, cross platform and simple code
- Unable to carry large traffic (limitations)
JSP/Servlet
B/S: browser and server
C/S: client and server
- B/S architecture mainly promoted by sun company
- Based on Java language
- It can bear the impact of the three high problems
2.2. web server
Server is a passive operation, which is used to process some requests and give some responses to users
IIS
- Microsoft
- Run ASP
- Built in Windows
Tomcat
Tomcat is a core project in the Jakarta project of the Apache Software Foundation (Apache). The latest Servlet and JSP specification can always be reflected in Tomcat, because Tomcat technology is advanced, stable and free, which is deeply loved by the fans and has been recognized by some software developers. Become a more popular Web application server.
Tomcat server is a free open source Web application server, which belongs to lightweight application The server , it is widely used in small and medium-sized systems and occasions where there are not many concurrent access users. It is the first choice for developing and debugging JSP programs. For a Java web beginner, it is the best choice
Tomcat actually runs JSP pages and servlets. The latest version of Tomcat is 10.0.14.
Download Tomcat
- install
- Understand the configuration file and directory structure
- effect
3,Tomcat
3.1. Installing Tomcat
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-n4aHD7WG-1643023648904)(JavaWeb learning notes. assets/image-20220117163035044.png)]
Note: tar GZ is the installation package under Linux
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-R03KERJ0-1643023648905)(JavaWeb learning notes. assets/image-20220117163111236.png)]
Right click decompression
3.2. Tomcat startup
Role of folders
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-aOciRmnY-1643023648906)(JavaWeb learning notes. assets/image-20220116103324543.png)]
Start and close Tomcat
start-up
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-sPF9bTKb-1643023648907)(JavaWeb learning notes. assets/image-20220116114502302.png)]
Double click this file to run
Enter localhost:8080 / enter in the url address bar of the browser
If successful, you will see the following page [the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-FkxI9K0u-1643023648907)(JavaWeb learning notes. assets/image-20220116114815719.png)]
close
- Close the Tomcat window directly
- [the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-kjdjIeAx-1643023648908)(JavaWeb learning notes. assets/image-20220116115022085.png)]
Possible problems
- Java environment variables are not configured
- Flash back problem: compatibility needs to be configured
- Garbled code problem: set in the configuration file
3.3. Tomcat configuration
Modify boot port
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-WjTsXEu0-1643023648908)(JavaWeb learning notes. assets/image-20220116115254901.png)]
Modify the startup port number, host name in this folder
Configurable ports
- The default port number of Tomcat is 8080
- mysql: 3306
- http: 80
- https: 443
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
Configurable host name
- The default is localhost – > 127.0.0.1
- The default site app location is the webapps folder
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
However, the modified name cannot be accessed successfully
The following practices are required
For example:
-
name = "www.qinjiang.com"
-
Modify host in Windows
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-2iDpfNGp-1643023648909)(JavaWeb learning notes. assets/image-20220116120946549.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-HBOeVIi2-1643023648909)(JavaWeb learning notes. assets/image-20220116121145884.png)]
Restart Tomcat
Modify home page information
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-tzOu61Ji-1643023648910)(JavaWeb learning notes. assets/image-20220116120007535.png)]
Here you can modify the information of accessing the home page
<div id="navigation" class="curved container"> <span id="nav-home"><a href="${tomcatUrl}">Home</a></span> <span id="nav-hosts"><a href="${tomcatDocUrl}">Documentation</a></span> <span id="nav-config"><a href="${tomcatDocUrl}config/">Configuration</a></span> <span id="nav-examples"><a href="${tomcatExamplesUrl}">Examples</a></span> <span id="nav-wiki"><a href="https://wiki.apache.org/tomcat/FrontPage">Wiki</a></span> <span id="nav-lists"><a href="${tomcatUrl}lists.html">Mailing Lists</a></span> <span id="nav-help"><a href="${tomcatUrl}findhelp.html">Find Help</a></span> <br class="separator" /> </div>
How is the website accessed
-
Enter URL enter
-
Check whether there is a mapping of this domain name under the hosts configuration file under C:\Windows\System32\drivers\etc
-
If yes, directly return the corresponding ip address. There are web programs we need to access in this address, which can be accessed directly
127.0.0.1 www.qinjiang.com
-
If not, go to the DNS server to find it and return it if found. If not, return it if not found
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-DKWWM8mp-1643023648910)(JavaWeb learning notes. assets/image-20220116122743387.png)]
-
3.4. Publish a web site
-
Put the website written by yourself under the specified folder (webapps) of Tomcat server
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-wNAzLgtk-1643023648910)(JavaWeb learning notes. assets/image-20220116162649670.png)]
Each folder corresponds to localhost:8080 / folder name
Structure of website
—webapps
— root
- scy: directory name of the website
—WEB-INFO
- classes: java program
- lib: the jar package on which the web reference depends
—web.xml: Web site configuration file
—index.html: default home page
- static: static resource
—css
—**.css
—js
—images
—...
4,http
4.1. What is http
Hypertext Transfer Protocol (HTTP) is a simple request response protocol, which usually runs on TCP.
- Text html string
- Hypertext
- picture
- music
- video
- location
- Map
- Port 80
HTTPS (full name: Hyper Text Transfer Protocol over SecureSocket Layer) is an HTTP channel aiming at security. On the basis of HTTP, it ensures the security of the transmission process through transmission encryption and identity authentication.
- Port 443
4.2 two times of http
- http1.0
- HTTP/1.0: after the client can connect with the web server, it can only obtain one web resource and disconnect
- http2.0
- HTTP/1.1: after the client can connect with the web server, it can obtain multiple web resources
4.3 http request
- The client sends a request to the server
Baidu
General
Request URL: https://www.baidu.com / / request address Request method: GET //Request method Status code: 200 OK //Status code Remote address: 14.215.177.39:443 //Remote address
Request header
Accept: text/html //type Accept-Encoding: gzip, deflate, br //Type code Accept-Language: zh-CN,zh;q=0.9 //language Cache-Control: max-age=0 //cache control Connection: keep-alive //connect
Request line
- GET mode in request line
- Request method: GET, POST, HEAD, DELETE, PUT, trace
- The parameters that get can carry in one request are relatively few, and the size is limited. The content will be displayed in the URL bar of the browser, but it is efficient
- A post request can carry many parameters with unlimited size. It will not display the content in the browser URL, but it is not efficient
Message header
Accept //Tell the browser what data types it supports Accept-Encoding //Tell the browser the supported encoding format GBK UTF-8 GB2312 Accept-Language //Tell the browser his locale Cache-Control //Cache control Connection //Tell the browser whether to disconnect or remain connected after the request Host //host
4.4 http response
- The server returns a response to the client
Baidu
Response header
Cache-Control: private //cache control Connection: keep-alive //Connect: keep connected Content-Encoding: gzip //code Content-Type: text/html;charset=utf-8 //type
Responder
Accept //Tell the browser the data types it supports Accept-Encoding //Tell the browser the supported encoding format GBK UTF-8 GB2312 Accept-Language //Tell the browser his locale Cache-Control //Cache control Connection //Tell the browser whether to disconnect or remain connected after the request Host //host Refresh //Tell the client how often to refresh Location //Repositioning web pages
Response status code
- 200 request response successful
- 3xx request redirection
- Redirect: you return to the new location I gave you
- 4xx resource not found - 404
- Resource does not exist
- 5xx server code error - 500
- 502 gateway error
Common interview questions:
When you enter the address in the address bar of your browser and press enter, the page can show back. What has happened?
5,Maven
Why Maven?
- In Java Web, we need a large number of jar packages, which we need to import manually
- Maven can automatically import and configure jar packages for us
5.1 Maven architecture management tool
We currently use it to import jar packages
Maven's core idea: Convention is greater than configuration
- Don't break the rules
- Maven will specify how you should write our Java code
5.2 Maven Download
Official website: https://maven.apache.org/
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-oEwTto9r-1643023648911)(JavaWeb learning notes. assets/image-20220117093602526.png)]
decompression
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-YKcCx1Mq-1643023648911)(JavaWeb learning notes. assets/image-20220117093853005.png)]
5.3. Configure environment variables
Configure the following in the system environment variable
- M2_ bin directory under home Maven directory
- MAVEN_HOME maven directory
Configure our Maven in the path of the system_ HOME %MAVEN_ HOME%\bin
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-I2nBlWaG-1643023648912)(JavaWeb learning notes. assets/image-20220117095213835.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Ncq0AXHu-1643023648912)(JavaWeb learning notes. assets/image-20220117095243730.png)]
path is also added
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-6jhegRsL-1643023648912)(JavaWeb learning notes. assets/image-20220117095509705.png)]
Test whether the configuration is successful
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-U2ALbMWZ-1643023648913)(JavaWeb learning notes. assets/image-20220117095435349.png)]
5.4 Alibaba cloud image
- mirrors: Mirror
- Function: accelerate our download
- Alibaba cloud image Maven 3 is recommended in China 8.4 self contained, no modification recommended
<mirror> <id>nexus-aliyun</id> <mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf> <name>Nexus aliyun</name> <url>http://maven.aliyun.com/nexus/content/groups/public</url> </mirror>
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (IMG jotpdtyq-1643023648913) (JavaWeb learning notes. assets/image-20220117095851316.png)]
5.5. Establish local warehouse
Local warehouse
Remote warehouse
Build a local repository
Create a new local folder
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-gZtZ25rT-1643023648913)(JavaWeb learning notes. assets/image-20220117100426335.png)]
E:\environment\apache-maven-3.8.4\maven-repo
In the conf folder, click settings Add local warehouse location in XML (notepad software used here, if not, right-click to open notepad)
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-XfTZD2T9-1643023648914)(JavaWeb learning notes. assets/image-20220117100546627.png)]
5.6. Use Maven in idea
-
Start idea
-
Create a maven web project
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (IMG pqpdpulb-1643023648914) (JavaWeb learning notes. assets/image-20220117101933521.png)]
-
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-be0Wmmzm-1643023648914)(JavaWeb learning notes. assets/image-20220117102210722.png)]
Click next
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-UvArtO9c-1643023648915)(JavaWeb learning notes. assets/image-20220117102415660.png)]
Then set the address of the project file and finish
Then wait for the profile to download
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-DJmaZIR3-1643023648915)(JavaWeb learning notes. assets/image-20220117104447804.png)]
- After the idea is created successfully, we should pay attention to
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-FNG8cFt3-1643023648915)(JavaWeb learning notes. assets/image-20220117104716101.png)]
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-d6qPrvL2-1643023648916)(JavaWeb learning notes. assets/image-20220117104828548.png)]
- Here, it's ok to import maven from idea
5.7. Create a common maven project
Uncheck direct next
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG gutlotmr-1643023648916) (JavaWeb learning notes. assets/image-20220117105123716.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-HKP3l4JS-1643023648916)(JavaWeb learning notes. assets/image-20220117105629116.png)]
In the case of webapp above
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-MN2N6Wq7-1643023648916)(JavaWeb learning notes. assets/image-20220117110052208.png)]
In the webapp project above, follow the clean maven project and create a new java resources
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-UXOaWyCh-1643023648917)(JavaWeb learning notes. assets/image-20220117110229041.png)]
5.8. Mark folder function in idea
If your above java resources are inconsistent with mine
Taking java as an example, right-click java
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9Dw74ATz-1643023648917)(JavaWeb learning notes. assets/image-20220117110444242.png)]
Or the sources under file – project structure modules can also be set
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-qh6wynXD-1643023648917)(JavaWeb learning notes. assets/image-20220117110952092.png)]
5.9. Configure Tomcat in idea
1,
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-YOHmyHVj-1643023648918)(JavaWeb learning notes. assets/image-20220117111207736.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-94lIgGNt-1643023648918)(JavaWeb learning notes. assets/image-20220117111452708.png)]
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-VH1WF2qt-1643023648918)(JavaWeb learning notes. assets/image-20220117112141109.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG cjvfsisv-1643023648919) (JavaWeb learning notes. assets/image-20220117112259522.png)]
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-TjheXqxq-1643023648919)(JavaWeb learning notes. assets/image-20220117112517730.png)]
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (IMG aybids5m-1643023648919) (JavaWeb learning notes. assets/image-20220117112932085.png)]
Click ok
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-yfPXQp8I-1643023648920)(JavaWeb learning notes. assets/image-20220117113033883.png)]
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-zHYljh39-1643023648920)(JavaWeb learning notes. assets/image-20220117113309769.png)]
5.10 pom documents
pom.xml is Maven's core configuration file
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zKL9VZcA-1643023648920)(JavaWeb learning notes. assets/image-20220117113601618.png)]
pom file details
<?xml version="1.0" encoding="UTF-8"?> <!--Maven Version and header file--> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!--This is what we just configured GVA--> <groupId>com.si</groupId> <artifactId>javaweb-01-maven</artifactId> <version>1.0-SNAPSHOT</version> <!--Packaging method of the project jar package -java application war package -javaweb application --> <packaging>war</packaging> <!--to configure--> <properties> <!--Default build code for the project--> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!--maven Compiled version of--> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <!--Project dependency--> <dependencies> <!--Specific dependent jar package--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <!--Things for project construction--> <build> <finalName>javaweb-01-maven</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-tAKOwSwW-1643023648921)(JavaWeb learning notes. assets/image-20220117115510005.png)]
Because maven's convention is greater than configuration, we may encounter the problem that the configuration file we wrote cannot be exported or take effect. Solution: configure the resource node
<!--stay build Medium configuration resources,To prevent the failure of resource export--> <build> <resources> <resource> <directory>src/main/resources</directory> <excludes> <exclude>**/*.properties</exclude> <exclude>**/*.xml</exclude> </excludes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
5.11. idea operation directory tree
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-KNSFMrbo-1643023648921)(JavaWeb learning notes. assets/image-20220117120136842.png)]
5.12 use of Maven repository
Address: https://mvnrepository.com/
Take servlet API as an example
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-59n0MSZ5-1643023648921)(JavaWeb learning notes. assets/image-20220117132139780.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wR0ken3J-1643023648921)(JavaWeb learning notes. assets/image-20220117132301353.png)]
6,Servlet
6.1 introduction to servlet
- It is a technology for sun company to develop dynamic web
- sun provides an interface in these API s - servlet s
- If you want to develop a servlet applet, you only need to complete two steps
- Write a class to implement the servlet interface
- Deploy the developed java classes to the web server
The Java code that implements the servlet interface is called servlet
6.2,HelloServlet
Servlet has two implementation interfaces in sun company: HTTPServlet and GenericServlet
-
Build a maven project and delete the src directory. In the future, we will build a module here. This empty project is the main project of Maven
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Ubxi9qrf-1643023648922)(JavaWeb learning notes. assets/image-20220117140753900.png)]
New sub module
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-5IHaKfx6-1643023648922)(JavaWeb learning notes. assets/image-20220117140847213.png)]
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-N6BtOQFQ-1643023648922)(JavaWeb learning notes. Assets / image-2022011714093353533. PNG)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-gFTegbfm-1643023648923)(JavaWeb learning notes. assets/image-20220117140948861.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-NTe1Row8-1643023648923)(JavaWeb learning notes. assets/image-20220117141040878.png)]
-
Understanding of Maven father son project
-
There is a mudule in the pom in the parent project
<modules> <module>servlet-01</module> </modules>
-
The pom in the child project has a parent (if you don't, delete the scope in the parent project pom first)
<parent> <artifactId>javaweb-02-Servlet</artifactId> <groupId>com.si</groupId> <version>1.0-SNAPSHOT</version> </parent>
-
The son project can use the jar package of the father project
-
Maven environment optimization
- Modify web XML is the format in the latest version of apache-tomcat-10.0.14\webapps\ROOT\WEB-INF
- Complete Maven's structure
-
Create a new servlet program
-
Write a common class
-
Implement servlet interface and inherit HTTP Servlet
package com.si.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class HelloServlet extends HttpServlet { //Because Get Post is only a different way of request implementation, it can be called each other, and the business logic is the same @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); //Response flow writer.print("Hello Servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
-
-
Write the mapping map of Servlet
Why do we need mapping?
Because we write java programs that need to be accessed through the browser, and the browser needs to access the web server, we need to register the Servlet program we write in the web server and give it a mapping that the browser can access
On the web Register in XML
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0" metadata-complete="true"> <!--register Servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.si.servlet.HelloServlet</servlet-class> </servlet> <!--Servlet Request path for--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>hello</url-pattern> </servlet-mapping> </web-app>
-
Configure Tomcat
Note the configured project publishing path
- Start test
6.3 principle of Servlet
The servlet is called by the web server. After receiving the browser request, the web server will
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-uM5rZnsU-1643023648923)(JavaWeb learning notes. assets/image-20220119105510642.png)]
6.4,Mapping
-
A Servlet can specify a mapping path
<!--Servlet Request path for--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
-
A Servlet can specify multiple mapping paths
<!--Servlet Request path for--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello1</url-pattern> </servlet-mapping>
-
A Servlet can specify a common mapping path
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping> <!--Default request path--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
-
Specify some prefixes, suffixes, etc
<!--Servlet Request path for--> <!--as long as.scy Can be accessed /hello/sssss.scy Can also access *Item mapping path cannot be added before --> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.scy</url-pattern> </servlet-mapping>
-
Priority issues
The inherent mapping path is specified with the highest priority. If it cannot be found, the default processing request will be taken
<!--Register default Servlet request--> <servlet> <servlet-name>error</servlet-name> <servlet-class>com.si.servlet.ErrorServlet</servlet-class> </servlet> <!--Servlet Request path for--> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
6.5,ServletContext
When the web container starts, it will create a servletContext object for all web applications, which represents the current web application
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Xfg1dFHQ-1643023648923)(JavaWeb learning notes. assets/image-20220119123654484.png)]
6.51. Shared data
The data I saved in this servlet can also be obtained in another servlet
Placed class
package com.si.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //this.getInitParameter() get initialization parameters //this.getServletConfig() get servlet configuration //this.getServletContext() get servlet context ServletContext servletContext = this.getServletContext(); String username = "Si Chengyong"; //data servletContext.setAttribute("username",username); //A data is saved in the ServletContext with the name username and the value username System.out.println("hello"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
Read class
package com.si.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); String username = (String) servletContext.getAttribute("username"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); resp.getWriter().print(username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
Configure web xml
<servlet> <servlet-name>hello</servlet-name> <servlet-class>com.si.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>getc</servlet-name> <servlet-class>com.si.servlet.GetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>getc</servlet-name> <url-pattern>/getc</url-pattern> </servlet-mapping>
6.52. Get initialization parameters
<!--Configure initialization parameters--> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybaits</param-value> </context-param>
Get initialization parameters
package com.si.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ServletDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //this.getInitParameter() get initialization parameters //this.getServletConfig() get servlet configuration //this.getServletContext() get servlet context ServletContext servletContext = this.getServletContext(); String url = servletContext.getInitParameter("url"); resp.getWriter().print(url); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
Register servlet
<servlet> <servlet-name>gp</servlet-name> <servlet-class>com.si.servlet.ServletDemo03</servlet-class> </servlet> <servlet-mapping> <servlet-name>gp</servlet-name> <url-pattern>/gp</url-pattern> </servlet-mapping>
6.53 request forwarding
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ZjVOE8kX-1643023648924)(JavaWeb learning notes. assets/image-20220119131458425.png)]
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //this.getInitParameter() get initialization parameters //this.getServletConfig() get servlet configuration //this.getServletContext() get servlet context System.out.println("Entered servletDemo04"); ServletContext servletContext = this.getServletContext(); /* Write separately RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/gp"); //Forwarded request path requestDispatcher.forward(req,resp); //Call forward to forward the request */ servletContext.getRequestDispatcher("/gp").forward(req,resp); }
6.54. Read resource files
properties
- Create properties under java
- Create properties under resources
The discovery is packaged in the same path (classes, commonly known as classpath)
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-L96xfNmG-1643023648924)(JavaWeb learning notes. assets/image-20220119133456288.png)]
properties file
username=root password=123456
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); InputStream resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/classes/db.properties");//Read resources Properties properties = new Properties(); properties.load(resourceAsStream); //Load resource content System.out.println("account" + properties.get("username") + "password" + properties.get("password")); }
Register servlet
<servlet> <servlet-name>sd5</servlet-name> <servlet-class>com.si.servlet.ServletDemo05</servlet-class> </servlet> <servlet-mapping> <servlet-name>sd5</servlet-name> <url-pattern>/sd5</url-pattern> </servlet-mapping>
6.6,(HttpServlet)Request
(HttpServlet)Request represents the request of the client. The user accesses the server through the Http protocol. All the information in the Http request will be encapsulated in the HttpServletRequest. Through this HttpServletRequest method, all the information of the client can be obtained
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wF8OwjEe-1643023648924)(JavaWeb learning notes. assets/image-20220120135242702.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG zoqcalmm-1643023648925) (JavaWeb learning notes. assets/image-20220120135305592.png)]
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-twlIGYk3-1643023648925)(JavaWeb learning notes. assets/image-20220120135340385.png)]
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-Q7iLtY7c-1643023648925)(JavaWeb learning notes. assets/image-20220120135358400.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-1TJyFqDb-1643023648926)(JavaWeb learning notes. Assets / image-20220135409881. PNG)]
6.61. Obtain the information transmitted by the front end and forward the request
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-NdMBluQt-1643023648926)(JavaWeb learning notes. assets/image-20220120135715649.png)]
package com.si.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //The background accepts Chinese garbled code req.setCharacterEncoding("UTF-8"); //Chinese garbled code at the front desk resp.setCharacterEncoding("UTF-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobbies = req.getParameterValues("hobby"); //Get multiple values, multiple check boxes System.out.println("username:" + username + "\t password:" + password + "\nhobbies:" + Arrays.toString(hobbies)); //redirect //resp.sendRedirect("/r2/success.jsp"); /// here represents the current web application when forwarding the request, so / r2 is not added req.getRequestDispatcher("/success.jsp").forward(req,resp); } }
Interview question: the relationship between redirection and forwarding
- Same point
- Page Jump
- difference
- The URL will not change when the request is forwarded 307
- When redirecting, the URL will change 302
6.7,(HttpServlet)Response
The web server receives the http request from the client. For this request, an HttpServletRequest object representing the request and an HttpServletResponse request representing the response are created respectively
- Get the parameter HttpServletRequest requested from the client
- If you want to respond to some information to the client, HttpServletResponse
6.71 simple classification
Method responsible for sending data to browser
getOutputStreampublic ServletOutputStream getOutputStream() throws IOException; public PrintWriter getWriter() throws IOException;
Method responsible for sending response header to browser
public void setCharacterEncoding(String charset); public void setContentLength(int len); public void setContentLengthLong(long len); public void setContentType(String type); public void setDateHeader(String name, long date); public void addDateHeader(String name, long date); public void setHeader(String name, String value); public void addHeader(String name, String value); public void setIntHeader(String name, int value); public void addIntHeader(String name, int value);
Response status code
/** * Status code (100) indicating the client can continue. */ public static final int SC_CONTINUE = 100; /** * Status code (101) indicating the server is switching protocols * according to Upgrade header. */ public static final int SC_SWITCHING_PROTOCOLS = 101; /** * Status code (200) indicating the request succeeded normally. */ public static final int SC_OK = 200; /** * Status code (201) indicating the request succeeded and created * a new resource on the server. */ public static final int SC_CREATED = 201; /** * Status code (202) indicating that a request was accepted for * processing, but was not completed. */ public static final int SC_ACCEPTED = 202; /** * Status code (203) indicating that the meta information presented * by the client did not originate from the server. */ public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; /** * Status code (204) indicating that the request succeeded but that * there was no new information to return. */ public static final int SC_NO_CONTENT = 204; /** * Status code (205) indicating that the agent <em>SHOULD</em> reset * the document view which caused the request to be sent. */ public static final int SC_RESET_CONTENT = 205; /** * Status code (206) indicating that the server has fulfilled * the partial GET request for the resource. */ public static final int SC_PARTIAL_CONTENT = 206; /** * Status code (300) indicating that the requested resource * corresponds to any one of a set of representations, each with * its own specific location. */ public static final int SC_MULTIPLE_CHOICES = 300; /** * Status code (301) indicating that the resource has permanently * moved to a new location, and that future references should use a * new URI with their requests. */ public static final int SC_MOVED_PERMANENTLY = 301; /** * Status code (302) indicating that the resource has temporarily * moved to another location, but that future references should * still use the original URI to access the resource. * * This definition is being retained for backwards compatibility. * SC_FOUND is now the preferred definition. */ public static final int SC_MOVED_TEMPORARILY = 302; /** * Status code (302) indicating that the resource reside * temporarily under a different URI. Since the redirection might * be altered on occasion, the client should continue to use the * Request-URI for future requests.(HTTP/1.1) To represent the * status code (302), it is recommended to use this variable. */ public static final int SC_FOUND = 302; /** * Status code (303) indicating that the response to the request * can be found under a different URI. */ public static final int SC_SEE_OTHER = 303; /** * Status code (304) indicating that a conditional GET operation * found that the resource was available and not modified. */ public static final int SC_NOT_MODIFIED = 304; /** * Status code (305) indicating that the requested resource * <em>MUST</em> be accessed through the proxy given by the * <code><em>Location</em></code> field. */ public static final int SC_USE_PROXY = 305; /** * Status code (307) indicating that the requested resource * resides temporarily under a different URI. The temporary URI * <em>SHOULD</em> be given by the <code><em>Location</em></code> * field in the response. */ public static final int SC_TEMPORARY_REDIRECT = 307; /** * Status code (400) indicating the request sent by the client was * syntactically incorrect. */ public static final int SC_BAD_REQUEST = 400; /** * Status code (401) indicating that the request requires HTTP * authentication. */ public static final int SC_UNAUTHORIZED = 401; /** * Status code (402) reserved for future use. */ public static final int SC_PAYMENT_REQUIRED = 402; /** * Status code (403) indicating the server understood the request * but refused to fulfill it. */ public static final int SC_FORBIDDEN = 403; /** * Status code (404) indicating that the requested resource is not * available. */ public static final int SC_NOT_FOUND = 404; /** * Status code (405) indicating that the method specified in the * <code><em>Request-Line</em></code> is not allowed for the resource * identified by the <code><em>Request-URI</em></code>. */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** * Status code (406) indicating that the resource identified by the * request is only capable of generating response entities which have * content characteristics not acceptable according to the accept * headers sent in the request. */ public static final int SC_NOT_ACCEPTABLE = 406; /** * Status code (407) indicating that the client <em>MUST</em> first * authenticate itself with the proxy. */ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** * Status code (408) indicating that the client did not produce a * request within the time that the server was prepared to wait. */ public static final int SC_REQUEST_TIMEOUT = 408; /** * Status code (409) indicating that the request could not be * completed due to a conflict with the current state of the * resource. */ public static final int SC_CONFLICT = 409; /** * Status code (410) indicating that the resource is no longer * available at the server and no forwarding address is known. * This condition <em>SHOULD</em> be considered permanent. */ public static final int SC_GONE = 410; /** * Status code (411) indicating that the request cannot be handled * without a defined <code><em>Content-Length</em></code>. */ public static final int SC_LENGTH_REQUIRED = 411; /** * Status code (412) indicating that the precondition given in one * or more of the request-header fields evaluated to false when it * was tested on the server. */ public static final int SC_PRECONDITION_FAILED = 412; /** * Status code (413) indicating that the server is refusing to process * the request because the request entity is larger than the server is * willing or able to process. */ public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413; /** * Status code (414) indicating that the server is refusing to service * the request because the <code><em>Request-URI</em></code> is longer * than the server is willing to interpret. */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** * Status code (415) indicating that the server is refusing to service * the request because the entity of the request is in a format not * supported by the requested resource for the requested method. */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** * Status code (416) indicating that the server cannot serve the * requested byte range. */ public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** * Status code (417) indicating that the server could not meet the * expectation given in the Expect request header. */ public static final int SC_EXPECTATION_FAILED = 417; /** * Status code (500) indicating an error inside the HTTP server * which prevented it from fulfilling the request. */ public static final int SC_INTERNAL_SERVER_ERROR = 500; /** * Status code (501) indicating the HTTP server does not support * the functionality needed to fulfill the request. */ public static final int SC_NOT_IMPLEMENTED = 501; /** * Status code (502) indicating that the HTTP server received an * invalid response from a server it consulted when acting as a * proxy or gateway. */ public static final int SC_BAD_GATEWAY = 502; /** * Status code (503) indicating that the HTTP server is * temporarily overloaded, and unable to handle the request. */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** * Status code (504) indicating that the server did not receive * a timely response from the upstream server while acting as * a gateway or proxy. */ public static final int SC_GATEWAY_TIMEOUT = 504; /** * Status code (505) indicating that the server does not support * or refuses to support the HTTP protocol version that was used * in the request message. */ public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
6.72 downloading files
-
Output message to browser
-
Download File
- Gets the path to the downloaded file
- Downloaded file name
- Set up a way to make the browser support downloading what we need
- Gets the input stream of the downloaded file
- Create buffer
- Get outputstream object
- Write Fileoutputstream to buffer
- Use outputstream to output the data of the buffer to the client
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. Get the path of the downloaded file String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/images/1.png"); System.out.println("True path of file:" + realPath); //2. Downloaded file name String FileName = realPath.substring(realPath.lastIndexOf("\\") + 1); System.out.println(FileName); //3. Set up a way to make the browser support (content disposition) to download what we need. The Chinese file name is urlencoder Encode solution resp.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(FileName,"UTF-8")); //4. Obtain the input stream of the downloaded file FileInputStream in = new FileInputStream(realPath); //5. Create buffer int len = 0; byte[] buffer = new byte[1024]; //6. Get outputstream object ServletOutputStream out = resp.getOutputStream(); //7. Write Fileoutputstream to the buffer and use outputstream to output the data of the buffer to the client while ((len=in.read(buffer)) > 0) { out.write(buffer,0,len); } in.close(); out.close(); }
6.73 verification code function
How do I get the verification code?
- Front end implementation js
- The back-end implementation needs to use the java picture class to generate a picture
package com.si.servlet; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //How to make the browser refresh automatically every 5 seconds resp.setHeader("refresh","3"); //Create a picture in memory BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); //Get pictures Graphics2D graphics = (Graphics2D)image.getGraphics(); //A brush //Set the background color of the picture graphics.setColor(Color.WHITE); graphics.fillRect(0,0,80,20); //Write data to pictures graphics.setColor(Color.BLUE); graphics.setFont(new Font(null, Font.BOLD,20)); graphics.drawString(makeRandomArray(),0,20); //Tell the browser to open the request as a picture resp.setContentType("image/png"); //There is a cache on the website. Do not let the browser cache resp.setDateHeader("expires",-1); resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Pragma","no-cache"); //Write the picture to the browser boolean is_ok = ImageIO.write(image,"jpg" ,resp.getOutputStream()); } //Generate random number private String makeRandomArray() { Random random = new Random(); String array = String.valueOf(random.nextInt(9999999)); StringBuffer sb = new StringBuffer(); //If the length is not enough, fill 0 with 7 for (int i = 0; i < 7-array.length(); i++) { sb.append("0"); } array = sb.toString() + array; return array; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
6.74 redirection
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-euQurl9g-1643023648926)(JavaWeb learning notes. Assets / image-20220130814509. PNG)]
After a web resource receives a client request, it will notify the client to access another web resource. This process is called redirection.
Common scenarios:
- User login
public void sendRedirect(String location) throws IOException;
test
resp.sendRedirect("/r1/image");
Equivalent to the following
resp.setHeader("Location","/r1/image"); resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
Interview question: the relationship between redirection and forwarding
- Same point
- Page Jump
- difference
- The URL will not change when the request is forwarded
- The URL will change during redirection
7,Session,Cookie
7.1 conversation
Session: users open a browser, click many hyperlinks, access multiple web resources, and close the browser. This process is called session.
Stateful conversation: a classmate has been to the classroom. Next time we come back, we will know that this classmate has been to the classroom
How can you prove that you are Chinese?
- Resident ID card of the people's Republic of China -- the ID card given to you by the state
- The country has registered you -- the country marks you as Chinese
How does a website prove you've been here
Client server
- The server sends a letter to the client, and the client can bring the letter to the server next time Cookie
- The server registers that you have been here. Next time you come, I'll match you; - Session
7.2. Two techniques for saving sessions
Cookie
- Client Technology (Response,Request)
Session
- Server side technology. Using this technology, we can save the user's Session information. We can put the information or data in the Session
Common scenarios:
- After the website is logged in, you can log in directly the next time you visit
7.3,Cookie
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wk3TjNqG-1643023648927)(JavaWeb learning notes. assets/image-20220121125141046.png)]
- Get cookie information from the request
- The server responds to the client
//cookie, the server obtains the request from the client //Returns an array indicating that there may be multiple cookies Cookie[] cookies = req.getCookies(); //Get the name of the cookie String name = cookie.getName(); //Get cookie Value value of name cookie.getValue() //Create a new cookie Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + ""); //Cookies are valid for one day cookie.setMaxAge(24*60*60); //The server gives the client a cookie resp.addCookie(cookie);
Cookies are generally saved in the local user directory appdata;
Is there an upper limit for a website cookie?
- A cookie can only hold one piece of information
- A web site can send multiple cookie s to the browser, but can store up to 20
- The cookie size is limited to 4KB
- The browser can accept cookie s up to 300
delete cookie
- If the validity period is not set, it will be deleted automatically when the browser is closed
- Set the validity period. The validity period is 0
Prevent garbled code -- encoding and decoding
URLEncoder.encode("Si Chengyong","utf-8") //code URLDecoder.decode(cookie.getValue(),"utf-8") //decode
7.4. Session (key)
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-CZIDdwqb-1643023648927)(JavaWeb learning notes. assets/image-20220121125331423.png)]
What is a Session?
- The server will create a Session object for each user (browser)
- A Session monopolizes a browser. As long as the browser is not closed, the Session exists
- After a user logs in, he can access session -- > to save user information and shopping cart information throughout the website
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-jnp20kzY-1643023648927)(JavaWeb learning notes. assets/image-20220121102603761.png)]
Use of Session
//Get Session HttpSession session = req.getSession(); //Pass something to Session session.setAttribute("name",new Person("Si Chengyong",21)); //Get the id of the session String id = session.getId(); //Judge whether the session is newly created boolean aNew = session.isNew(); //What did the Session do when it was created //Cookie cookie = new Cookie("JSESSIONID", session.getId()); //resp.addCookie(cookie); //Get Session HttpSession session = req.getSession(); //Get property value Object person = session.getAttribute("name"); session.removeAttribute("name"); //Log off Session manually session.invalidate();
Session expires automatically
<!--set up Session Default expiration time--> <session-config> <!--1min after Session Automatic failure--> <session-timeout>1</session-timeout> </session-config>
The difference between Session and Cookie
- Cookie is to write the user's data to the user's browser, and the browser saves it (multiple can be saved)
- Session is to write the user's data into the user's exclusive session and save it on the server side (save important information and reduce the waste of server resources)
- The Session object is created by the server
Usage scenario:
- Save a user's login information
- Save cart information
- The data that is often used in the whole website is saved in the Session
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-i3YHAyiQ-1643023648927)(JavaWeb learning notes. assets/image-20220121125544254.png)]
8,JSP
8.1. What is JSP
Java Server Pages: Java server pages, like servlets, are used to develop dynamic web technology
Biggest features:
- Writing JSP is like writing HTML
- difference:
- HTML provides users with static data
- Java code can be embedded in JSP pages to provide users with dynamic data
8.2 JSP principle
Idea: how does JSP execute?
-
There are no problems at the code level
-
Server Internal:
There is a work directory in Tomcat; If Tomcat is used in Idea, a work directory will be produced in Tomcat
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-2vYBFvdX-1643023648928)(JavaWeb learning notes. assets/image-20220121132308980.png)]
The source code address that can be found on my computer
E:\environment\apache-tomcat-10.0.14\work\Catalina\localhost\ROOT\org\apache\jsp
Finally, the jsp page is converted into a java file
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-r85jq9UU-1643023648928)(JavaWeb learning notes. assets/image-20220121133532020.png)]
The browser sends a request to the server. No matter what resource is accessed, it is actually accessing the Servlet
JSP will eventually be converted into Java classes
JSP is essentially a Servlet
public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final jakarta.servlet.http.HttpServletRequest request, final jakarta.servlet.http.HttpServletResponse response) throws java.io.IOException, jakarta.servlet.ServletException { }
-
Judgment request
-
Built in some objects Tomcat9
final jakarta.servlet.jsp.PageContext pageContext; //page javax.servlet.http.HttpSession session; //session final jakarta.servlet.ServletContext application; //applicationContext final jakarta.servlet.ServletConfig config; //config javax.servlet.jsp.JspWriter out = null; //out final java.lang.Object page = this; //page: current HttpServletRequest request //request HttpServletResponse response //response
-
Enter the code added before the page
response.setContentType("text/html;charset=UTF-8"); //Set the page type of the response pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out;
-
The above objects can be directly applied in JSP
principle
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-oVwvsjJS-1643023648928)(JavaWeb learning notes. assets/image-20220121191341422.png)]
In JSP, as long as it is Java code, it will be output intact
If it is HTML code, it will be converted to out write()
8.3. JSP basic syntax
Any language has its own syntax. JSP, as an application of Java, also has its own extended syntax (understand). All Java grammars support it!
JSP expression
<%--JSP expression Used to output the output of the program to the client <%= Variable or expression%> --%> <%= new Date()%>
JSP script fragment
<%--JSP Script fragment--%> <hr> <% int sum = 0; for (int i = 0; i < 100; i++) { sum += i; } out.println("<h1>sum = " + sum + "</h1>"); %>
Re implementation of script fragments
<% int x = 10; out.print(x); %> <p>This is a JSP file</p> <% int y = 1; out.print(y); %> <hr> <%--Embedding in code HTML element--%> <% for (int i = 0; i < 5; i++) { %> <h1>Hello world! <%= i%></h1> <% } %>
JSP declaration
<%! static { System.out.println("Loading Servlet!"); } private static int globalVar = 0; public static void si() { System.out.println("Hello!"); } %>
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-BelSnvAF-1643023648929)(JavaWeb learning notes. assets/image-20220122103316129.png)]
The JSP declaration will be compiled into the java class generated by JSP, and the other three will be generated into**_ jspService * * method
Just embed java code in JSP
<%%> Code snippet <%= %> jsp expression <%! %> jsp statement
8.4. JSP instruction
<%@ page args... %> <%@include file=""%> Extract public pages
Custom error page
First kind
<%@ page errorPage="error/500.jsp" %>
<%--500.jsp--%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>500</title> </head> <body> <img src="../images/500.png" alt="Server error"> </body> </html>
The second web Configuration in XML
<error-page> <error-code>404</error-code> Error type <location>/error/404.jsp</location> Address of the response error page </error-page> <error-page> <error-code>500</error-code> <location>/error/500.jsp</location> </error-page>
Extract public pages
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%@ include file="common/header.jsp"%> <h1>Web Theme</h1> <%@ include file="common/footer.jsp"%> <%--jsp label common Add it before you want it/ --%> <jsp:include page="/common/header.jsp"/> <h1>Web Theme</h1> <jsp:include page="/common/footer.jsp"/> </body> </html>
The difference between the two methods
include file is to get the content
If there is an int x = 1 in the include file
If int x = 10 is also introduced, an error will be reported and the definition will be repeated
out.write("<h1>I am header</h1>"); out.write("\r\n"); out.write(" <h1>Web Theme</h1>\r\n"); out.write(" "); out.write("\r\n"); out.write("\r\n"); out.write("<h1>I am footer</h1>\r\n");
jsp tags are spliced page essence or three
static { _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(2); _jspx_dependants.put("/common/header.jsp", Long.valueOf(1642820803792L)); _jspx_dependants.put("/common/footer.jsp", Long.valueOf(1642820837149L)); }
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/common/header.jsp", out, false); out.write("\r\n"); out.write(" <h1>Web Theme</h1>\r\n"); out.write(" "); org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/common/footer.jsp", out, false);
8.5 and 9 built-in objects
- PageContext stores data
- Request store data
- Response
- Session store data
- Application (ServletContext) stores data
- Config (ServletConfig)
- Out
- Page
- Exception
<% pageContext.setAttribute("name1","Si Chengyong 1"); //The saved page is only valid in one page request.setAttribute("name2","Si Chengyong 2"); //The saved data is valid only in one request session.setAttribute("name3","Si Chengyong 3"); //The saved data is valid in one session (from opening the browser to closing the browser or the session expires) application.setAttribute("name4","Si Chengyong 4"); //The saved data is valid in the server, from opening the server to closing the server %>
Request: the client sends a request to the server, and the generated data is useless after the user reads it, such as news
session: the client sends a request to the server. The generated data is still useful when the user runs out, such as a shopping cart
Application: when the client sends a request to the server, the generated data may be used up by one user, but other users may still be able to use it, such as chat data
/*Get the search method through pageContext * From the bottom to the top (SCOPE) * */ String name1 = (String) pageContext.findAttribute("name1"); String name2 = (String) pageContext.findAttribute("name2"); String name3 = (String) pageContext.findAttribute("name3"); String name4 = (String) pageContext.findAttribute("name4"); String name5 = (String) pageContext.findAttribute("name5"); //Nonexistent data <%--use EL Expression output ${}--%> <h1>The extracted value is: ${name1}</h1> <h1>The extracted value is: ${name2}</h1> <h1>The extracted value is: ${name3}</h1> <h1>The extracted value is: ${name4}</h1> <h1>The extracted value is: ${name5}</h1> null pageContext.setAttribute("hello","hello",PageContext.SESSION_SCOPE); // Equivalent to session setAttribute pageContext Medium setAttribute method public void setAttribute (String name, Object attribute, int scope) { switch (scope) { case PAGE_SCOPE: mPage.put (name, attribute); break; case REQUEST_SCOPE: mRequest.put (name, attribute); break; case SESSION_SCOPE: mSession.put (name, attribute); break; case APPLICATION_SCOPE: mApp.put (name, attribute); break; default: throw new IllegalArgumentException ("Bad scope " + scope); } }
8.6. JSP tag, JSTL tag, EL expression
<!--JSTL Dependency of expression--> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <!--standard Tag library--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>
EL expression ${}
- get data
- Perform operations
- Get common objects of web Development
- Call Java method
JSP tag
<%--Parameters can be carried during forwarding--%> <jsp:forward page="/jsptag2.jsp"> <jsp:param name="name" value="sichenyong"/> <jsp:param name="age" value="21"/> </jsp:forward> <%--Take parameters--%> <span>name:</span><%=request.getParameter("name")%></br> <span>Age:</span><%=request.getParameter("age")%>
JSTL expression
JSTL tag library is used to make up for the shortcomings of HTML tags. It has customized many tags for me to use. The tag function is the same as that of Java code
-
Core label
-
The header must be introduced
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
-
[the external link picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-2KaWprM2-1643023648929)(JavaWeb learning notes. assets/image-20220122140142264.png)]
-
Use steps
- Introduce the corresponding taglib tag header
- Use his method
- JSTL standard jar package should also be introduced into Tomcat, otherwise the parsing failure error will be reported
-
c:if test
<body> <h4>if test</h4> <hr> <form action="coreif.jsp" method="get"> <%--EL Expression to get the data in the form ${param.Parameter name} --%> <input type="text" name="username" value="${param.username}"> <input type="submit" value="Sign in"> </form> <%-- Judge that if the submitted user name is administrator, the submission is successful --%> <%--<% if (request.getParameter("username").equals("admin")) { out.print("Login succeeded!"); } %>--%> <%-- test: Judgment text var: The return value variable name is true false scope: Scope --%> <c:if test="${param.username == 'admin'}" var="isAdmin" scope="request"> <c:out value="Welcome! My dear administrator"/> </c:if> <c:out value="${isAdmin}"/> </body>
-
Corechen test
<body> <%--Defines an achievement 87--%> <c:set var = "score" value="87"/> <%--amount to Switch--%> <c:choose> <c:when test="${score >= 90}"> excellent </c:when> <c:when test="${score >= 80 && score < 90}"> good </c:when> <c:when test="${score >= 60 && score < 80}"> pass </c:when> </c:choose> </body>
-
coreforeach
<body> <% ArrayList<String> people = new ArrayList<>(); people.add(0,"Zhang San a"); people.add(1,"Zhang San"); people.add(2,"Li Si"); people.add(3,"Wang Wu"); people.add(4,"Zhao Liu"); people.add(5,"pseudo-ginseng"); request.setAttribute("list",people); %> <%-- var Variables traversed each time items Array to be traversed --%> <c:forEach var="people" items="${list}"> <c:out value="${people}"/> <br> </c:forEach> <%-- var Variables traversed each time items Array to be traversed begin Start subscript end End subscript step step --%> <c:forEach var="people" items="${list}" begin="1" end="3" step="2"> <c:out value="${people}"/> <br> </c:forEach> </body>
-
-
Format label
-
Lead in head
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
-
Related operations
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Ex7qTjFt-1643023648929)(JavaWeb learning notes. assets/image-20220122150219546.png)]
-
-
SQL tag
-
Lead in head
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
-
Related operations
[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ysATJn3H-1643023648930)(JavaWeb learning notes. assets/image-20220122150236374.png)]
-
-
XML tag
-
Lead in head
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
-
Related operations
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-B6aZhFkM-1643023648930)(JavaWeb learning notes. assets/image-20220122150253712.png)]
-
-
JSTL function
-
Lead in head
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
-
Related operations
[the transfer of external chain pictures failed. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-uvjtpgdM-1643023648930)(JavaWeb learning notes. assets/image-20220122150311346.png)]
-
9,JavaBean
Entity class
JavaBean s have a fixed way of writing
- There must be a parameterless construct
- Property must be privatized
- There must be a corresponding get/set method
The ORM is generally used to map fields in the database
ORM: object mapping relationship
- Table -- > class
- Fields -- > Properties
- Row record -- > object
people table
id | name | age |
---|---|---|
1 | Si Chengyong 1 | 13 |
2 | Si Chengyong 2 | 17 |
3 | Si Chengyong 3 | 21 |
class People { private Integer id; private String name; private Integer age; } new People(4,"Si Chengyong 4",25);
- filter
- File upload
- Mail sending
- JDBC review: how to use JDBC, JDBC crud, JDBC transaction
- GUI listener
10. MVC three-tier architecture
10.1. What is MVC
Model View Controller
Early years
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-50SE0mc9-1643023648931)(JavaWeb learning notes. assets/image-20220123135132173.png)]
Users directly access the control layer, and the control layer can directly operate the database
servlet --> crud --> database Disadvantages: the program is bloated, which is not conducive to maintenance servlet In the code of: processing request, response, view jump, processing JDBC,Processing business code and processing logic code In the idea of architecture, nothing can not be solved by adding a layer programmer | JDBC | mysql oracle sqlServer..
10.2 three tier architecture
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-eYE5Sm90-1643023648931)(JavaWeb learning notes. assets/image-20220123140645213.png)]
Model
- Business processing: business logic (Service layer)
- Data persistence layer: CRUD(Dao layer)
View
- Display data
- Provide connection and initiate Servlet request (a,form,image...)
Controller(Servlet)
-
Receive user's request (request: request parameters, session, cookie)
-
Give it to the business layer to process the corresponding code
-
Control view jump
Sign in --> Receive user's request --> Processing user requests(Get user login parameters:username password) --> Give it to the business layer to handle the login business(Judge whether the user name and password are correct, and the transaction) --> Dao Check whether the user name and password are correct --> database
11. Filter (important)
Shiro
Filter: filter, which is used to filter the data of the website
- Deal with Chinese garbled code
- validate logon
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-6vCC4PRG-1643023648931)(JavaWeb learning notes. assets/image-20220123165336791.png)]
Filter development steps: implement the interface and rewrite the corresponding method
-
Guide Package
-
Write filter
-
Do not import javax by mistake servlet.*; implements Filter
-
package com.si.filter; import javax.servlet.*; import java.io.IOException; public class CharacterEncodingFilter implements Filter { //Initializing the web server startup filter starts the characterencoding filter initialization! @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharacterEncodingFilter initialization!"); } /* 1.All codes in the filter will be executed when filtering specific requests 2.The filter must continue to pass through filterchain doFilter(servletRequest,servletResponse) */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); servletResponse.setContentType("text/html;charset=utf-8"); System.out.println("CharacterEncodingFilter Before execution...."); filterChain.doFilter(servletRequest,servletResponse); //Let our request continue. If we don't write, the program will be intercepted and stopped System.out.println("CharacterEncodingFilter After execution...."); } //When the destruction server is shut down, the characterencoding filter will be destroyed! @Override public void destroy() { System.out.println("CharacterEncodingFilter Destroy!"); } }
-
web. Configure filter filter in XML
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.si.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <!--As long as it is/servlet Any request under will pass through this filter--> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
-
12. Listener listener
Implement the interface of a listener: (N kinds)
Write a listener
-
Implement the interface of listener
package com.si.listener; import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; //Count the number of people online -- count the number of session s public class OnlineListener implements HttpSessionListener { //Create Session listener //Once a session is created, this event will be triggered @Override public void sessionCreated(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); System.out.println(se.getSession().getId()); Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount"); if (onlineCount == null) { onlineCount = new Integer(1); } else { int count = onlineCount.intValue(); onlineCount = new Integer(count + 1); } servletContext.setAttribute("OnlineCount",onlineCount); } //Destroy Session listening //This event will be triggered once a Session is destroyed @Override public void sessionDestroyed(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount"); if (onlineCount == null) { onlineCount = new Integer(0); } else { int count = onlineCount.intValue(); onlineCount = new Integer(count - 1); } servletContext.setAttribute("OnlineCount",onlineCount); //Destroy Session // Manual configuration // Or web Configure automatic destruction time in XML se.getSession().invalidate(); } }
-
web. Configuring listeners in XML
<!--Register listener--> <listener> <listener-class>com.si.listener.OnlineListener</listener-class> </listener>
13. Common applications of filters and listeners
package com.si.listener; import java.awt.*; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class TestPanel { public static void main(String[] args) { //Create a new form Frame frame = new Frame("happy new year"); //Create a new panel Panel panel = new Panel(null); //Set the layout of the form frame.setLayout(null); frame.setBounds(300,300,500,500); //Set background color frame.setBackground(new Color(0,0,255)); panel.setBounds(50,50,300,300); panel.setBackground(new Color(255,0,0)); frame.add(panel); frame.setVisible(true); //Listen for closing events frame.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { System.out.println("open"); } @Override public void windowClosing(WindowEvent e) { System.out.println("Closing"); System.exit(0); } @Override public void windowClosed(WindowEvent e) { System.out.println("close"); } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { System.out.println("Activated"); } @Override public void windowDeactivated(WindowEvent e) { System.out.println("not active"); } }); } }
Users can enter the home page only after logging in. Users cannot enter the home page after logging out
-
After logging in, put the user's data into the Session
-
When entering the home page, judge whether the user has logged in
-
Add the following code to the login success page
<% Object user_session = request.getSession().getAttribute("USER_SESSION"); if (user_session == null) { response.sendRedirect("/Login.jsp"); } %>
-
Filter
-
Implement filter interface
package com.si.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class SysFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; Object userSession = request.getSession().getAttribute("USER_SESSION"); if (userSession == null) { response.sendRedirect("/error.jsp"); } filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { Filter.super.destroy(); } }
-
web. Configuration in XML
<filter> <filter-name>filter</filter-name> <filter-class>com.si.filter.SysFilter</filter-class> </filter> <filter-mapping> <filter-name>filter</filter-name> <url-pattern>/sys/*</url-pattern> </filter-mapping>
-
-
14,JDBC
What is JDBC
What is JDBC: java database connector
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-I7PjA3Qs-1643023648932)(JavaWeb learning notes. Assets / image-202201241112130156. PNG)]
JDBC basic experiment
The jar package needs to be imported
- java.sql
- javax.sql
- MySQL connector Java -- > connection driver
Construction of experimental environment
-
Create a new database and a new table Users (id, name, password, email,birthdate)
-
Import database dependencies
<!--mysql Drive of--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency>
-
Connect to database in IDEA
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (IMG ktbskuso-1643023648932) (JavaWeb learning notes. assets/image-20220124133502044.png)]
[external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-sJ3wkuOn-1643023648932)(JavaWeb learning notes. assets/image-20220124133350146.png)]
[the transfer of external chain pictures fails. The source station may have an anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-h6D9qhp8-1643023648933)(JavaWeb learning notes. assets/image-20220124133535595.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-fl7T2nlA-1643023648933)(JavaWeb learning notes. assets/image-20220124133611931.png)]
-
Create a new class - JdbcTest(Statement)
package com.si.test; import java.sql.*; public class JdbcTest { public static void main(String[] args) throws ClassNotFoundException, SQLException { /* characterEncoding=utf-8&useUnicode=true Solve Chinese garbled code useSSL=true Secure connection timeZone=utc time zone */ String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useUnicode=true&useSSL=true&timeZone=utc"; String username = "root"; String password = "123456"; //1. Load driver class Class.forName("com.mysql.cj.jdbc.Driver"); //2. Connect to the database to represent the database Connection connection = DriverManager.getConnection(url, username, password); //3. Send Statement: curd of sql object to database Statement statement = connection.createStatement(); //4. Write sql String sql = "select * from Users where id = 1"; //5. Execute the query sql statement to return a result set ResultSet resultSet = statement.executeQuery(sql); /* sql = "delete * from Users where id = 4"; //i == Number of rows affected int i = statement.executeUpdate(sql); */ while (resultSet.next()) { System.out.println("id:" + resultSet.getObject("id") + "name:" + resultSet.getObject("name")); } //6. Close the connection to release resources. Open first and then close resultSet.close(); statement.close(); connection.close(); } }
-
Create a new JDBC test class (PreparedStatement)
package com.si.test; import java.sql.*; public class JDBCTest2 { public static void main(String[] args) throws ClassNotFoundException, SQLException { /* characterEncoding=utf-8&useUnicode=true Solve Chinese garbled code useSSL=true Secure connection timeZone=utc time zone */ String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useUnicode=true&useSSL=true&timeZone=utc"; String username = "root"; String password = "123456"; //1. Load driver class Class.forName("com.mysql.cj.jdbc.Driver"); //2. Connect to the database to represent the database Connection connection = DriverManager.getConnection(url, username, password); //3. Write sql String sql = "select * from Users where id = ?"; //4. Precompile PreparedStatement pst; pst = connection.prepareStatement(sql); pst.setObject(1,2); //For the first placeholder? The value of is copied to 2 //5. Execute sql to obtain the result set ResultSet resultSet = pst.executeQuery(); while(resultSet.next()) { System.out.println("id: " + resultSet.getInt("id")); System.out.println("name: " + resultSet.getString("name")); System.out.println("password: " + resultSet.getString("password")); System.out.println("email: " + resultSet.getString("email")); System.out.println("birthdate: " + resultSet.getDate("birthdate")); } //6. Close the link resultSet.close(); pst.close(); connection.close(); } }
JDBC transaction
Either all succeed or all fail
ACID principle: ensure data security
ACID: atomicity, consistency, isolation and persistence
Open transaction Transaction commit commit() Transaction rollback rollback() Close transaction transfer accounts A: 1000 B: 1000 A ---------->B A(900) ---100---> B(1100)
Junit unit test
<!--unit testing --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
Simple use
@The Test annotation is only valid for methods. As long as the annotated method is added, it can be run directly
@Test public void c() { System.out.println("Hello") }
Build an environment test
Create a new table
CREATE TABLE account( id INT PRIMARY KEY auto_increment, `name` varchar(40), money FLOAT ); INSERT INTO account(`name`,money) VALUES('A',1000); INSERT INTO account(`name`,money) VALUES('B',1000);
Simple test
package com.si.test; import org.junit.Test; import java.sql.*; public class TestJDBC { @Test public void Test() { String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useUnicode=true&useSSL=true&timeZone=utc"; String username = "root"; String password = "123456"; Connection connection = null; try { //1. Load driver class Class.forName("com.mysql.cj.jdbc.Driver"); //2. Connect to the database to represent the database connection = DriverManager.getConnection(url, username, password); //3. Notify the database to start the transaction false start true close connection.setAutoCommit(false); String sql1 = "update account set money = money - 100 where name = 'A'"; connection.prepareStatement(sql1).executeUpdate(); //Manufacturing error // int i = 1/0; String sql2 = "update account set money = money + 100 where name = 'B'"; connection.prepareStatement(sql2).executeUpdate(); // Commit transaction connection.commit(); System.out.println("Submitted successfully!"); } catch (Exception throwables) { //Notify the database to roll back the transaction when an exception occurs try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } throwables.printStackTrace(); } finally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }