JavaWeb
Dynamic web
[the external chain 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-mxvcpxrt-1622964828729) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210520205235520. PNG)]
Tomcat
conf configuration file
server.xml
Port number modification
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
Host name
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
Idea configuring Tomcat
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vv2u3fph-1622964828731) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210520222246627. PNG)]
[the external chain 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-0qxg51zd-1622964828733) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210520222318073. PNG)]
[the external chain 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-f24o0prk-1622964828735) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210520222536460. PNG)]
The reason for the error is that when we visit a website, we need to specify the name of a folder
[the external chain 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-jsifxlgr-1622964828735) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210520223137103. PNG)]
Solve the problem and create an artifacti
[the external chain 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-60zi9gcx-1622964828737) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210520223312915. PNG)]
[the external chain 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-db8vmmrz-1622964828737) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210520223628449. PNG)]
Interview questions
Please talk about how to visit the website
-
1. Enter the domain name; enter
-
2. Check whether there is a mapping of this domain name under the local C:\Windows\System32\drivers\etc\hosts configuration file
-
1. Yes: directly return the corresponding IP address. In this address, there are web programs we need to access, which can be accessed directly
127.0.0.1 www.yesheng.com
-
2. No: go to the DNS server to find it and return it. If it cannot be found, it will return it and cannot be found
-
[the external chain 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-lyp3vtce-1622964828738) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-202105202016445533. PNG)]
Publish a web site
If not, imitate first
- Put the website written by yourself under the specified web application folder (webapps) in the server (Tomcat), and you can access it
The structure that a website should have
--webapps:Tomcat Server web catalogue -ROOT -yeshen:Directory name of the web site -WEB-INF -classes:java program -lib:web Application dependent jar package -web.xml:Site profile -index.html Default home page -static -css -style.css -js -img -....
web.xml configuration version
<?xml version="1.0" encoding="UTF-8"?> <web-app metadata-complete="true" version="4.0" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"> </web-app>
Http
What is Http
HTTP (Hypertext Transfer Protocol) is a simple request response protocol, which usually runs on TCP.
- Text: html, string
- Hypertext: picture, music, video, location, map...
- 80
Https: Secure
- 443
Two times of Http
-
http1.0: after the client establishes a connection with the server, only one web resource can be obtained. Disconnect
-
http1.1: After the client establishes a connection with the server, it obtains multiple web resources
Http request
- Client – request – server
Baidu:
Request URL: https://www.baidu.com/ Request Method: GET //get method / post method Status Code: 200 OK //Status code: 200 Remote((remote) Address: 183.232.231.174:443 Referrer Policy: unsafe-url
Message header
Accept:Tell the browser what data types it supports Accept-Encoding:Supported encoding formats GBK UTF-8 GB2312 Accept-Language: Tell browser locale Cache-Control:Cache control Connection:Tell the browser whether to disconnect or connect when the request is completed Host:host
Http response
-
Server – response – client
Baidu:
Cache-Control: private Cache control Connection: keep-alive connect: Content-Encoding: gzip Content-Type: text/html;charset=utf-8 Coding type
Responder
Accept:Tell the browser what data types it supports Accept-Encoding:Supported encoding formats GBK UTF-8 GB2312 Accept-Language: Tell browser locale Cache-Control:Cache control Connection:Tell the browser whether to disconnect or connect when the request is completed Host:host Refrush:Tell the client how often to refresh Location: Repositioning web pages
Status code
200: request response succeeded
3 * *: request redirection
- Return to the new position I gave you
404: resource not found
- Resource does not exist
500: server code error
502: gateway error
Common interview questions
When you enter the address in your browser address and press enter, the page denomination can be displayed. What has happened?
Maven
Maven architecture management tool
At present, it is convenient to import jar packages
Maven's core idea: Convention is greater than configuration
- There are constraints. Don't break them
Maven will specify how to write java code according to this specification
Download Maven
Official website: http://maven.apache.org/
Maven environment variable
M2_HOME=E:\gj\Maven\apache-maven-3.8.1\bin
MAVEN_HOME=E:\gj\Maven\apache-maven-3.8.1
path %MAVEN_HOME%\bin
Alibaba cloud image
-
Mirroring: mirrors
- Accelerated Download
-
Domestic suggestions Alibaba cloud
<mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror>
Local warehouse
Local warehouse
Set up a local repository
<localRepository>E:\gj\Maven\apache-maven-3.8.1\maven-repo</localRepository>
Tag folder function
[the external chain 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-gbzh7zdk-1622964828738) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210520221707142. PNG)]
pom.xml
pom.xml is Maven's core configuration file
<?xml version="1.0" encoding="UTF-8"?> <!--Maven Version and header files--> <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> <groupId>com.ye</groupId> <artifactId>javaweb-01-maven</artifactId> <version>1.0-SNAPSHOT</version> <!-- package: Packaging method of the project jar: java application war: javaweb application --> <packaging>war</packaging> <name>javaweb-01-maven Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <!-- to configure--> <properties> <!-- Default build code for the project--> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- Code version--> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <!-- Project dependency--> <dependencies> <!-- 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>
[the external chain 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-i0xdrhz0-1622964828739) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210520225534913. PNG)]
maven encountered the problem that the written configuration file cannot be exported or take effect in the future because his agreement is greater than the configuration. Solution:
<!-- Maven to configure pom.xml Prevent resource export failure--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
IDEA operation
[the external chain 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-hk7edpqg-1622964828739) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210520230412703. PNG)]
Maven warehouse operations
No jar package. Go to this address and put it in POM xml https://mvnrepository.com/
Web. In maven default project XML version problem
[the external chain 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-qv7cscoh-1622964828740) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210521111301566. PNG)]
solve
[the external chain 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-hse6byj4-1622964828740) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210521111755237. PNG)]
Servlet
server introduction
- Servlet is a technology for sun company to develop dynamic web
- There are two steps to develop Servlet program
- Write a class to implement the servlet interface
- Deploy the developed java classes to the web server
The Java program that implements the servlet interface is called servlet
HelloServlet
1. Build an ordinary Maven project,
Delete the src directory, and then create Moudel in this project; This empty project is Maven's main project
2. Understanding of Maven father son project;
There will be in the parent project
<modules> <module>servlet-01</module> </modules>
java subprojects in the parent project can be used directly
3.Maven environment optimization
1) modify web XML is the latest
2) complete the structure of Maven
4. Write a servlet program
Write a common class
Implement the servlet interface. Here we directly inherit HttpServlet
package com.yeshen.servlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; 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 or post are only different ways of request implementation, they can call each other, and the business logic is the same @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //ServletOutputStream outputStream = resp.getOutputStream(); PrintWriter writer = resp.getWriter();//Response flow writer.print("hello,servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
5. Write servlet mapping
Why do we need mapping? We write Java programs, but we need to access them through the browser, and the browser needs to connect to the web server. Therefore, we need to register the Servlet we write in the web service and give it a path that the browser can access
<!--register Servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.yeshen.servlet.HelloServlet</servlet-class> </servlet> <!--Servlet Request path--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
6. Configure Tomcat
7. Start up test
Servlet principle
The Servlet is called by the web server. After receiving the browser request, the web server will:
[the external chain 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-1zu5w4cy-1622964828741) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210521163301168. PNG)]
ServletContext
When the web container starts, it will create a corresponding ServletContext object for each web application, which represents the current web application
shared data
The data saved in different servlets can be obtained from each other
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //this.getServletContext(); Servlet context //this.getServletConfig(); Servlet Configuration //this.getInitParameter() initialization parameter ServletContext context = this.getServletContext(); String username="Late at night"; context.setAttribute("username",username); System.out.println("hello"); } }
public class getC extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String username=(String)context.getAttribute("username"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html"); resp.getWriter().print("name"+username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
<servlet> <servlet-name>hello</servlet-name> <servlet-class>com.yeshen.servlet.HelloServlet</servlet-class> </servlet> <servlet> <servlet-name>getC</servlet-name> <servlet-class>com.yeshen.servlet.getC</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>getC</servlet-name> <url-pattern>/getC</url-pattern> </servlet-mapping>
test result
First, open getC without any data
[the external chain 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-1yhqtzaj-1622964828741) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210521181420392. PNG)]
Set the value of ServletContext through hello
[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-jzkhmki0-1622964828742) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210521181529428. PNG)]
Access getC again to get the data
[the external chain 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-c4lv7suw-1622964828742) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210521181456830. PNG)]
Get initialization parameters
<!-- Configure some web Application initialization parameters --> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybatis</param-value> </context-param>
ServletContext context = this.getServletContext(); String url=context.getInitParameter("url"); resp.getWriter().print(url);
Request forwarding
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); // RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");// Forwarded request path // requestDispatcher.forward(req,resp);// Call forward to forward the request context.getRequestDispatcher("/gp").forward(req,resp); }
The difference between request forwarding and redirection
[the external chain 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-vy4yrmqm-1622964828743) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210521184306019. PNG)]
Read resource file
Properties
- Create new properties in java directory
- Create new properties in the resources directory
Discovery: they are all packaged in the same path: classes, commonly known as classpath
Idea: need a file stream;
public class ServlertDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties prop = new Properties(); prop.load(is); String user=prop.getProperty("user"); String pwd=prop.getProperty("pwd"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); resp.getWriter().print(user+":"+pwd); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
HttpServletResponse
The web server receives the http request from the client. For this request, create an HttpServletRequest object representing the request and an HttpServletResponse object representing the response;
- If you want to get the parameters requested by the client: find HttpServletRequest
- If you want to respond to the client with some information: find HttpServletResponse
Simple classification
Method responsible for sending data to browser
ServletOutputStream getOutputStream() throws IOException; PrintWriter getWriter() throws IOException;
Method responsible for sending response header to browser
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;
Download File
1. Output message to browser
2. Download files
1. To get the path of the downloaded file
2. File name to download
3. Setting allows the browser to support downloading what we need
4. Gets the input stream of the downloaded file
5. Create buffer
6. Get OutputStream object
7. Writes the FileOutputStream stream to the buffer buffer
8. Use OutputStream to output the data in the buffer to the client
public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1. To get the path of the downloaded file String realPath = "F:\\web\\javawweb-02-servlet\\response\\src\\main\\resources\\1.png"; System.out.println("Path to download file:"+realPath); // 2. File name to download String fileName=realPath.substring(realPath.lastIndexOf("\\")+1); // 3. Set the browser to support downloading what we need 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 len=0; byte[] buffer=new byte[1024]; // 6. Get OutputStream object ServletOutputStream out=resp.getOutputStream(); // 7. Write the FileOutputStream stream to the buffer, and use OutputStream to output the data in the buffer to the client while ((len=fis.read(buffer))!=0){ out.write(buffer,0,len); } if(out!=null){ out.close(); } if(fis!=null){ fis.close(); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
Verification code function
How did the verification come from?
- Front end implementation
- The back-end implementation needs to generate an image with the image class of java
Implement redirection
[the external chain 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-poxpyhnc-1622964828743) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210521205457225. PNG)]
When a web resource receives a client request, it will notify the client to access another web resource. This process is called redirection
A visits B. after receiving a's request, B informs a to visit C
void sendRedirect(String var1) throws IOException;
/* Redirection principle resp.setHeader("Location","/r/img"); resp.setStatus(302); */ resp.sendRedirect("/r/img");
Interview question: can you tell me the difference between redirection and forwarding?
Same point
- The page will jump
difference
- The url will not change when the request is forwarded
- When redirecting, the url address bar will change
HttpServletRequest
Get the parameters passed by the front end and request forwarding
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); req.setCharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobbys = req.getParameterValues("hobbys"); System.out.println("------------------------"); System.out.println(username); System.out.println(password); System.out.println(Arrays.toString(hobbys)); System.out.println("------------------------"); //Request forwarding req.getRequestDispatcher("/success.jsp").forward(req,resp); }
Cookie,Session
conversation
Session: users open a browser, click many hyperlinks, visit many web resources, and close the browser. This process is called session
Stateful session: the client has accessed the server, and the server knows it has accessed it the next time
How does a website prove you've been here?
Client server
1. The server sends a letter to the client, and the client can bring the letter when accessing the server next time: cookie
2. The server registers that you have been here. The next time you come, I will match you: session
Two techniques for saving sessions
cookie
- Client Technology (response, request)
session
- Server technology. Using this technology, we can save the user's session information. We can put the information or data into the session
Cookie
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-paedr0zn-1622964828744) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210524082906492. PNG)]
1. Obtain cookie information from the request
2. The server responds to the client cookie
Cookie[] cookies = req.getCookies();//Obtain cookie s from clients cookie.getName();//Get the key of the cookie cookie.getValue();//Get the value of the cookie Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");//Create a new cookie cookie.setMaxAge(24*60*60);//Set the validity period of the cookie resp.addCookie(cookie);//Respond to a cookie to the client
Cookies are generally saved in the local user directory appdata;
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
- Maximum of 300 cookie browsers
Delete cookies
- If the validity period is not set, close the browser and it will be invalid automatically
- Set the validity time to 0
Encoding, decoding
Cookie cookie=new Cookie("name", URLEncoder.encode("Ergat","UTF-8"));//code out.write(URLDecoder.decode(cookie.getValue(),"UTF-8"));//decode
Session
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-6f2zsx4s-1622964828744) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210524083349728. PNG)]
What is Session:
- The server will create a Session 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 the whole website - > save user information; Save cart information...
The difference between Session and Cookie:
- Cookie is to write the user's data to the browser, and the browser saves it (multiple can be saved)
- Session writes the user's data to the user's exclusive session and saves it on the server side (saving important information and reducing the waste of server resources)
- The Session object is created by the service
Usage scenario:
- Save the information of a login user
- Save shopping cart information
- The data often used in the whole website is saved in Session
Using Session
package com.yeshen.servlet; import com.yeshen.pojo.Person; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException; public class SessionDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Solve the problem of garbled code resp.setCharacterEncoding("UTF-8"); req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8");//Set browser //Get Session HttpSession session=req.getSession(); //Save something for Session session.setAttribute("name",new Person("Late at night",5)); //Get the id of the Session String sessionId = session.getId(); //Judge whether the Session is newly created if(session.isNew()){ resp.getWriter().write("session Created successfully, sessionID:"+sessionId); }else{ resp.getWriter().write("session Has been created in the server,sessionID:"+sessionId); } //What was done when the session was created Cookie cookie = new Cookie("JESSSIONID", sessionId); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } //Get Session HttpSession session=req.getSession(); // String name =(String)session.getAttribute("name"); // System.out.println(name); Person person=(Person) session.getAttribute("name"); System.out.println(person.toString()); HttpSession session = req.getSession(); session.removeAttribute("name"); //Manually unregister session session.invalidate();
Session expires automatically, web XML configuration
<!-- set up Session Automatic failure--> <session-config> <!-- After 15 minutes Session Automatic failure, in minutes --> <session-timeout>15</session-timeout> </session-config>
JSP
What is JSP
The address of my computer
C:\Users\10586\AppData\Local\JetBrains\IntelliJIdea2020.3\tomcat\0caab4f5-fc63-4815-8079-a1064720dc81\work\Catalina\localhost\ROOT\org\apache\jsp
jsp pages are transformed into java programs
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
//initialization public void _jspInit() { } //Destroy public void _jspDestroy() { } //JSP Service public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response){ }
1. Judgment request
2. Built in objects
final javax.servlet.jsp.PageContext pageContext; //Page context javax.servlet.http.HttpSession session = null; //session final javax.servlet.ServletContext application; //application final javax.servlet.ServletConfig config; //config javax.servlet.jsp.JspWriter out = null; //out final java.lang.Object page = this; //Page current page HttpServletRequest request //request HTTPServletResponse response //response
3. The code added before the output page
response.setContentType("text/html"); //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 used directly in JSP pages
[the external chain 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-ow6y4ouk-1622964828745) (C: \ users \ 10586 \ appdata \ roaming \ typora user images \ image-20210524124315740. PNG)]
JSP syntax
JSP expression
<%-- JSP Expression function Used to output the program to the client--%> <%= new java.util.Date()%> <%String name="yeshen";%> hello,<%out.write(name);%>
jsp script fragment
<%--jsp Script fragment--%> <% int num=0; for (int i=0;i<100;i++){ num+=i; } out.println("<h1>"+num+"</hi>"); %>
jsp declaration
<%! static{ System.out.println("code") } private static int globalVar=0; %> <%! In the middle is the overall situation%>
JSP declaration: it will be compiled into the Java class generated by JSP, and others will be generated into the jspService method
Embedding java code in JSP
<%%> <%=%> <%!%> <%--notes--%>
JSP comments will not be displayed on the client side, and HTML comments will be displayed
JSP instruction
instructions
<%@page ...%> <%--@include The two pages will be combined into one--%> <%@include file="common/header.jsp"%> <h1>Web page subject</h1> <%@include file="common/footer.jsp"%> <hr> <%--jsp label jsp:include The essence of splicing page is still three --%> <jsp:include page="/common/header.jsp"/> <h1>Web page subject</h1> <jsp:include page="common/footer.jsp"/>
9 built-in objects
- PageContext store things
- Request to store things
- Response
- Session storage
- Application [ServletContext] save things
- config [ServletConfig]
- out
- page
- exception
request.setAttribute("name1","yeshen1");//The saved data is valid in the page pageContext.setAttribute("name2","yeshen2");//The saved data is valid in one request, and the request forwarding will carry the data session.setAttribute("name3","yeshen3"); //The saved data is valid in one session, from opening to closing the browser application.setAttribute("name4","yeshen4"); //The saved data is valid in the server, from server on to server off
Jsel tags, JSTL Tags
<!-- JSTL Expression dependency --> <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
JSP tag
<%--Request forwarding with tags--%> <jsp:forward page="jsptag.jsp"> <jsp:param name="name" value="yeshen"/> <jsp:param name="age" value="18"/> </jsp:forward>
JSTL expression
JSTL tag library is used to make up for the shortage of HTML tags
Format label
SQL tag
XML tag
Core label (master part)
<%--introduce JSTL Core tag library can only be used JSTL label--%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Steps for using JSTL tag library
- Introduce the corresponding taglib
- Use one of the methods
- Tomcat also needs to introduce jstl packages, otherwise it will report errors and jstl parsing errors
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--introduce JSTL Core tag library can only be used JSTL label--%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <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> <c:if test="${param.username=='admin'}" var="isAdmin"> <c:out value="Administrator, welcome"/> </c:if> <c:out value="${isAdmin}"/> </body> </html>
JavaBean
Entity class
JavaBean s have specific ways of writing:
- There must be a parameterless construct
- Property must be privatized
- There must be a corresponding set/get method
The ORM is generally used to map fields in the database
ORM: Object Relational Mapping
- Table – > class
- Fields – > Properties
- Line record – > object
MVC three-tier architecture
What is MVC: Model View Controller
[the external chain 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-svs13kny-1622964828746) (C: \ users \ 10586 \ appdata \ roaming \ typora \ typora user images \ image-20210524195920826. PNG)]
Model:
- Business processing: business logic (Service)
- Data persistence layer: CRUD (Dao)
View:
- Display data
- Provide links and initiate Servlet requests (a,form,img...)
Controller(Servlet):
-
Receive user's request: (req: request parameters, Session information)
-
Give it to the business layer to process the corresponding code
-
Control view jump
Sign in--->Receive user login request--->Handle the user's request (obtain the 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: Transaction)--->Dao Check whether the user name and password are correct--->database
Filter
Filter: filter, which is used to filter the data of the website
- Deal with Chinese garbled code
- validate logon
Filter development steps:
1. Guide Package
2. Write filter
1) do not make mistakes in guiding packages, Java servlet
2) implement the Filter interface and rewrite the corresponding method
package com.yeshen.filter; import javax.servlet.*; import java.io.IOException; public class CharacterEncodingFilter implements Filter { //Initialization: when the web server starts, it has already been initialized, waiting for the filter object to appear at any time @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("initialization"); } //Chain: Chain @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); System.out.println("CharacterEncodingFilter Before execution..."); chain.doFilter(request,response);//Let the request continue. If you don't write, the program will be intercepted and stopped here System.out.println("CharacterEncodingFilter After execution..."); } //Destroy: when the web server is shut down, the filter is destroyed @Override public void destroy() { System.out.println("Destroy"); } }
3) on the web Configure filter in XML
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.yeshen.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/servlet/*</url-pattern> <!--<url-pattern>/*</url-pattern>--> </filter-mapping>
Filters, listeners, common applications
Users can enter the home page only after logging in. Users cannot 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, judge whether the user has logged in; Requirement: implemented in filter
HttpServletRequest request=(HttpServletRequest) req; HttpServletResponse response=(HttpServletResponse) resp; if(request.getSession().getAttribute(Constant.USER_SESSION)==null){ response.sendRedirect("/error.jsp"); } chain.doFilter(request,response);
JDBC
Import database dependencies
<!--mysql drive--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
idea connection database
JDBC fixed steps
1. Load drive
2. Connect to the database
3. Send sql object statement to the database: CRUD
4. Write sql
5. Execute sql
6. Close the connection
package com.yeshen.test; import java.sql.*; public class TestJdbc { public static void main(String[] args) throws ClassNotFoundException, SQLException { //configuration information //Useunicode = true & characterencoding = UTF-8 solve Chinese garbled code String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8"; String username="root"; String password="hadoop"; //1. Load drive Class.forName("com.mysql.jdbc.Driver"); //2. Connect to the database Connection conn = DriverManager.getConnection(url, username, password); //3. Send online statement crud Preparedstatement PS = conn.preparestatement (sql) of sql to the database; (secure, precompiled) Statement statement = conn.createStatement(); //PreparedStatement ps=conn.prepareStatement(sql); //4. Write sql String sql="select * from users"; //5. Execute sql and return a resultset result set ResultSet rs = statement.executeQuery(sql); while (rs.next()){ System.out.print("id"+rs.getObject("id")+"\t"); System.out.print("name"+rs.getObject("name")+"\t"); System.out.print("pwd"+rs.getObject("pwd")+"\t"); System.out.print("email"+rs.getObject("email")+"\t"); System.out.print("birthday"+rs.getObject("birthday")); System.out.println(); } //6. Close the connection and release resources rs.close(); statement.close(); conn.close(); } }
Statement is used for addition, deletion and modification executeUpdate(sql)
//Statement is used for addition, deletion and modification executeUpdate(sql); int i = statement.executeUpdate(sql);
package com.yeshen.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.Date; public class Test2 { public static void main(String[] args) throws Exception { String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false"; String username="root"; String password="hadoop"; Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(url, username, password); String sql="insert into users(id, name, pwd, email, birthday) values (?,?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setObject(1,3); ps.setObject(2,"yeshen"); ps.setObject(3,"12346"); ps.setObject(4,"564@qq.com"); ps.setObject(5,new Date(new java.util.Date().getTime())); int i = ps.executeUpdate(); if (i>0){ System.out.println("Successful execution"); } ps.close(); conn.close(); } }
Junit unit test
Test dependency
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>
@Test can only be used on methods. As long as the annotated method is added, it can be run directly
@Test public void test(){ }
affair
@Test public void test(){ Connection conn=null; try { //configuration information //Useunicode = true & characterencoding = UTF-8 solve Chinese garbled code String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false"; String username="root"; String password="hadoop"; //1. Load drive Class.forName("com.mysql.jdbc.Driver"); //2. Connect to the database conn = DriverManager.getConnection(url, username, password); // Turn on transaction (cancel auto commit) conn.setAutoCommit(false); String sql="update account set money=money-100 where name='a'"; conn.prepareStatement(sql).executeUpdate(); //Manufacturing error int i=1/0; String sql2="update account set money=money+100 where name='b'"; conn.prepareStatement(sql2).executeUpdate(); conn.commit(); } catch (ClassNotFoundException e) { try { conn.rollback(); } catch (SQLException throwables) { throwables.printStackTrace(); } e.printStackTrace(); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException throwables) { throwables.printStackTrace(); } e.printStackTrace(); }finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
Function expansion
File upload
Introduction to common methods:
//The isFormFile method is used to judge that the data encapsulated by the FileItem class object is a normal text form //It is also a file form. If it is a normal form field, it will return true; otherwise, it will return false boolean isField(); //The getFieldName method is used to return the value of the name attribute of the form label String getFieldName(); //The getString method is used to return the data stream content saved in the FileItem object as a string String getString(); //The getName method is used to obtain the file name in the file upload field. String getName(); //Return the data content of the uploaded file in the form of stream. InputStream getInputStream(); //The delete method is used to empty the body content stored in the FileItem class object //If the body content is saved in a temporary file, the delete method deletes the temporary file void delete();
Specific code implementation
package com.hao.servlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.UUID; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException { //Judge whether the uploaded form is an ordinary form or a form with files, return true or false; if (!ServletFileUpload.isMultipartContent(request)){ return;//If this is an ordinary file, we will return it directly }//If this if is passed, it means that our form is uploaded with files //Create a storage directory for uploaded files. For security, it is recommended to use the WEB-INF directory, which users cannot access String uploadpath = this.getServletContext().getRealPath("WEB-INF/Upload");//Get the save path of the uploaded file File uploadfile = new File(uploadpath); if (!uploadfile.exists()){ uploadfile.mkdir();//If the directory does not exist, create such a directory } //Temporary documents //Temporary path. If the uploaded file exceeds the expected size, we will store it in a temporary directory and delete it automatically in a few days, or remind the user to save it permanently String tmppath = this.getServletContext().getRealPath("WEB-INF/tmp"); File file = new File(tmppath); if (!file.exists()){ file.mkdir();//If the directory does not exist, create such a temporary directory } //Generally, the uploaded files need to be obtained through the stream. We can use request Getinputstream(), which is very troublesome to obtain from the upload stream of the original ecological file //However, we all recommend using Apache's file upload component to implement common file upload, which depends on the common IO component; try { //1. Create DiskFileItemFactory object, handle file upload path or limit file size DiskFileItemFactory factory = gteDiskFileItemFactory(file); //2. Get ServletFileUpload ServletFileUpload upload = getServletFileUpload(factory); //3. Process uploaded files String msg = uploadParseRequest(upload,request,uploadpath); //Servlet request forwarding message request.setAttribute("msg",msg); request.getRequestDispatcher("/info.jsp").forward(request,response); }catch (FileUploadException e){ e.printStackTrace(); } } public static DiskFileItemFactory gteDiskFileItemFactory(File file){ //1. Create DiskFileItemFactory object, handle file upload path or limit file size DiskFileItemFactory factory = new DiskFileItemFactory(); //Set a buffer through the factory. When the size of the uploaded file is larger than the buffer, put it into the temporary file; factory.setSizeThreshold(1024 * 1024);//The buffer size is 1M factory.setRepository(file); return factory; } public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){ //2. Get ServletFileUpload ServletFileUpload upload = new ServletFileUpload(factory); //Monitor file upload progress upload.setProgressListener(new ProgressListener() { public void update(long pBytesRead, long lpContentLenght, int i) { //pBytesRead: read file size //pContentLenght: file size System.out.println("Total size:"+lpContentLenght+"Uploaded:"+pBytesRead); } }); //Dealing with garbled code upload.setHeaderEncoding("UTF-8"); //Sets the maximum value for a single file upload.setFileSizeMax(1024 * 1024 * 10); //Set the total size of files that can be uploaded //1024 = 1kb * 1024 = 1M * 10 = 10M upload.setSizeMax(1024 * 1024 * 10); return upload; } public static String uploadParseRequest(ServletFileUpload upload,HttpServletRequest request,String uploadpath) throws IOException, FileUploadException { String msg = ""; //3. Process uploaded files //Parse the front-end request and encapsulate it into a FileItem object List<FileItem> fileItems = upload.parseRequest(request); for (FileItem fileItem : fileItems) { if (fileItem.isFormField()){ //Determine whether it is an ordinary form or a form with files //getFieldName refers to the name of the front-end form control String name = fileItem.getFieldName(); String value = fileItem.getString("UTF-8");//Deal with garbled code System.out.println(name+":"+value); }else {//Judge whether it is a form with files //======================Processing files=======================// //Get the name of the file String uploadFileName = fileItem.getName(); System.out.println("Uploaded file name:"+uploadFileName); if (uploadFileName.trim().equals("") || uploadFileName == null){ continue; } //Get the uploaded file name, such as / img / girl / ooa Jpg only needs ooa, and the front and back of it don't need it String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1); //Get the suffix of the file String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1); /* If the file suffix fileExtName is not what we need Just return without processing and tell the user that the file type is wrong */ //UUID (universal code with unique identification) can be used to ensure that the file name is unique //UUID. Random UUID, randomly generate a unique universal code //Everything in network transmission needs to be serialized //pojo, entity class. If you want to run on multiple computers, you need to serialize all the objects in the transfer -- > //JNI=java Native Interface //implements Serializable: tag interface, JVM -- > java stack, native method stack -- > C++ String uuidPath= UUID.randomUUID().toString(); System.out.println("File information [file name:"+fileName+"File type:"+fileExtName+"]"); //UUID (unique universal identification code) can be used to ensure the unity of file names String uuidFileName = UUID.randomUUID().toString(); //=======================Transfer file=========================// //Get the stream of file upload InputStream inputStream = fileItem.getInputStream(); //Create a file output stream FileOutputStream fos = new FileOutputStream(uploadpath + "/" + uuidFileName +"."+ fileExtName); //Create a buffer byte[] buffer = new byte[1024 * 1024]; //Judge whether the reading is completed int len = 0; //If it is greater than 0, there is still data while ((len=inputStream.read(buffer))>0){ fos.write(buffer,0,len); } //Close flow fos.close(); inputStream.close(); msg = "File upload succeeded!"; fileItem.delete();//Upload succeeded, clear temporary files } } return msg; } }
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--Upload file via form post: There are no restrictions on uploaded files get: There are restrictions on uploaded files --%> <form action="/upload.do" method="post" enctype="multipart/form-data"> Upload user:<input type="text" name="username"> <br> <p><input type="file" name="file1"></p> <p><input type="file" name="file2"></p> <p><input type="submit">|<input type="reset"></p> </form> </body> </html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${msg} </body> </html>
xml
<?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>FileServlet</servlet-name> <servlet-class>com.hao.servlet.FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileServlet</servlet-name> <url-pattern>/upload.do</url-pattern> </servlet-mapping> </web-app> -------- Copyright notice: This article is CSDN Blogger「Crab roe」Original articles, follow CC 4.0 BY-SA Copyright agreement, please attach the original source link and this statement for reprint. Original link: https://blog.csdn.net/qq_45879460/article/details/107544819
If it is greater than 0, there is still data
while ((len=inputStream.read(buffer))>0){
fos.write(buffer,0,len);
}
//Close flow fos.close(); inputStream.close(); msg = "File upload succeeded!"; fileItem.delete();//Upload succeeded, clear temporary files } } return msg; }
}
jsp ```javascript <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--Upload file via form post: There are no restrictions on uploaded files get: There are restrictions on uploaded files --%> <form action="/upload.do" method="post" enctype="multipart/form-data"> Upload user:<input type="text" name="username"> <br> <p><input type="file" name="file1"></p> <p><input type="file" name="file2"></p> <p><input type="submit">|<input type="reset"></p> </form> </body> </html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${msg} </body> </html>
xml
<?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>FileServlet</servlet-name> <servlet-class>com.hao.servlet.FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileServlet</servlet-name> <url-pattern>/upload.do</url-pattern> </servlet-mapping> </web-app> -------- Copyright notice: This article is CSDN Blogger「Crab roe」Original articles, follow CC 4.0 BY-SA Copyright agreement, please attach the original source link and this statement for reprint. Original link: https://blog.csdn.net/qq_45879460/article/details/107544819