Java Web
1. Basic concepts
1.1 Preface
Web development:
-
The meaning of web page, www.baidu com
-
Static web
- html,css
- The data provided to everyone will never change
-
Dynamic web
-
Taobao... Almost all websites
-
The data provided to all people will change (different time, different place (occasion))
-
Technology stack: Servlet/Jsp, ASP, PHP
-
In Java, the technology of dynamic web resource development is collectively referred to as JavaWeb;
1.2. Web application
Web applications, programs that provide browser access:
-
a.html, b.html... Multiple Web resources, which can be accessed by the outside world and provide services to the outside world;
-
Any page or resource that can be accessed exists on a computer somewhere in the world
-
URL: on the WWW, each information resource has a unified and unique address , which is called URL (Uniform Resource Locator). It is the uniform resource location mark of WWW, that is, the network address.
URI = Universal Resource Identifier
URL = Universal Resource LocatorThe URL represents the path address of the resource, and the URI represents the name of the resource.
-
This unified Web resource will be placed in the same folder, and the Web application - >tomcat (server)
-
A web application consists of multiple parts (static web, dynamic web)
- html,css,js
- jsp,servlet
- java program
- jar package
- Configuration files (properties)
After the Web application is written, if you want to provide access to the outside world, you need a server for unified management;
1.3. Static Web
- *. htm, *. html these are suffixes of web pages. If these things always exist on the server, we can read them directly.
[external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ky8gik7g-1627784097289) (c:\users\ly\desktop\markdown\markdown image resources \ static Web2.png)]
- Disadvantages of static Web
- The Web page cannot be dynamically updated. All users see the same page
- Rotation chart, click feature: pseudo dynamic
- JavaScript [much used in actual development]
- VBScript
- Unable to interact with the database (data cannot be persisted and users cannot interact)
- The Web page cannot be dynamically updated. All users see the same page
1.4 dynamic Web-
Page dynamic display: "Web page" thousands of people and thousands of faces
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-47piliky-1627784097292) (c:\users\ly\desktop\markdown\markdown image resources \ dynamic Webpng.png)]
Disadvantages:
- If there is an error in the dynamic Web resources of the server, we need to rewrite our background program and republish it (downtime maintenance)
advantage:
- Web pages can be dynamically updated, and all users do not see the same page
- It can interact with the database (data persistence: registration, product information, user information)
2. Web server
2.1 technical explanation
ASP:
- Microsoft: ASP is the first popular in China
- VB script, ASP+COM, is infiltrated into html;
- In ASP development, there is basically one page (thousands of lines of business code, and the page is extremely chaotic)
- High maintenance costs
- C#
- IIS
PHP:
- php has fast development speed, powerful functions, cross platform and simple code (70% of small and medium-sized websites)
- 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 (large companies or some open source components are written in Java)
- It can bear the impact of three highs (high concurrency, high availability and high performance)
- Syntax like ASP
2.2. Web server
The server is a passive operation, which is used to process some user requests and give users some response information:
IIS:
Microsoft's: ASP... Comes with Windows
TomCat
Tomcat is a core project of the Jakarta project of the Apache Software Foundation. The latest Servlet and JSP specifications can always be reflected in Tomcat. Because Tomcat technology is advanced, stable and free, it is deeply loved by Java enthusiasts and recognized by some software developers. It has become a popular Web application server at present.
Tomcat server is a free open source Web application server, which is a lightweight application The server , which is widely used in small and medium-sized systems and not many concurrent access users. It is the first choice for developing and debugging JSP programs. For a beginner, the best choice
Tomcat actually runs JSP pages and servlets. In addition, Tomcat and IIS Like other Web servers, it has the function of processing HTML pages. In addition, it is also a Servlet and JSP container. The independent Servlet container is the default mode of Tomcat. However, Tomcat handles static HTML Is not as powerful as Apache server. At present, the latest version of Tomcat is 10.0.5****
...
Download TomCat
-
install
-
Understand the configuration file and directory structure
3,TomCat
3.1. Installing TomCat
Official website: https://tomcat.apache.org/
Configure the installation tutorial: https://blog.csdn.net/weixin_45737584/article/details/105324829?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162656722216780262563479%2522%252C%2522scm%2522%253A%252220140713.130102334 …%2522%257D&request_ id=162656722216780262563479&biz_ id=0&utm_ medium=distribute. pc_ search_ result. none-task-blog-2alltop_ positive~default-2-105324829. first_ rank_ v2_ pc_ rank_ v29&utm_ term=tomcat%E5%AE%89%E8%A3%85%E5%8F%8A%E9%85%8D%E7%BD%AE%E6%95%99%E7%A8%8B&spm=1018.2226.3001.4187
Port number that can be configured for startup:
The default is 8080
E:\learing softwares\Maven\apache-tomcat-9.0.45\conf\server.xml file
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
Name of the host that can be configured
- Default host name: localhost->127.0.0.1
- Default website app storage address: webapps
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
How to visit the website?
1. Enter a domain name and press enter
2. Check whether there is this domain name mapping under the C:\Windows\System32\drivers\etc\hosts configuration file of the local machine:
-
Yes: directly return the corresponding ip address, which contains the web program we need to access
127.0.0.1 www.lyStudy.com
-
No: go to the DNS server to find (the domain name in the world) and return if found. If not, return if not found;
3.2. Publish a Web site
- You can access the website you wrote by yourself by placing it under the specified webapps folder in the server (Tomcat)
The structure a website should have
--webapps:Tomcat Server's web catalogue -ROOT -lyStudy: Site directory name -classes: java program -lib: web Application dependent jar package -web.xml Site profile -index.html//Default home page -static -css -jss -img - ...
4,HTTP
4.1. What is HTTP
HTTP (Hypertext Transfer Protocol) is an agreement and specification for transmitting text, pictures, audio, video and other hypertext data between two points in the computer world
It is a simple request and response protocol, usually running on TCP
https: (secure)
4.2 two times
- http 1.0
- HTTP/1.0: the client connects to the web server. Only one web resource can be obtained. Disconnect
- http 2.0
- HTTP/1.1: the client connects to the web server to obtain multiple web resources
4.3 Http request
Client - send Request - server
Request URL:https://www.baidu.com/ request address Request Method:GET get method/post method Status Code: 200 ok Status code: 200 Remote Address: 14.215.177.39: 433 //Original address Referrer Policy: no-referrer-when-downgrade//agreement
1. Request line
-
Request method in the request line: GET
-
Request method: get, post, head, delete, put, trace
-
get: the request can carry few parameters with limited size. The data content will be displayed in the URL address bar of the browser. It is not safe but efficient
-
post: there are no restrictions on the parameters that the request can carry and the size. The data content will not be displayed in the URL address bar of the browser. It is safe but not efficient.
-
2. Message header
Accept: Tell the browser what data types it supports Accept-Encoding: Which encoding format is supported GBK UTF-8 GB2312 ISO8859-1 Accept-Language: Tell the browser its locale Cache-Control: Cache control Connection: Tell the browser whether to disconnect or remain connected when the request is completed HOST: host..../.
4.4 Http response
Server response client
Cache-Control:private Cache control Connection:Keep-Alive connect Content-Encoding:gzip code Content-Type:text/html type
1. Responder
Accept: Tell the browser what data types it supports Accept-Encoding: Which encoding format is supported GBK UTF-8 GB2312 ISO8859-1 Accept-Language: Tell the browser its locale Cache-Control: Cache control Connection: Tell the browser whether to disconnect or remain connected when the request is completed HOST: host..../. Refresh: Tell the client how often to refresh; Location: Reposition page
2. Response status code
200: request response succeeded 200
3xx: request redirection · redirection: you go back to the new location I gave you;
4xx: resource not found 404 · resource does not exist;
5xx: server code error 500 502: gateway error
5,Maven
Why Maven ?
1. In javaweb development, we need to use a large number of jar packages, which we import manually;
2. How to let a tool help us automatically import and configure this jar package
Thus, Maven was born!
5.1 Maven project architecture management tool
We currently use it to facilitate the import of jar packages!
Maven's core idea: Convention is greater than configuration
- There are restrictions, don't break them
Maven will stipulate how to write our java code, and must follow this specification;
5.2. Download Maven
Official website: https://maven.apache.org/
After downloading, unzip it;
5.3 configuring environment variables
Configure the following configurations in our system environment variables:
- M2_ bin directory under home Maven directory
- MAVEN_HOME maven directory
- Configure%maven in the path of the system_ HOME%\bin
Test whether Maven is successfully installed and ensure that the configuration is complete!
5.4 Alibaba cloud image
-
Mirroring: mirrors
-
Function: accelerate our download
-
Alibaba cloud image is recommended in China
<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>
E:\learing softwares\Maven\apache-maven-3.8.1\conf\settings.xml
5.5 local warehouse
Local warehouse, remote warehouse; Set up a local repository: localRepository
<localRepository>E:\learing softwares\Maven\apache-maven-3.8.1\repository</localRepository>
5.6 Maven used in IDEA
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-duahq3o2-1627784097295) (c:\users\ly\desktop\markdown\markdown image resources \ create a Maven web project.png)]
...
Maven webapp template is used (there will be problems)
5.7. Create a common Maven project
[the external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-sgg4vyle-1627784097296) (c:\users\ly\desktop\markdown\markdown image resources \ create a common Maven project.png)]
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nryulbvt-1627784097298) (c:\users\ly\desktop\markdown\markdown image resources \ clean Maven project.png)]
Only under web Application
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ixmm0wmn-1627784097299) (c:\users\ly\desktop\markdown\markdown image resources \png under the web application)]
...
5.7. Configuring Tomcat
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-iesjcia6-1627784097299) (c:\users\ly\desktop\markdown\markdown image resources \ configure tomcat.png)]
Plus sign at the upper left corner of the point
[external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8b9npz4w-1627784097300) (c:\users\ly\desktop\markdown\markdown image resources \ click the plus sign.Png in the upper left corner)]
Solve the warning problem: because we visit the website, we need to specify a file name
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-c1n62xos-1627784097300) (c:\users\ly\desktop\markdown\markdown image resources \ solve the warning problem.png)]
Virtual path mapping
Application context:/
Path can be written or not
Do not write. The default path is localhost:8080
If /ly is written, the path is localhost:8080/ly
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zpzlybiq-1627784097301) (c:\users\ly\desktop\markdown\markdown image resources \ path filling.png)]
5.8 pom file
pom.xml is the core configuration file of Maven
<?xml version="1.0" encoding="UTF-8"?><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><! -- is the gav setting when creating the project -- > <groupid>com.ly</groupid> <artifactid>javaweb-01-maven</artifactid> <version>1.0-snapshot</version> <! -- packaging: project packaging method jar:java application war:javaweb application -- > <packaging>war</packaging> <name>javaweb-01-maven maven webapp</name> <! -- Fifi xme change it to the project's website -- > <url> http://www.example.com </url><!-- Configuration -- > <properties><-- Default build code of the project -- > <project build. sourceEncoding>UTF-8</project. build. sourceEncoding><!-- Compiled version -- > <maven compiler. source>1.7</maven. compiler. source> <maven. compiler. target>1.7</maven. compiler. target> </properties><!-- Project dependencies -- > <dependencies><-- The specific dependent jar package configuration file -- > <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>
<!-- Maven What's advanced about it is that it will help you import this jar Others on which the package depends jar package-->
pom.xml Add: <!--stay build Medium configuration resources,To prevent our resource export from failing--> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
Directory tree: jar package association diagram
[external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wxulqagi-1627784097301) (c:\users\ly\desktop\markdown\markdown image resources \ directory tree.png)]
Maven must be configured repeatedly every time in DEA
Solution: open configure in the lower right corner of the software
[external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-t3ocj384-1627784097302) (c:\users\ly\desktop\markdown\markdown image resources \ config.png in the lower right corner)]
Setup complete, create project
It is best to set / confirm each time before creating a project
6,Servlet
6.1 introduction to Servlet
-
Servlet is a technology for sun company to develop dynamic web
-
sun provides an interface called Servlet in these API s
-
Develop Servlet program in two steps
-
Write a class to implement Servlet interface
-
Deploy the developed java classes to the web server
-
java programs that implement Servlet interfaces are called servlets
6.2,HelloServlet
1. Build a normal Maven project, delete the src directory, and create modules in the project.
2. Understanding of Maven and son project:
jar package subprojects in the parent project can be used; otherwise, they cannot be used
3. Maven Environment Optimization:
1. modify the web XML is up to date
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"></web-app>
2. Add java and resources resource directories under the main directory
3. Write a Servlet program
- Write a common class
- Implement Servlet interface (here we inherit Servlet)
/** * HelloServlet * @author LY */public class HelloServlet extends HttpServlet { //Because get and post are only different ways of request implementation, they can be called each other. The business logic is the same @override protected void doget (HttpServletRequest req, httpservletresponse RESP) throws ServletException, IOException {/ / ServletOutputStream OutputStream = rep.getoutputstream(); printwriter writer = rep.getwriter(); / / response stream writer.println ("Hello servlet");}@ Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
4. Writing a Servlet mapping
The java program we write needs to be accessed through the browser. The browser needs to connect to the web server, so we need to register the Servlet we write in the web service and give it a path that the browser can access
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns. jcp. org/xml/ns/javaee" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xsi:schemaLocation=" http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd "Version=" 4.0 "> <! -- register servlet -- > <servlet> <servlet name>hello</servlet-name> <servlet class>com.ly.servlet.helloservlet</servlet-class> </servlet><! -- mapping (request) path of servlet -- > <servlet mapping> <servlet name>hello</servlet-name > <url pattern>hello</url-pattern> </servlet-mapping></web-app>
5. Configuring Tomcat
6. Start test
6.3 Servlet principle
The working process of Servlet involves three roles: client (browser), Servlet container and Servlet application. The general process is as follows:
First, the client initiates the request.
Then, the servlet container receives the request from the client and parses the request protocol and data. If the servlet program has not been loaded, it will execute the loading process and call the service() method. Otherwise, it will call the service() method directly.
Among them, the process of loading the Servlet program: according to the contract between the Servlet container and the Servlet program, when a request comes, if the Servlet program has not been loaded into the Servlet container, the Servlet container will load the Servlet class into memory by calling the init() method and generate a Servlet instance. When the init() method is called, the Servlet container will pass in a ServletConfig object to initialize the Servlet object. This process can only be executed once, that is, in an application, there can only be one instance of each type of Servlet program. Among them, a ServletContext instance object is hidden in the ServletConfig object, which represents the context environment of the Servlet program in the container.
The service() method performs the following process: first, the Servlet container parses the request parameters and encapsulates them into a ServletRequest and ServletResponse object. The ServletRequest encapsulates the current Http request. The developer can operate the ServletRequest object to obtain the user's request data; ServletResponse encapsulates the Http response of the current user. Developers can operate the ServletResponse object to send the response content back to the user. The Servlet container passes the ServletRequest and ServletResponse as parameters to the service() method, implements the logic of the response by executing the service() method, and returns the content to the client through the ServletResponse object.
Finally, when the Servlet container is closed, the Servlet container will call the destroy() method according to the contract. This method is generally used to write some logic to release resources.
6.4. Mapping problems
1. A servlet can specify a generic mapping path
<!-- set up/hello Is the default request path--><servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/*</url-pattern></servlet-mapping>
2. Specify some prefixes, suffixes, etc
<!-- Custom suffix implementation request mapping--><servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.dylan</url-pattern></servlet-mapping><!-- http://localhost:8080/abcdsdd. dylan --><!-- With Dylan ending -- >
3. Priority issues
It specifies the inherent highest priority. If it is not found, it will go through the default processing request
Custom 404
<!-- 404 --><servlet> <servlet-name>error</servlet-name> <servlet-class>com.ly.servlet.ErrorServlet</servlet-class></servlet> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern></servlet-mapping>
6.5. ServletContext object
When the web container is started, it will create a ServletContext object for each web application, which represents the current web application;
1. Shared data
The data saved in the servlet can be obtained in another Servlet
/**Transfer data*/public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // this.getInitParameter() initialization parameter //this Getservletconfig() servlet configuration //this Getservletcontext() context ServletContext context = this getServletContext(); String username= "Lv Bu"// Data context setAttribute("username",username);// Save data in context object system out. println("hello"); }}
/**receive data */public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String username = (String) context.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); }}
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"><servlet> <servlet-name>hello</servlet-name> <servlet-class>com.ly.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.ly.servlet.GetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>getc</servlet-name> <url-pattern>/getc</url-pattern> </servlet-mapping></web-app>
Test access results
2. Get initialization parameters
<!--Configure some web Apply initialization parameters--><context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306</param-value></context-param>
public class ServletDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String url = context.getInitParameter("url"); resp.getWriter().print(url); }}
<!--web.xml Register in--> <servlet> <servlet-name>gp</servlet-name> <servlet-class>com.ly.servlet.ServletDemo03</servlet-class> </servlet> <servlet-mapping> <servlet-name>gp</servlet-name> <url-pattern>/gp</url-pattern> </servlet-mapping>
3. Request forwarding (the requested address will not change)
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Entered Demo04!"); ServletContext context = this.getServletContext(); // RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");// Forwarded request path //requestdispatcher forward(req,resp);// Call forward to forward the context getRequestDispatcher("/gp"). forward(req,resp); }
4. Read resource file
Properties
- Create new properties in the java directory
- Create new properties in the resources directory
Are packaged under the classes path, which we call classpath
A file stream is required:
username=rootpassword=123456
public class ServletDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream is= this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties properties = new Properties(); properties.load(is); String username = properties.getProperty("username"); String password = properties.getProperty("password"); resp.getWriter().print(username+" "+password); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
Test is enough
6.6,HttpServletResponse
The web server receives the client http request, and creates an HttpServletRequest object representing the request and an HttpServletResponse object representing the response.
- If we want to get the parameters from the client request: find HttpServletRequest
- If you want to respond to some information for the client: find HttpServletResponse
1. Simple classification
Method responsible for sending data to the browser
ServletOutputStream getOutputStream() throws IOException; PrintWriter getWriter() throws IOException;
Methods responsible for sending response headers to browsers
void setCharacterEncoding(String var1);void setContentLength(int var1);void setContentLengthLong(long var1);void setContentType(String var1);void setDateHeader(String var1, long var2);void addDateHeader(String var1, long var2);void setHeader(String var1, String var2);void addHeader(String var1, String var2);void setIntHeader(String var1, int var2);void addIntHeader(String var1, int var2);
Response status code
int SC_CONTINUE = 100; int SC_SWITCHING_PROTOCOLS = 101; int SC_OK = 200; int SC_CREATED = 201; int SC_ACCEPTED = 202; int SC_NON_AUTHORITATIVE_INFORMATION = 203; int SC_NO_CONTENT = 204; int SC_RESET_CONTENT = 205; int SC_PARTIAL_CONTENT = 206; int SC_MULTIPLE_CHOICES = 300; int SC_MOVED_PERMANENTLY = 301; int SC_MOVED_TEMPORARILY = 302; int SC_FOUND = 302; int SC_SEE_OTHER = 303; int SC_NOT_MODIFIED = 304; int SC_USE_PROXY = 305; int SC_TEMPORARY_REDIRECT = 307; int SC_BAD_REQUEST = 400; int SC_UNAUTHORIZED = 401; int SC_PAYMENT_REQUIRED = 402; int SC_FORBIDDEN = 403; int SC_NOT_FOUND = 404; int SC_METHOD_NOT_ALLOWED = 405; int SC_NOT_ACCEPTABLE = 406; int SC_PROXY_AUTHENTICATION_REQUIRED = 407; int SC_REQUEST_TIMEOUT = 408; int SC_CONFLICT = 409; int SC_GONE = 410; int SC_LENGTH_REQUIRED = 411; int SC_PRECONDITION_FAILED = 412; int SC_REQUEST_ENTITY_TOO_LARGE = 413; int SC_REQUEST_URI_TOO_LONG = 414; int SC_UNSUPPORTED_MEDIA_TYPE = 415; int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; int SC_EXPECTATION_FAILED = 417; int SC_INTERNAL_SERVER_ERROR = 500; int SC_NOT_IMPLEMENTED = 501; int SC_BAD_GATEWAY = 502; int SC_SERVICE_UNAVAILABLE = 503; int SC_GATEWAY_TIMEOUT = 504; int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2. Common applications
1. Output information to browser
2. Download File
1. To obtain the file download path
2. Downloaded file name
3. Let the browser support downloading what we need
4. Obtain the input stream of the downloaded file
5. Create buffer
6. Get the OutputStream object
7. Write FileOutputStream stream to buffer
8,use OutputStream Output buffer data to client
public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 1. To obtain the file download path string realpath = "d:\idea project\javaweb-01-servlet\response\target\classes\ Lubu.png"; System. out. Println ("file path to download:" +realpath)// D: \idea project\javaweb-01-servlet\response\target\classes\ Lubu png// 2. Downloaded file name string filename = realpath substring(realPath.lastIndexOf("\") + 1); // 3. Let the browser support downloading what we need download header information resp setHeader("Content-disposition","attachment;filename"+ URLEncoder.encode(filename,"utf-8")); 4. Obtain the input stream of the downloaded file FileInputStream fis = new FileInputStream(realPath); 5. Create buffer int count=0; byte[] buffer = new byte[1024]; 6. Get the OutputStream object ServletOutputStream OS = resp getOutputStream(); 7. Write the FileOutputStream stream to the buffer buffer, and use OutputStream to output the buffer data to the client while ((count=fis.read (buffer))=- 1){ os.write(buffer,0,count); } // 8 close the flow fis close(); os. close(); } @ Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
3. Verification code function
- Front end implementation
- The back-end implementation needs to use the java picture class to generate a · picture
public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //How to make the browser refresh resp automatically in 5s setHeader("refresh","3"); // Create a picture BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_BGR) in memory// Get picturegraphics2d graphics = (graphics2d) image getGraphics();// Brush / / set the background color of the picture graphics setColor(Color.white); graphics. fillRect(0,0,80,20); // Write data to pictures setColor(Color.blue); graphics. setFont(new Font(null,Font.BOLD,20)); graphics. drawString(makeRandom(),0,20); // Tell the browser to open resp setContentType("image/jpeg"); // The website has a cache, and the browser is not allowed to cache resp setDateHeader("expires",-1); resp. setHeader("Cache-Control","no-cache"); resp. setHeader("Pragma","no-cache"); // Write the image to the browser Boolean write = imageio write(image,"jpg", resp.getOutputStream()); } // Making random numbers private string makerandom() {random random = new random(); string s = random.nextint (999999) + ""; StringBuffer sb = new stringbuffer(); for (int i = 0; I <7-s.length(); i++) {sb.append ("0");} String s1 = sb. toString() + s; return s1; } @ Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
On the web Register in XML
<servlet> <servlet-name>image</servlet-name> <servlet-class>com.ly.servlet.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>image</servlet-name> <url-pattern>/image</url-pattern> </servlet-mapping>
3. Implement redirection
After web resource B receives A request from client A, it will notify client A to access another web resource C. This process is called redirection.
Common scenario: user login
void sendRedirect(String var1) throws IOException;//Source code method
// resp.setHeader("Location","/response/image"); //resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); // (the system has done the above two steps) resp sendRedirect("/response/image");
Difference between redirection and forwarding:
- Same point: the page will jump
difference:
- Forwarding: url will not change, redirection: url will change
6.7,HttpServletRequest
HttpServletRequest 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 will be obtained;
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nyuizpku-1627784097303) (c:\users\ly\desktop\markdown\markdown image resources \req.get method.png)]
...
1. Get the parameters passed by the front end
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-5a8orzjn-1627784097304) (c:\users\ly\desktop\markdown\markdown image resource \req.getparmeter method.png)]
2. Obtain parameters and request forwarding
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Solve the garbled code problem req setCharacterEncoding("utf-8"); resp. setCharacterEncoding("utf-8"); String username = req. getParameter("username"); String password = req. getParameter("password"); String[] hobbys = req. getParameterValues("hobbys"); System. out. println(username); System. out. println(password); System. out. println(Arrays.toString(hobbys)); System. out. println("=========================================="); System. out. println(req.getContextPath()); // Forward by request (url unchanged) / / the / here represents the current web application req getRequestDispatcher("/success.jsp"). forward(req, resp); }
Difference between redirection and forwarding:
- Same point: the page will jump
difference:
- Request forwarding: url will not change (307)
- Redirection: url address bar changes (302)
7,Cookie,Session
7.1. Conversation
In the program, session tracking is A very important thing. Theoretically, all request operations of one user should belong to the same session, while all request operations of another user should belong to another session. The two cannot be confused. For example, any product purchased by user A in the supermarket should be placed in A's shopping cart. No matter when user A purchases it, it belongs to the same session and cannot be placed in the shopping cart of user B or user C. It does not belong to the same session.
Web applications use the HTTP protocol to transfer data. The HTTP protocol is A stateless protocol. Once the data exchange is completed, the connection between the client and the server will be closed, and A new connection needs to be established to exchange data again. This means that the server cannot track sessions from the connection. That is, user A purchases A commodity and puts it into the shopping cart. When purchasing A commodity again, the server cannot judge whether the purchase behavior belongs to the session of user A or the session of user B. To track this session, A mechanism must be introduced.
7.2. Two techniques for saving sessions
cookie
- Client Technology (response, request)
session
- Server technology can be used to save the user's session information. We can put the information or data in the session
Common example: after logging in to the website, do not log in again next time (CSDN)
7.3,Cookie
1. Get cookie information from the request
2. Server responds to client cookie s
//Cookies: the server obtains cookies from the client [] cookies = req getCookies();// Cookie there are multiple cookies Getname() / / get the keycookie in the cookie Getvalue() / / obtain the value in the cookie. / / the server responds to the customer service side with a cookie. Cookie cookie = new cookie ("lastlogintime", system.currenttimemillis() + "")// Create a new cookie. / / the validity of the cookie is set to one day (in seconds). After the browser is turned off, the cookie still exists (unsafe) setMaxAge(24*60*60); resp. addCookie(cookie);// Respond to a cookie to the client!!!
Cookies are usually saved in the appdata folder under the local user directory;
Whether there is an upper limit for a website cookie
- A cookie can only store one piece of information
- A web site can send multiple cookies to the browser and store up to 20 cookies
- The cookie size is limited to 4kb (4*1024 bytes)
- Browser limit 300 cookie s
Delete cookie s:
- Do not set the validity period, close the browser, and automatically expire
- Set effective time to 0
Encoding and decoding
Cookie cookie=new Cookie("name",URLEncoder.encode("Lv Bu","utf-8"));//Code out write(URLDecoder.decode(cookie.getValue(),"utf-8"));// decode
7.4,Session
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 the user logs in, it can access the entire website – > save the user information
The difference between Session and Cookie:
- Cookie s write the user's data to the user's browser, and the browser saves it (multiple can be saved)
- Session writes the user data to the session exclusive to the user and saves it on the server side (saves important information and reduces the waste of server resources)
- The Session object is created by the server
Usage scenario:
- Save login user information
- Shopping cart information
- Data that is often used in the entire website. Save it in the Session
/*Save Session**/public class SessionDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Solve the garbled code problem req setCharacterEncoding("gbk"); resp. setCharacterEncoding("gbk"); resp. setContentType("text/html;charset=utf-8"); // Get Session httpsession Session = req getSession(); // Save something in the Session session SetAttribute ("name", new person ("Zhao Yun", 22))// Get the Session ID string id = Session getId(); // Judge whether it is a new if (Session.isnew()) {resp.getwriter().Write ("Session created successfully! Sessionid:" +id);} Else {resp.getwriter().Write ("Session already exists in the server! Sessionid:" +id);}// What is done when Session is created / / cookie cookie = new cookie ("jsessionid", ID)// resp. addCookie(cookie); } @ Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
/**Get Session*/public class SessionDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Solve the garbled code problem req setCharacterEncoding("gbk"); resp. setCharacterEncoding("gbk"); resp. setContentType("text/html;charset=utf-8"); // Get session httpsession session = req getSession(); Person name = (Person) session. getAttribute("name"); System. out. println(name); } @ Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
/**Unregister Session*/public class SessionDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.removeAttribute("name"); //Manually unregister session session invalidate(); } @ Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
<!--web.xml Medium settings--><!--set up session Default expiration time of--> <session-config><!-- 1 Minutes later session Automatic invalidation here, the basic unit is minute--> <session-timeout>1</session-timeout> </session-config>
8,JSP
8.1. What is JSP
Java Server Pages: Java server-side pages, like servlets, are used for dynamic Web technology
Main features:
- Writing JSP is like writing HTML
- difference:
- HTML only provides static data to users
- Java code can be embedded in JSP pages to provide users with dynamic data
8.2 JSP principle
Idea: how to execute JSP
-
Code level
-
Server internal work
There is a work directory in tomcat
Tomcat workspace in IEDA:
C:\Users\LY\.IntelliJIdea2019.3\system\tomcat
Address on this computer
C:\Users\LY\.IntelliJIdea2019.3\system\tomcat\Unnamed_javaweb-session-cookie\work\Catalina\localhost\jwsc\org\apache\jsp\index_jsp.java
The discovery page has been transformed into a java program!
The browser sends a request to the server. No matter what resources it accesses, it is actually accessing the Servlet
JSP will eventually be converted into a java class
JSP is essentially a Servlet
//Initialize public void_ Jspinit() {} / / destroy public void_ jspDestroy() { }//jspService public void _ jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java. io. IOException, javax. servlet. ServletException {
1. Judgment request
2. Built in some objects
final javax.servlet.jsp.PageContext pageContext;//Page context javax servlet. http. HttpSession session = null;// sessionfinal javax. servlet. ServletContextapplication;// applicationContextfinal javax. servlet. ServletConfig config;// configjavax. servlet. jsp. JspWriter out = null;// outfinal java. lang.Object page = this; // Page current page HttpServletRequest request / / request HttpServletResponse response / / response
3. Code added before output page
response.setContentType("text/html");//Set the page type of 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;
4. The above objects can be used directly in JSP pages
[external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nidwbt8y-1627784097305) (c:\users\ly\desktop\markdown\markdown image resource \jsp servlet.png)]
In a JSP page:
As long as it is Java code, it will be output intact
If it is HTML code, it will be converted to
out.write("<html>\r\n");
8.3. JSP basic syntax
Any language has its own syntax. JSP, as an application of java technology, has its own extended syntax.
JSP expression
<%-- JSP expression--%><%--It is used to output the output of the program to the client--%><%= Variable or expression %><%= new java.util.Date() %>
JSP script fragment
<%--jsp Script snippet--%><%int sum=0; for (int i = 0; i <=100 ; i++) { sum+=i; }out.println("<h1>Sum="+sum+"</h1>");%>
Re implementation of JSP script fragment
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html> <head> <title>$Title$</title> </head> <body><%-- JSP expression--%><%--It is used to output the output of the program to the client--%><%= new java.util.Date() %><hr><%--jsp Script snippet--%><%int sum=0; for (int i = 0; i <=100 ; i++) { sum+=i; }out.println("<h1>Sum="+sum+"</h1>"); %><% int x=10; out.println(x);%> <p>This is a JSP file</p><% int y=20; out.println(y);%><hr><%-- Embed in code HTML element --%> <% for (int i = 0; i <5 ; i++) { %> <h1>hello world <%=i%> </h1><% }%> </body></html>
JSP declaration
<%! static{ System.out.println("Loading......");}private int globalVar=0; public void ly(){ System.out.println("Entered the method ly"); }%>
JSP declaration: will be compiled into the Java class generated by JSP
Others will be generated to_ In jspService()
Just embed java code in JSP
<% %><%= %><%! %>
JSP comments will not be displayed on the client, HTML will.
9,JavaBean
Entity class
JavaBean s have a specific way of writing:
- Must have a parameterless construct
- Property must be privatized
- There must be a corresponding get/set method
It is generally used for mapping with database fields
ORM: object relationship mapping
- Table – > class
- Fields – > attributes
- Row record – > object
People table
id | name | age | addresss |
---|---|---|---|
1 | Zhang San | 10 | Beijing |
2 | Lisi | 11 | Shanghai |
3 | Wang Wu | 12 | Chengdu |
class People{ private int id; private String name; private int age; private String address;}class A { new People(4"anonymous",99,"Xi'an");}
10. MVC three-tier architecture
What is MVC:Mode View Controller model view controller
10.1 early years
[external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-tp5axsbq-1627784097305) (c:\users\ly\desktop\markdown\markdown image resources \ jsp.png in earlier years)]
Users directly access the control layer, and the control layer can directly operate the database
servlet----CRUD----->Disadvantages of database: the program is very bloated, which is not conducive to maintenance servlet In the code of: processing request, response, view jump, processing JDBC,Processing business code and logic code architecture: there is nothing that cannot be solved by adding a layer | JDBC |MySQL,Oracle...
10.2 MVC three-tier architecture
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ach5rqfo-1627784097306) (c:\users\ly\desktop\markdown\markdown image resources \JSP MVC.png)]
Model
- Business processing: business logic (Service)
- Data persistence layer: CRUD (Dao)
View
- Presentation data
- Provide links to initiate Servlet requests (a, form, img...)
Controller
- Receive user request (request: request parameter Session information...)
- Give it to the business layer to process the corresponding code
- Control view jump
Sign in---->Receive user's login request-->Process user's request (get user login parameters) ---->Give it to the business layer to handle the login business (judge whether the user name and password are correct: Transaction) ---->Dao Whether the user name and password of layer query are correct-->database
11. Filter
Used to filter web site data
- Handle Chinese garbled code
- validate logon
[external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-whlxjyqc-1627784097306) (c:\users\ly\desktop\markdown\markdown image resource \filter.png)]
Filter development steps
1. Guide Package
2. Write filter (package type error)
package com.ly.filter;import javax.servlet.*;import java.io.IOException;/** * Custom filter * @author LY */public class CharacterEncodingFilter implements Filter { //The initialization web server is initialized when it is started. Wait for the public void init (filterconfig filterconfig) throws ServletException {system.out.println ("characterencoding initialization") to appear on the filter object at any time.}/* Chain: chain 1 All codes in the filter will be executed when filtering pending requests. 2 The filter must continue to pass * / public void dofilter (ServletRequest request, servletresponse, filterchain chain) throws IOException, ServletException {request.setcharacterencoding ("UTF-8"); response.setcharacterencoding ("UTF-8"); response.setcontenttype ("text/html; character=utf-8"); system.out.println ("before characterencoding filter is executed"); chain.doFilter(request,response); / / let our requests continue. If we don't write, intercept and stop system.out.println ("after characterencoding filter is executed") ; } // Destroy when the web server is closed, the filter automatically destroys public void destroy() {system.out.println ("characterencoding destroy");}
3. On the web Configuring Filter filtermapping in XML
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.ly.filter.CharacterEncodingFilter</filter-class></filter> <filter-mapping><!-- As long as it is/servlet Any request from will pass through this filter --> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
12. Listener
1 | write a listener to implement a listener interface: many kinds
/** * Online number monitoring * @author LY */public class OnlineCountListener implements HttpSessionListener { //Listening for creating a session: every move / / this event will be triggered once a session is created. Public void sessioncreated (httpsessionevent httpsessionevent) {ServletContext ServletContext = httpsessionevent. Getsession(). Getservletcontext(); system.out.println (httpsessionevent. 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 the listening public void sessiondestroyed (httpsessionevent httpsessionevent) {ServletContext ServletContext = httpsessionevent. Getsession(). Getservletcontext(); 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); }}
2,web. Register listeners in XML
<!-- Register listeners--> <listener> <listener-class>com.ly.listener.OnlineCountListener</listener-class> </listener>
3. Hardly used (depending on the situation)
13. Common use of filters and listeners
Listener: often used in GUI programming
Users can only enter the home page after logging in. They can't enter the home page after logging out!
1. After the user logs in, put the user's data into the Session
2. When entering the home page, it is necessary to determine whether the user has logged in and implemented in the filter
<!-- As long as it is/sys Any request from will pass through this filter --> <filter> <filter-name>SysFilter</filter-name> <filter-class>com.ly.filter.SysFilter</filter-class> </filter> <filter-mapping> <filter-name>SysFilter</filter-name> <url-pattern>/sys/*</url-pattern> </filter-mapping>
public class SysFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request= (HttpServletRequest) servletRequest; HttpServletResponse response= (HttpServletResponse) servletResponse; Object user_session = request.getSession().getAttribute("USER_SESSION"); if(user_session==null){ response.sendRedirect("/error.jsp"); } filterChain.doFilter(servletRequest,servletResponse); } public void destroy() { }}
Junit unit test
rely on
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>
Simple and practical
@The Test annotation is only valid for methods. As long as the annotated method is added, the Test can be run directly
Review JDBC, transactions