Crazy God Javaweb full version basic introduction (IDEA version) JavaWeb tutorial worth learning

Java web

Java web

1. Basic concepts

web development:

  • web, meaning web page, www.baidu.com
  • static web
    • html,css
    • The data available for everyone to see never changes!
  • dynamic web
    • Taobao, almost all websites
    • The data provided to everyone will always change. Everyone sees different information at different times and in different places.
    • Technology stack: Servlet/Jsp, ASP, PHP

In Java, the technology for dynamic web resource development is collectively called JavaWeb;

1.2. Web application

web application: A program that provides browser access to:

  • a.html, b.html... multiple web resources. These web resources can be accessed by the outside world and provide services to the outside world.
  • Every page and resource that can be accessed exists on a computer in a certain location.
  • URL
  • This unified web resource will be placed in the same folder, 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 file (Properties)

After the web application is written, if you want to provide it for external access: a server is needed for unified management;

1.3. Static web

  • *.htm, *.html These are the suffixes of web pages. If these things always exist on the server, we can read them directly.

Please add image description

  • Disadvantages of static web
    • The web page cannot be updated dynamically, and all users see the same page.
      • Carousel image, click special effects: pseudo-dynamic
      • JavaScript [most commonly used in actual development
      • VBScript
    • He cannot interact with data (data cannot be persisted and users cannot interact)

1.4. Dynamic web

The page will be displayed dynamically: "The web page display effect varies from person to person";

Insert image description here

shortcoming

  • An error occurred when adding dynamic web resources to the server. We need to rewrite the background program and re-publish it.
    • Downtime maintenance

advantage:

  • Web pages can be updated dynamically, so all users do not see the same page.
  • He can interact with data (data persistence: registration, product information, user information)

Insert image description here

2. web server

ASP

  • Microsoft: ASP is the most popular in China
  • Embed VB script in HTML, ASP + COM
  • In ASP development, basically every page has thousands of lines of business code, and the page is extremely confusing.
  • High maintenance costs
  • C#
  • IIS
<h1>
    <h1>
        <%
        System.out.println("hello")
        %>
    </h1>
</h1> 

php

  • PHP development is fast, powerful, cross-platform, and the code is simple (70%, WP)
  • Unable to carry large amounts of traffic (limitations)

JSP/Servle

B/S: browser and server

C/S: client and server

  • The B/S architecture mainly promoted by Sun Company
  • Based on Java language (all large companies, or some open source components, are written in Java)
  • Can bear the impact of three high problems (high concurrency, high availability, high performance)
  • Syntax like ASP, ASP–>JSP, strengthen market strength

2.2. web server

The server is a passive operation, used to process some requests from users and give some response information to users:

IIS

Microsoft ASP… comes with Windows

Tomcat

Tomcat is a core project in the Jakarta project of the Apache Software Foundation. Because Tomcat has advanced technology, stable performance, and is free, it is deeply loved by Java enthusiasts and recognized by some software developers. It has become A relatively popular web application server.

Tomcat server is a free open source web application server. It is a lightweight application server . It is commonly used in small and medium-sized systems and situations where there are not many concurrent access users. It is the first choice for developing and debugging JSP programs.

Tomcat actually runs JSP pages and Servlets, and the latest version of Tomcat is 10.0.23**. **

Download tomcat

  1. Installation and decompression
  2. Understand configuration files and directory structure
  3. effect

3、Tomcat

3.1. Install Tomcat

Official website: https://tomcat.apache.org

Insert image description here

3.2. Tomcat startup and configuration

Folder information:
Insert image description here

Start Tomcat

  • startup.bat starts the server
  • shutdown.bat shuts down the server

Visit the website: http://localhost:8080/

3.3. Configuration

Insert image description here

  • The host port number can be configured: default port number 8080
<Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

The host name can be configured: the default host name is localhost and the default website storage location is webapps

<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">

Interview questions:

How is the website accessed?

  1. Enter the 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 this machine:

    • If it exists: directly return the corresponding IP address. In this address, the web program we need to access can be accessed directly.
    • No: Go to the DNS server to search, and return if found. If not found, return "Not found".

image-20230203130342439

3.4. Publish a website

  • Put the website you wrote in the specified directory on the server (web apps, you can access it
--webapps : Tomcat服务器的web目录
    -ROOT:
    -hwt:	网站的目录名
        -WEB-INF:
        	-classes:	Java程序
        	-lib:	web应用所依赖的jar包
			- web.xml:	网站的配置文件
		-index.html:	默认的首页
		-static:	
			-css
            -js
            -img

4、HTTP

4.1. What is HTTP?

HTTP: (Hypertext Transfer Protocol) is a simple request-response protocol, usually running on top of TCP

  • Text: html, string
  • Hypertext: pictures, music, videos, positioning, maps
  • port 80

HTTPS: secure

  • Port: 443

4.2. Two eras

  • HTTP1.0
    • After the client connects to the web server, it can only obtain one resource.
  • HTTP2.0
    • After the client connects to the web server, it can obtain multiple web resources

4.3. HTTP request

  • Client----Request-------Server

Baidu

Request URL: https://www.baidu.com/
Request Method: GET
Status Code: 200 OK
Remote Address: 180.101.50.242:443
Referrer Policy: unsafe-url
1. Request line
  • Request method in request line: GET
  • Request method: Get, Post , HEAD, DELETE, PUT, TRACT
    • GET: The request can carry relatively few parameters, the size is limited, and the data content will be displayed in the URL address bar of the browser. It is unsafe, but efficient;
    • POST: There is no limit on the parameters that can be carried, and there is no limit on the size. The data content will not be displayed in the URL address bar of the browser. It is safe and inefficient.
2. Message header
Accept: text/html	支持的数据类型
Accept-Encoding: gzip, deflate, br	支持的编码格式
Accept-Language: zh-CN,zh;q=0.9   语言环境
Cache-Control: max-age=0		缓存控制
Connection: keep-alive		告诉浏览器,请求完成是断开还是保持连接
HOST:主机

4.4. HTTP response

  • Server-----Response------Client

Baidu

Bdpagetype: 1
Bdqid: 0x93f5dcf00001d517
Connection: keep-alive	连接
Content-Encoding: gzip	编码
Content-Type: text/html; 类型
1. Response body
Accept: text/html	支持的数据类型
Accept-Encoding: gzip, deflate, br	支持的编码格式
Accept-Language: zh-CN,zh;q=0.9   语言环境
Cache-Control: max-age=0		缓存控制
Connection: keep-alive		告诉浏览器,请求完成是断开还是保持连接
HOST:主机
Refresh:告诉客户端,多久刷新一次
Location:让网页重新定位
2. Response status code
  • 200: Request response successful 200

  • 3xx: Request redirect

    • Redirect to a new URL
  • 4xx: Resource Not Found 404

    • Resource does not exist
  • 5xx: Server error code 500 502: Gateway error

Common interview questions:

What did you experience when the page was displayed when you entered the address in the browser address bar and pressed Enter?

5、maven

The role of maven:

在Javaweb开发中,需要使用大量的jar包,只能手动导入,通过maven可以帮助我们自动导入jar包

5.1. Maven project architecture management tool

The core idea of ​​Maven: Agreement is greater than configuration

  • If there are restrictions, don’t violate them

Maven will stipulate our code specifications, and we must follow these specifications.

5.2. Download and install Maven

Official website: https://maven.apache.org/
Insert image description here

5.3. Configure environment variables

  • M2_HOME: bin directory under the maven directory
  • MAVEN_HOME: maven directory
  • Configure %MAVEN_HOME%\bin in the system path

mvn -version tests whether the installation is successful

5.4. Configure Alibaba Cloud image

  • Mirrors: mirrors
    • Function: Accelerate downloading
  • Generally use Alibaba Cloud's image
<mirror>
     <id>nexus-aliyun</id>
     <mirrorOf>*</mirrorOf>
     <name>Nexus aliyun</name>
     <url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>

5.5. Local warehouse

**Create a local repository: **localRepository

<localRepository>D:\environment\java\apache-maven-3.8.7\maven-repo</localRepository>

5.6. Using maven in IDEA

  1. Start IDEA

  2. Create a maven web project

Insert image description here

  1. Project initialization successful
    Insert image description here

  2. Observe changes in the maven repository

  3. Maven settings in IDEA

    Check Maven configuration after successful creation
    Insert image description here

5.7. Create a normal Maven project

Insert image description here

Insert image description here

Only available under web application
Insert image description here

5.8. Configure Tomcat in IDEA

Insert image description here

Necessary configuration: To access a website, you must specify the name of a folder

Insert image description here

Insert image description here

5.9. pom file

The pom.xml file is the core configuration file of Maven

<?xml version="1.0" encoding="UTF-8"?>
<!--pom文件的头文文件-->
<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>
<!--配置的GAV-->
  <groupId>org.example</groupId>
  <artifactId>javaweb-01-maven</artifactId>
  <version>1.0-SNAPSHOT</version>

  <packaging>war</packaging>
  <!--
    package项目的的包方式
    jar:Java应用
    war:Javaweb应用-->
  <name>javaweb-01-maven Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

<!--配置-->
  <properties>
<!--    项目默认构建编码-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--    编码的版本-->
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
<!--项目依赖-->
  <dependencies>
<!--    具体的依赖配置-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
<!--项目构建工具-->
  <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>

Since maven's convention is greater than its configuration, the configuration file we wrote may not take effect. Solution:

<!--在build中配置resources,来防止资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

5.10. Import package dependencies

Insert image description here

maven warehouse address: https://mvnrepository.com/

5.10、web.xml

Replace header file

<?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"
  metadata-complete="true">
</web-app>

5.11. Use of Maven warehouse

maven warehouse address: https://mvnrepository.com/

6、Servlet

6.1. Introduction to Servlet

  • Servlet is a technology used by Sun to develop dynamic web
  • Sun provides an interface in these APIs called: Servlet. If you want to develop a Servlet program, you only need to complete two small steps:
    • 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

6.2、HelloServlet

Servlet interface Sun has two default implementation classes: HttpServlet,

  1. Build a normal Maven project, delete the src directory inside, and then create a Model in this project; this empty project is the main Maven project;

  2. Understanding of Maven father-son projects:

    The parent project will have

    <modules>
            <module>servlet-01</module>
    </modules>
    

    There will be sub-projects

     <parent>
            <artifactId>javaweb-02-Servlet</artifactId>
            <groupId>org.example</groupId>
            <version>1.0-SNAPSHOT</version>
    </parent>
    

    Jar package sub-projects in the parent project can be used directly

  3. Maven environment optimization

    1. Modify web.xml to be the latest
    2. Complete the Maven structure
  4. Write a Servlet program

    1. Write a normal class
    2. Implement the Servlet interface and directly inherit HttpServlet

Insert image description here

public class HelloServlet extends HttpServlet {
    
    

    //由于get或者post只是请求实现方式的不同,可以互相调用,业务逻辑一样

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
//        ServletOutputStream outputStream = resp.getOutputStream();
        PrintWriter writer = resp.getWriter();//响应流

        writer.print("hello Servlet!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doGet(req,resp);
    }
}
  1. Write Servlet mapping

    The program is written in Java, but it needs to be accessed through a browser. The browser is connected to the web server, so the Servlet needs to be registered in the web service and an access path needs to be given.

    <!--    注册Servlet-->
        <servlet>
            <servlet-name>hello</servlet-name>
            <servlet-class>com.hwt.servlet.HelloServlet</servlet-class>
        </servlet>
    <!--    Servlet的请求路径-->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
  2. Configure Tomecat

    Note: Just configure the path for project release.

  3. Start testing

Notice:

  • Switch /hello. Lu Jin reports error 500 and uses tomcat10 version. It can be solved by switching to Tomcat9.
  • Qi℃伅garbled code:
    • Open the conf/ logging.properties folder in the tomcat installation directory and modify the logging.properties file.
    • Change java.util.logging.ConsoleHandler.encoding = utf-8
      to java.util.logging.ConsoleHandler.encoding = GBK

6.3. Servlet principle

Servlet is called by the Web server. After receiving the browser's request, the Web server will

Insert image description here

6.4. Mapping problem

  1. A Servlet can specify a mapping path

      <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
      </servlet-mapping>
    
  2. A Servlet can specify multiple mapping paths

<servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/hello</url-pattern>
</servlet-mapping> 
<servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/hello1</url-pattern>
</servlet-mapping> 
<servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/hell2</url-pattern>
</servlet-mapping>
  1. A Sevlet can specify a universal mapping path
<servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/hello/*</url-pattern>
</servlet-mapping> 
  1. Default request path: higher priority than index.jsp
<servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping> 
  1. Specify some suffixes or prefixes
<!--  可以自定义后缀实现请求映射
      注意,*前面不能加项目映射的路径
      hello/ssss.aaa-->
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>*.hwt</url-pattern>
  </servlet-mapping>
  1. The specified inherent mapping path has the highest priority. If it cannot be found, the default processing request will be used.

    <!--404-->
    <servlet>
      <servlet-name>error</servlet-name>
      <servlet-class>com.hwt.servlet.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>error</servlet-name>
      <url-pattern>/*</url-pattern>
    

6.5、ServletContext()

When the web container starts, it will create a corresponding ServletContext object for each web program, which represents the current web application.

6.5.1. Shared data

The data saved in this Servlet can be obtained in another Servlet

Insert image description here

Place ServletContext data

public class HelloServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
//        this.getInitParameter()   初始化参数
//        this.getServletConfig()   Servlet配置
//        this.getServletContext()  Servlet上下文

        ServletContext context = this.getServletContext();
        String username = "hwt";//数据
        context.setAttribute("username",username);//将一个数据保存在了ServletContext中,名字为:username 值为:username
    }
}

Read ServletContext 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);
    }
}

Web.xml file

<?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"
         metadata-complete="true">
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.hwt.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.hwt.servlet.GetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>getc</servlet-name>
    <url-pattern>/getc</url-pattern>
  </servlet-mapping>
</web-app>

Test access results: Multiple Servlet data sharing can be achieved through ServletContext

6.5.2. Obtain initialization parameters

web.xml

<!--  配置Web初始化参数-->
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
  </context-param>
//获取参数
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    ServletContext context = this.getServletContext();
    String url = context.getInitParameter("url");
    resp.getWriter().print(url);
}
6.5.3. Request forwarding

Insert image description here

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("进入了sd4");
        ServletContext context = this.getServletContext();
        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
        requestDispatcher.forward(req,resp);//调用forward实现请求转发
    }
6.5.4. Request forwarding

Properties

  • Create new Properties in the Java file directory
  • Create new Properties in the resources directory

They are all packaged under the same path: classes, commonly known as classpath.

Need to use a file stream

username=root
password=root
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 username = prop.getProperty("username");
    String pwd = prop.getProperty("password");
    resp.getWriter().print(username+":"+pwd);
}

6.6、HttpServletResponse

The web server receives the client's http request. For this request, it creates an HttpServletRequest object representing the request and an HttpServletResponse representing the response.

  • ​ Get the parameters requested by the client: use HttpServletResponse
  • Respond to information from the client: use HttpServletRequest
6.6.1. Simple classification

Responsible for sending data to the browser

ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;//中文

Responsible for sending response headers to the 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;
6.6.2. Common applications
  1. Output message to browser

  2. download file

    • Get the path to the downloaded file
    • Get downloaded file name
    • Set the browser to support downloading what you need
    • Get the input stream of the downloaded file
    • Create buffer
    • Get OutputStream object
    • Write the FileOutStream stream to the buffer buffer
    • Use OutPutStream to output data in the buffer to the client
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
          
    //- 获取下载的文件名
            String realPath = "D:\\procedure2\\java\\JavaWeb\\javaweb-02-servlet\\response\\target\\classes\\测试.jpg";
            System.out.println("下载路径为"+realPath);
    //  下载的文件名是啥?
            String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
    //- 设置让浏览器支持下载需要的东西,中文文件名URLEncoder.encode编码,否则可能乱码
            resp.setHeader("Content-Disposition","attachment;fileName"+ URLEncoder.encode(fileName,"UTF-8"));
    //- 获取下载文件的输入流
            FileInputStream in = new FileInputStream(realPath);
    //- 创建缓冲区
            int len = 0;
            byte[] buffer = new byte[1024];
    //- 获取OutputStream对象
            ServletOutputStream out = resp.getOutputStream();
    //- 将FileOutStream流写入到buffer缓冲区,使用OutPutStream将缓冲区中的数据输出到客户端
            while ((len=in.read(buffer))>0){
          
          
                out.write(buffer,0,len);
            }
            in.close();
            out.close();
        }
    
    1. Implementation of verification code

      • Front-end implementation

      • Back-end implementation requires the use of Java's picture class to produce a picture

        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                  
                  
                //如何让浏览器3秒刷新一次
                resp.setHeader("refresh","3");
                //在内存中创建一个图片
                BufferedImage image = new BufferedImage(88, 20, BufferedImage.TYPE_INT_RGB);
                //得到图片
                Graphics2D g = (Graphics2D) image.getGraphics();
                //设置图片背景颜色
                g.setColor(Color.white);
                g.fillRect(0,0,80,20);
                //给图片写数据
                g.setColor(Color.BLACK);
                g.setFont(new Font(null,Font.BOLD,20));
                g.drawString(makeNum(),0,20);
                //告诉浏览器这个请求用图片打开
                resp.setContentType("image/jpeg");
                //网站存在缓存,不让浏览器缓存
                resp.setDateHeader("expires",-1);
                resp.setHeader("Cache-Control","no-cache");
                resp.setHeader("Pragma","no-cache");
                //把图片写给浏览器
                ImageIO.write(image,"jpg",resp.getOutputStream());
        
            }
            //生成随机数
            private String makeNum(){
                  
                  
                Random random = new Random();
                String num = random.nextInt(9999999) + "";
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < 7 - num.length(); i++) {
                  
                  
                    sb.append("0");
                }
                String s = sb.toString() + num;
                return s;
            }
        
      1. Implement redirection
        Insert image description here

        After B receives the request from client A, B will notify client A to access another web resource C. This process is redirection.

        Common scenarios:

        • User login
        void sendRedirect(String var1) throws IOException;
        
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                  
                  
                /*
                    resp.setHeader("Location","/r/img");
                    resp.setStatus(302);       
                */      
                resp.sendRedirect("/r/img");//重定向
            }
        

        The difference between redirecting and grabbing

        Same point:

        • The page will jump

        difference:

        • When the request is forwarded, the url will not change 307
        • The url will change when redirecting 302
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              
              
              //处理请求
              String username = req.getParameter("username");
              String password = req.getParameter("password");
      
              System.out.println(username+"--"+password);
              //重定向时注意路径问题,路径错误报404
              resp.sendRedirect("/r/success.jsp");
          }
      
        <servlet>
          <servlet-name>RequestTest</servlet-name>
          <servlet-class>com.hwt.servlet.RequestTest</servlet-class>
        </servlet>
        <servlet-mapping>
          <servlet-name>RequestTest</servlet-name>
          <url-pattern>/login</url-pattern>
        </servlet-mapping>
      
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>Title</title>
      </head>
      <body>
          <h1>success</h1>
      </body>
      </html>
      

6.7、HttpServletRequest

HttpServletRequest represents the client's request. The user accesses the server through the Http protocol. All information in the HTTP request will be encapsulated into HttpServletRequest. All the customer's information is obtained through the HttpServletRequest method.

1. Obtain the parameters passed by the front end and request forwarding

req.getParameter()//获取一个
req.getParameterValues()//获取多个

Request forwarding

public class LoginServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //后台接收中文乱码问题
        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("*******************************");
        //后台接收中文乱码问题
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbys));
        System.out.println("*******************************");
        //通过请求转发
        //这里的/代表当前的web应用
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doGet(req,resp);
    }
}

7、Cookie、Session

7.1. Conversation

**Session:** The user opens a browser, clicks on many links, accesses multiple web resources, and closes the browser. This process can be called a session.

Stateful session:

How to prove that you have logged in to a website before?

client server

  1. The server sends a letter to the client, and the client can just bring the letter with it the next time it visits the server; cookie
  2. The server registers that you have been here and will match you directly the next time you come; seesion

7.2. Two techniques for saving sessions

cookie

  • Client technology (response, request)

seesion

  • Server technology, using this technology, can save the user's session information. You can put information or data in Session

Example: After logging in to the website, you do not need to log in again the next time you use it.

7.3、Cookie

Insert image description here

  1. Get cookie information from request

  2. Server responds to client Cookie

    Cookie[] cookies = req.getCookies();//获得Cookie
    cookie.getName();//获得Cookie中的key
    cookie.getValue();//获得Cookie中的Value
    new Cookie("lastLoginTime", System.currentTimeMillis()+"");//新建一个Cookie
    cookie.setMaxAge(24*60*60);//设置Cookie有效时长
    resp.addCookie(cookie);//响应给客户端
    

    Cookie: Generally stored in the local user directory appdata

    Is there an upper limit for cookies on a website?

    • A cookie can only save one piece of information;
    • A web site can send multiple cookies to iBrowser and store up to 20 cookies;
    • Cookie size is limited to 4kb;
    • Browser limit of 300 cookies.

    Delete cookies

    • If you do not set a time limit, it will automatically expire when you close the browser;
    • Set the validity period to 0;

encode decode

URLEncoder.encode("测试","utf-8"))
URLDecoder.decode(cookie.getValue(),"utf-8")

7.4. Session (Key Points)

Insert image description here

Session:

  • The server will create a Session object for each user (browser);
  • A Session occupies a browser. As long as the browser is not closed, this Session exists;
  • After the user logs in, he can access the entire website! —>Save user information;

The difference between Session and Cookie:

  • Cookie writes the user's data to the user's browser, and the browser saves it (can save multiple)
  • Session writes the user's data to the user's exclusive Session and saves it on the server side (save important information and reduce the waste of server resources)
  • Session object is created by the service

use:

  • Save a logged-in user information;
  • Shopping cart information;
  • Data that is frequently used throughout the website is generally stored in Session.

Use Session:

public class SessionDome01 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

        //解决乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //得到Session
        HttpSession session = req.getSession();

        //给Session中存东西
        session.setAttribute("name",new Person("测试",2));

        //获取Session的ID
        String sessionIdid = session.getId();

        //判断session是不是新创建的
        if (session.isNew()){
    
    
            resp.getWriter().write("session创建成功,ID"+sessionIdid);
        }else {
    
    
            resp.getWriter().write("session已经在服务器中存在了,ID"+sessionIdid);
        }
        //Session创建的时候做了什么事
//        Cookie cookie = new Cookie("JSESSIONID", sessionIdid);
//        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

    }
}

GetSession

public class SessionDome02 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

        //解决乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //得到Session
        HttpSession session = req.getSession();

        Person person = (Person) session.getAttribute("name");
        System.out.println(person.toString());
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

    }
}

Log out Session

public class SessionDome03 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

        //解决乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8")
        //得到Session
        HttpSession session = req.getSession();
        session.invalidate();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

    }
}

Automatic session expiration: web.xml configuration

<!--    设置Session默认的失效时间-->
    <session-config>
<!--        15分钟后Session自动失效,以分钟为单位-->
        <session-timeout>15</session-timeout>
    </session-config>

Insert image description here

8、jsp

8.1. Definition

Java Servlet Pages: Java server pages, used in dynamic Web technology like servlets!

The greatest feature

  • Similar to HTML
  • the difference:
    • HTML only provides static data to users
    • JSP pages can embed Java code to provide users with dynamic data

8.2. JSP principles

JSP execution process:

  • The inner workings of the server

    There is a work directory in tomcat;

    Using tomcat in IDEA will generate a work directory in the IDE's Tomcat

    C:\Users\Administrator\AppData\Local\JetBrains\IntelliJIdea2021.3\tomcat\65e27a1a-da4c-4252-87cb-54a11768bc5f\work\Catalina\localhost\javaweb_session_cookie_war\org\apache\jsp
    

Insert image description here

​The original jsp file becomes a Java file

The browser sends a request to the server. No matter what resource is accessed, it is actually accessing the Servlet.

jsp will eventually be converted into Java classes

jsp is essentially a Servlet

//初始化
  public void _jspInit() {
    
    
  }
//销毁
  public void _jspDestroy() {
    
    
  }
//jspService
  public void _jspService(HttpServletRequest request, HttpServletResponse response) {
    
    
  1. Judgment request

  2. built-in objects

    final javax.servlet.jsp.PageContext pageContext;	//页面上下文
    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:当前
    HttpServletRequest request;							//请求
    HttpServletResponse response;						//响应
    
  3. Code added before outputting the page

    response.setContentType("text/html");		//设置响应的页面类型
    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
    Insert image description here

In the JSP page:

As long as it is JAVA code, it will be output unchanged.

If it is HTML code, it will be replaced with:

 out.write("<h2>Hello World!</h2>\n");

Replace the format to the front end!

8.3. JSP basic syntax

As an application of Java technology, JSP has some of its own extended syntax, which is supported by all syntaxes in Java.

JSP expression

    <%--  JSP表达式
    作用:用来将程序的输出输出到客户端
    <%= 变量或者表达式 %>
    --%>
  <%= new java.util.Date() %>

JSP script snippet

  <%
    int sum = 0;
    for (int i = 0; i <= 100; i++) {
      sum+=i;
    }
    out.println("<h1>Sum = "+sum+"</h1>");
  %>

Reimplementation of script fragments

  <%
    int x = 10;
    out.println(x);
  %>
    <p>JSP文档</p>
  <%
    int y = 2;
    out.println(x);
    out.println(y);
  %>
  <hr>
<%--  在代码中嵌入HTML元素--%>
  <%
    for (int i = 0; i < 5; i++) {
  %>
    <h1>hello <%=i%></h1>
  <%
    }
  %>

JSP declaration

<%!
  static {
    System.out.println("加载中");
  }
  private int a = 0;
  public void hwt(){
    System.out.println("hwt");
  }
%>

JSP declaration: will be compiled into the Java class generated by JSP! Others will be declared in the jsp_Service method!

Embed Java code in JSP code

<%%>
<%=%>
<%!%>
<%--注释--%>

JSP comments will not be displayed to the client, but HTML comments will be displayed to the client.

8.4. JSP instructions

<%@page args... %>

Two ways to merge pages

    <%--@include会将两个页面合并
    	会导致变量冲突
    --%>
    <%@include file="common/header.jsp"%>
    <h1>主体</h1>
    <%@include file="common/footer.jsp"%>

    <hr>

    <%--
    jsp标签
    jsp:include:拼接页面,本质还是三个
    --%>
    <jsp:include page="common/header.jsp"/>
    <h1>网页主体</h1>
    <jsp:include page="common/footer.jsp"/>

8.5. Nine built-in objects

  • PageContext stores things
  • Request to save something
  • Response
  • Session saves things
  • Aplication【ServletContext】save things
  • Config【ServletConfig】
  • out
  • page
  • Exception
<%
pageContext.setAttribute("name1","测试一");//保存的数据只在一个页面中有效
request.setAttribute("name2","测试二");//保证村的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3","测试三");//保证村的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","测试四");//保存的数据只在服务器中有效,从打开服务器到关闭服务器
%>
<%--
    脚本片段中的代码,会被原封不动生成到.jsp.java
    要求:这些代码必须保证java语法的正确性
--%>
<%
    //通过pagecontext取出,寻找的方式
    //从底层到高层(作用域):page->request->session->applocation
    //JSP:双亲委派机制:
    String name1 = (String) pageContext.findAttribute("name1");
    String name2 = (String) pageContext.findAttribute("name2");
    String name3 = (String) pageContext.findAttribute("name3");
    String name4 = (String) pageContext.findAttribute("name4");
%>
<%--使用el表达式取--%>
<h1>${name1}</h1>
<h1>${name2}</h1>
<h1>${name3}</h1>
<h1>${name4}</h1>

Request: The client sends a request to the server. The generated data is useless after the user has finished reading it, such as news.

Session: A request sent by the client to the server. The generated data can be used by the user after use, such as a shopping cart.

Application: The client sends a request to the server. The generated data is used by one user, but other users may still use it, such as chat records.

8.6, JSP tags, JSTL tags, EL expressions

 <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/taglibs/standard -->
<!--        standard标签库-->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

EL expression: ${}

  • retrieve data
  • perform operations
  • Get common objects used in web development

jsp tag

<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="name" value="ceshi"/>
    <jsp:param name="password" value="root"/>
</jsp:forward>

JSTL expression

The use of JSTL tag library is to make up for the shortcomings of HTML tags; it has customized many tags, and the functions of the tags are the same as Java codes.

formatting tags

SQL tag

XML tag

Core Tags (Mastery)

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>//引入标签

Insert image description here

JSTL tag library usage steps

  • Introduce the corresponding taglib
  • Use the method
  • Tomcat also needs to introduce the jstl package, otherwise an error will be reported: jstl parsing error

c:if

<body>
<h4>测试c:if</h4>
<form action="coreif.jsp" method="get">
    <%--
        el表达式获取表单中的数据
        ${param.参数名}
    --%>
    <input type="text" name="username" value="${param.username}"/>
    <input type="submit" value="登录">
</form>

<%--判断提交的是管理员,则登陆成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
    <c:out value="管理员欢迎您"/>
</c:if>
<c:out value="${isAdmin}"/>

</body>

c:forEach

<%
    ArrayList<String> people = new ArrayList<>();
    people.add(0,"张三");
    people.add(1,"李四");
    people.add(2,"王五");
    people.add(3,"赵六");
    request.setAttribute("list", people);
%>
<%--
var,    每一次遍历出来的变量
items, 要遍历的对象
begin,  哪里开始
end,    到哪里
step,  步长
--%>
<c:forEach var="people" items="${list}">
    <c:out value="${people}"/><br>
</c:forEach>
<hr>

<c:forEach var="people" items="${list}" begin="1" end="3" step="2">
    <c:out value="${people}"/><br>
</c:forEach>

9、JavaBean

Entity class

JavaBean has a specific way of writing:

  • There must be a parameterless constructor
  • Properties must be private
  • There must be corresponding get/set methods

Generally used to map ORM to database fields;

ORM: Object Relational Mapping

  • Table—>Class
  • Field---->Attribute
  • Row record---->Object
id name age address
1 Zhang San 3 Tianjin
2 John Doe 4 Beijing
3 Wang Wu 5 Nanjing
class People{
    
    
    private int id;
    private String name;
    private int age;
    private String address;
}
class A{
    
    
    new People(1,"张三",3"南京");
}
  • filter
  • File Upload
  • Email sending
  • JDBC Review: How to use JDBC

10. MVC three-tier architecture

What is MVC: Model View Controller model, view, controller

10.1. Early days:

In the early years, users had direct access to the control layer. The control layer can directly operate the database

servlet--CRUD-->数据库
弊端:程序十分臃肿,不利于维护
servlet代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
    
   架构:没有什么是加一层解决不了的

10.2. Three-tier architecture

Insert image description here

  • Model
    • Business processing: business logic (Service)
      • Data persistence CRUD: (Dao)
  • View
    • display data
    • Provide a link to initiate a Servlet request (
  • Controller(servlet)
    • Receive user request (req: request parameters, session information...)
    • Hand it over to the business to handle the code
    • Control view jump

Login—>Receive user login request—>Process user request (obtain user login parameters, username, password) and hand it over to the business layer to process the login business (determine whether the account password is correct: transaction)—>Dao layer queries whether the username and password are correct— >Database

11. Filter (key point)

Filter: Filter, used to filter website data

  • Handle Chinese garbled characters
  • Login authentication

Insert image description here

Filter development steps

  1. Guide package

    import javax.servlet.*;
    
  2. Implement the Filter interface and rewrite the corresponding method

    public class CharacterEncodingFilter implements Filter {
          
          
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
          
          
            System.out.println("初始化");
        }
      @Override
      //filterChain:链
      /*
       *   1. 过滤所有代码,再过滤特定请求的时候都会执行
       *   2. 必须要让过滤器继续同行
       * filterChain.doFilter(servletRequest,servletResponse)
       * */
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
          
          
            servletRequest.setCharacterEncoding("utf-8");
            servletResponse.setCharacterEncoding("utf-8");
            servletResponse.setContentType("text/html;charset=UTF-8");
    
            System.out.println("CharacterEncodingFilter执行前");
            filterChain.doFilter(servletRequest,servletResponse);//如果不写,程序到这里会被拦截停止
            System.out.println("filterChain执行后");
        }
    
        @Override
        public void destroy() {
          
          
            System.out.println("销毁");
        }
    }
    
  3. Configure Filter in web.xml

        <servlet>
            <servlet-name>ShowServlet</servlet-name>
            <servlet-class>com.hwt.ShowServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>ShowServlet</servlet-name>
            <url-pattern>/servlet/show</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>ShowServlet</servlet-name>
            <url-pattern>/show</url-pattern>
        </servlet-mapping>
    
        <filter>
            <filter-name>CharacterEncodingFilter</filter-name>
            <filter-class>com.hwt.filter.CharacterEncodingFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>CharacterEncodingFilter</filter-name>
            <url-pattern>/servlet/*</url-pattern>
        </filter-mapping>
    

12. Listener

Implement a listener interface; N types of listener interfaces

  1. Write a listener

    Implement the listener interface

    //统计网站在线人数:统计session个数
    public class OnlineCountListener implements HttpSessionListener {
          
          
    
        @Override//创建session监听,一旦创建session就会触发事件
        public void sessionCreated(HttpSessionEvent se) {
          
          
            ServletContext ctx = se.getSession().getServletContext();
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            if (onlineCount==null){
          
          
                onlineCount = new Integer(1);
            }else {
          
          
                int count = onlineCount.intValue();
                onlineCount = new Integer(count+1);
            }
            ctx.setAttribute("OnlineCount",onlineCount);
        }
    
        @Override//销毁session监听,一旦销毁session就会触发事件
        public void sessionDestroyed(HttpSessionEvent se) {
          
          
            ServletContext ctx = se.getSession().getServletContext();
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            if (onlineCount==null){
          
          
                onlineCount = new Integer(0);
            }else {
          
          
                int count = onlineCount.intValue();
                onlineCount = new Integer(count-1);
            }
            ctx.setAttribute("OnlineCount",onlineCount);
        }
    }
    
  2. Register listener in web.xml

    <!--    注册监听器-->
        <listener>
            <listener-class>com.hwt.listener.OnlineCountListener</listener-class>
        </listener>
    
  3. Whether to use it depends on the situation

13. Common applications of filters and listeners

Listener, commonly used in GUI programming

public class TestPanel {
    
    
    public static void main(String[] args) {
    
    
        Frame frame = new Frame("测试");//创建一个窗体
        Panel panel = new Panel(null);//面板
        frame.setLayout(null);//设置窗体布局

        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(0,0,255));//设置背景颜色
        panel.setBounds(50,50,300,300);
        panel.setBackground(new Color(0,255,0));//设置背景颜色
        frame.add(panel);
        frame.setVisible(true);

        //监听事件,监听关闭事件
        frame.addWindowListener(new WindowAdapter() {
    
    
            @Override
            public void windowClosing(WindowEvent e) {
    
    
                System.out.println("关闭ing");
            }
        });
    }
}

Only after the user logs in can they enter the home page! After the user logs out, he cannot enter the home page.

  1. After the user logs in, put user data into the Session

  2. When entering the homepage, it is necessary to determine whether the user is logged in; used in filters

    public class SysFilter implements Filter {
          
          
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
          
          
        }
        @Override
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain Chain) throws IOException, ServletException {
          
          
    
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
    
            if (request.getSession().getAttribute("USER_SESSION")==null){
          
          
                response.sendRedirect("/error.jsp");
            }
    
            Chain.doFilter(request,response);
        }
        @Override
        public void destroy() {
          
          
        }
    }
    

14、JDBC

JDBC: Java connects to the database, which is equivalent to adding a unified layer of drivers between various databases.

Jar packages that need to be imported

  • java.sql
  • javax.sql
  • mysql-connecter-java connection driver

database

CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(40),
`password` VARCHAR(40),
email VARCHAR(60),
birthday DATE
);

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'张三','123456','[email protected]','2000-01-01');

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','[email protected]','2000-01-01');

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','[email protected]','2000-01-01');

SELECT * FROM users

Import database dependencies

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
    </dependencies>

JDBC fixed steps

public class Testjdbc {
    
    
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
    
    
        //配置信息
        String url = "jdbc:mysql://localhost:3306/jdbc?userUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "root";
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.连接数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        Statement statement = connection.createStatement();
        //4.编写sql
        String sql = "select * from users";
        //5.执行sql
        ResultSet rs = statement.executeQuery(sql);
        while (rs.next()){
    
    
            System.out.println("id"+rs.getObject("id"));
            System.out.println("name"+rs.getObject("name"));
            System.out.println("password"+rs.getObject("password"));
            System.out.println("email"+rs.getObject("email"));
            System.out.println("birthday"+rs.getObject("birthday"));
        }
        //6.关闭连接,释放资源
        rs.close();
        statement.close();
        connection.close();
    }
}

affairs

Either both succeed or both fail

ACID principles: atomicity, consistency, isolation, durability

开启事务
    事务提交	commit()
    事务回滚	rollback()
关闭事务
    
转账
    A1000
    B1000
 经过转账后:两种情况 A900	B1100
    			  A1000  B1000
    

Transaction operations

public class Testjdbc2 {
    
    
    public static void main(String[] args) throws SQLException {
    
    
        //配置信息
        String url = "jdbc:mysql://localhost:3306/jdbc?userUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "root";
        Connection connection = null;
        //1.加载驱动
        try {
    
    
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.连接数据库
            connection = DriverManager.getConnection(url, username, password);
            //3.通知数据库开启事务,false 开启
            connection.setAutoCommit(false);

            String sql = "update account set money = money - 100 where name = 'A';";
            connection.prepareStatement(sql).executeUpdate();
            //错误
//            int i = 1 / 0;
            String sql2 = "update account set money = money + 100 where name = 'B';";
            connection.prepareStatement(sql2).executeUpdate();
            connection.commit();//两条都执行成功,才会提交事务
            System.out.println("success");
        } catch (Exception e) {
    
    
            try {
    
    
                connection.rollback();
                e.printStackTrace();
            } catch (SQLException ex) {
    
    
                ex.printStackTrace();
            }
        }finally {
    
    
            connection.close();
        }
    }
}

JavaWeb implements file upload (organized from Western Open Source Teacher Qinjiang)

1. Preparation

For file upload, the browser submits the file to the server in the form of a stream during the upload process.

Generally, the file upload component of Apache's open source tool common-fileupload is used.

common-fileupload depends on the common-io package, so you also need to download this package.

We download the latest jar package:

common-fileupload :https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload/1.4

common-io :https://mvnrepository.com/artifact/org.apache.commons/commons-io/1.3.2

Import the Jar package in the JavaWeb project:

Upload file process:

Insert image description here

2. Introduction to usage classes

Notes on file upload

  1. To ensure the security of the server, uploaded files should be placed in a directory that is inaccessible to the outside world, such as WEN-INF.
  2. To prevent files with the same name from being overwritten, specify a unique file name for the file.增加时间戳 -uuid -MD5 --位运算算法
  3. Limit the size of uploaded files.
  4. You can limit the type of uploaded files. When receiving a file, determine whether the file name suffix is ​​legal.

Detailed explanation of the classes needed

ServletFileUpload is responsible for processing the uploaded file data and encapsulating each input item in the form into a FileItem object. The DiskFileItemFactory object is required when using the ServletFileUpload object to parse the request.

Therefore, we need to construct the DiskFileItemFactory object before parsing , and set the fileItemFactory property of the ServletFileUpload object through the construction method of the ServletFileItem object or setFileItemFactory() .

FileItem class

There must be a name in the HTML page:<p><input type="file" name="filename"></p>

<form action=""  method="post">
  <p><input type="file" name="file1"></p>
  <p><input type="file" name="file1"></p>
  <p><input type="submit"> | <input type="reset"></p>
</form>

If the form contains a file upload item, the entype attribute of the form must be set to multipart/form-data

/*
	通过表单上传文件
	get:上传文件大小有限制
	post:上传文件大小没有限制
*/
<form action="" enctype="multipart/form-data" method="post">
  上传用户:<input type="text" name="username"><br/>
  <p><input type="file" name="file1"></p>
  <p><input type="file" name="file1"></p>
  <p><input type="submit"> | <input type="reset"></p>
</form>

If the browser's form type is multipart/form-data, the server must obtain data through the stream

[Introduction to common methods]

//isFormFile方法用于判断FileItem类对象封装的数据是一个普通文本表单//还是一个文件表单,如果时普通表单字段则返回true,否则返回false

booleanisField();//getFieldName方法用于返回表单标签name属性的值

String getFieldName();//getString方法用于将FileItem对象中保存的数据流内容以一个字符串返回

String getString();//getName方法用于获得文件上传字段中的文件名。

String getName();//以流的形式返回上传文件的数据内容。

InputStream getInputStream();//delete方法用来清空FileItem类对象中存放的主体内容//如果主体内容被保存在临时文件中,delete方法将删除该临时文件

void delete();

ServletFileUpload类

ServletFileUpload is responsible for processing uploaded file data and encapsulating each input item in the form into a FileItem object. Use its parseRequest(HttpServletRequest) method to encapsulate the data submitted through each HTML tag in the form into a FileItem object, and then Returned as a List. This method is simple and easy to use for uploading files.

3. Code writing

package com.hwt.servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
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 {
    
    
    //private File file;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    
    
        //判断上传的表单是普通表单还是带文件的表单,是返回true,否返回false;
        if (!ServletFileUpload.isMultipartContent(request)){
    
    
            return;//如果这是一个普通文件我们直接返回
        }//如果通过了这个if,说明我们的表单是带文件上传的
        //创建上传文件的保存目录,为了安全建议在WEB-INF目录下,用户无法访问
        String uploadpath = this.getServletContext().getRealPath("WEB-INF/Upload");//获取上传文件的保存路径
        File uploadfile = new File(uploadpath);
        if (!uploadfile.exists()){
    
    
            uploadfile.mkdir();//如果目录不存在就创建这样一个目录
        }
        /*//临时文件
        //临时路径,如果上传的文件超过预期的大小,我们将它存放到一个临时目录中,过几天自动删除,或者提醒用户转存为永久
        String tmppath = this.getServletContext().getRealPath("WEB-INF/tmp");
        File file = new File(tmppath);
        if (!file.exists()){
            file.mkdir();//如果目录不存在就创建这样临时目录
        }*/
        //处理上传的文件一般需要通过流来获取,我们可以通过request.getInputstream(),原生态文件上传流获取,十分麻烦
        //但是我们都建议使用Apache的文件上传组件来实现,common-fileupload,它需要依赖于common-io组件;
        try {
    
    
            //1、创建DiskFileItemFactory对象,处理文件上传路径或限制文件大小
            File file = null;
            DiskFileItemFactory factory = gteDiskFileItemFactory(file);
            //2、获取ServletFileUpload
            ServletFileUpload upload = getServletFileUpload(factory);
            //3、处理上传文件
            String msg = uploadParseRequest(upload,request,uploadpath);
            //Servlet请求转发消息
            request.setAttribute("msg",msg);
            request.getRequestDispatcher("/info.jsp").forward(request,response);
        }catch (FileUploadException e){
    
    
            e.printStackTrace();
        }
    }

    public static DiskFileItemFactory gteDiskFileItemFactory(File file){
    
    
        //1、创建DiskFileItemFactory对象,处理文件上传路径或限制文件大小
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //通过这个工厂设置一个缓冲区,当上传的文件大小大于缓冲区的时候,将它放到临时文件中;
        factory.setSizeThreshold(1024 * 1024);//缓冲区大小为1M
        factory.setRepository(file);
        return factory;
    }
    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) throws UnsupportedEncodingException {
    
    
        //2、获取ServletFileUpload
        ServletFileUpload upload = new ServletFileUpload(factory);
        //监听文件上传进度
        upload.setProgressListener(new ProgressListener() {
    
    
            @Override
            public void update(long pBytesRead, long lpContentLenght, int i) {
    
    
                //pBytesRead:已读取到的文件大小
                //pContentLenght:文件大小
                System.out.println("总大小:"+lpContentLenght+"已上传:"+pBytesRead);
            }
        });
        //处理乱码问题
        upload.setHeaderEncoding("UTF-8");
        //设置单个文件的最大值
        upload.setFileSizeMax(1024 * 1024 * 10);
        //设置总共能够上传文件的大小
        //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、处理上传文件
        //把前端的请求解析,封装成一个FileItem对象
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem fileItem : fileItems) {
    
    
            if (fileItem.isFormField()){
    
     //判断是普通表单还是带文件的表单
                //getFieldName指的是前端表单控件的name
                String name = fileItem.getFieldName();
                String value = fileItem.getString("UTF-8");//处理乱码
                System.out.println(name+":"+value);
            }else {
    
    //判断它是带文件的表单
                //======================处理文件=======================//
                //拿到文件的名字
                String uploadFileName = fileItem.getName();
                System.out.println("上传的文件名:"+uploadFileName);
                if (uploadFileName.trim().equals("") || uploadFileName == null){
    
    
                    continue;
                }
                //获得上传的文件名,例如/img/girl/ooa.jpg,只需要ooa,其前面的后面的都不需要
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                //获得文件的后缀名
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
                /*
                 * 如果后缀名 fileExtName 不是我们需要的
                 *就直接return,不处理,告诉用户类型不对
                 * */
                System.out.println("文件信息【文件名:"+fileName+"文件类型:"+fileExtName+"】");
                //可以使用UUID(唯一通用识别码)来保证文件名的统一
                String uuidFileName = UUID.randomUUID().toString();
                //=======================传输文件=========================//
                //获得文件上传的流
                InputStream inputStream = fileItem.getInputStream();
                //创建一个文件输出流
                FileOutputStream fos = new FileOutputStream(uploadpath + "/" + uuidFileName +"."+ fileExtName);
                //创建一个缓冲区
                byte[] buffer = new byte[1024 * 1024];
                //判断是否读取完毕
                int len = 0;
                //如果大于0,说明还存在数据
                while ((len=inputStream.read(buffer))>0){
    
    
                    fos.write(buffer,0,len);
                }
                //关闭流
                fos.close();
                inputStream.close();
                msg = "文件上传成功!";
                fileItem.delete();//上传成功,清除临时文件
            }
        }
        return msg;
    }
}

loadException { String msg = ""; //3. Process uploaded files // Parse the front-end request and encapsulate it into a FileItem object List fileItems = upload.parseRequest(request); for (FileItem fileItem : fileItems) { if (fileItem. isFormField()){ //Determine whether it is a normal form or a form with a file //getFieldName refers to the name of the front-end form control String name = fileItem.getFieldName(); String value = fileItem.getString("UTF-8"); //Handle garbled characters System.out.println(name+":"+value); }else {//Judge that it is a form with a file //











Process 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 oa is needed, and the preceding and following ones are not required String fileName = uploadFileName.substring(uploadFileName.lastIndexOf ("/") + 1); //Get the suffix name of the file String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1); /* * If the suffix name fileExtName is not what we need * just return directly , not processed, telling the user that the type is incorrect * */ System.out.println("File information [File name:"+fileName+"File type:"+fileExtName+"]"); //UUID (unique universal identification code) can be used To ensure the uniformity of file names String uuidFileName = UUID.randomUUID().toString(); //=













Transfer files===//
//Get the file upload stream
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];
//Determine whether the reading is completed
int len ​​= 0;
//If it is greater than 0, it means there is still data
while ((len=inputStream.read(buffer ))>0){ fos.write(buffer,0,len); } //Close the stream fos.close(); inputStream.close(); msg = "File uploaded successfully!"; fileItem.delete();/ /Upload successful, clear temporary files } } return msg; } }












Guess you like

Origin blog.csdn.net/qq_44624801/article/details/129113638