JavaWeb entry to actual combat---notes

Most of the notes are moved to the javaWeb that the mad god said at station B. By the way, the pictures and texts are merged and recorded for easy review

Video address: https://www.bilibili.com/video/BV12J411M7Sj

Table of contents

1. Basic concepts

1.1. Preface

1.2, web application web application:

1.3, static web

2. Web server

2.1. Technical explanation

3、Tomcat

3.1 Install tomcat tomcat

3.2, Tomcat startup and configuration

3.3. Configuration

4、Http

4.1, what is HTTP

4.2. Two eras

4.3, Http request

1. Response body

2. Response status code

5、Maven

5.1 Maven project architecture management tool

5.2 Download and install Maven

5.4 Alibaba Cloud Mirroring

5.5 Local Warehouse

5.6 ~ 5.13 notes - download address

6、Servlet

6.1 Introduction to Servlets

6.2、HelloServlet

6.5、ServletContext

6.7、HttpServletRequest

7、Cookie、Session

7.1. Session

7.2. Two techniques for saving sessions

7.3、Cookie

7.4, Session (key)

8、JSP

8.1, what is JSP

8.2, JSP principle

8.3, JSP Basic Syntax

8.5, 9 built-in objects

8.6, JSP tags, JSTL tags, EL expressions

9、JavaBean

10. MVC three-tier architecture

10.1, the previous architecture

10.2, MVC three-tier architecture

11. Filter (emphasis)

12. Listener

13. Common applications of filters and listeners

14、JDBC


1. Basic concepts

1.1. Preface

  • web development:
    • web, the meaning of web page, www.baidu.com·
      • static web
        • html,css
        • The data available for all to see never changes!
    • dynamic web 
      • Taobao, almost all websites;
      • Technology stack: Servlet/JSP, ASP, PHP

1.2, web application web application:

programs that provide browser access;

  • a.html, b.html... multiple web resources, these web resources can be accessed by the outside world and provide services to the outside world;
  • Any page or resource you can access exists on a computer in a certain corner of the world.
  • 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 program is written, if you want to provide access to the outside world; you need a service to manage it uniformly

1.3, static web

  • *.htm, *.html are the background of network members. If these things exist on the server all the time, we can read them directly and need the network;

  • Disadvantages of static web
    • Web pages cannot be updated dynamically, all users see the same page
      • Carousel image, click special effect: pseudo-dynamic
      • JavaScript [in actual development, it is used the most]
      • VBScript
    • It cannot interact with the database (data cannot be persisted, users cannot interact)

1.4 , dynamic web

The page will be displayed dynamically, "the display effect of the web page varies from person to person"

shortcoming:

  • There is an error in the dynamic web resource added to the server, we need to rewrite our background program and republish;
  • Advantages of shutdown maintenance:
  • Web pages can be updated dynamically, and all users see different pages. It can interact with the database (data persistence: registration, product information, user information...)

2. Web server

2.1. Technical explanation

ASP:

  • Microsoft: ASP is the earliest popular in China;
  • · Embed VB script in HTML, ASP+COM;
  • ·In ASP development, basically a page has several lines of business code, and the page is extremely chaotic
  • ·High maintenance cost!
  • C#
  • IIS

php:

  • PHP development is fast, powerful, cross-platform, and the code is very simple (70%, WP)
  • Situations that cannot carry a large amount of traffic (limitations)

jSP/Servlet:

B/S; browse and server C/S: client and server

  • The B/S architecture promoted by sun company
  • Based on the Java language (all big companies, or some open source components, are written in Java)
  • Can bear the impact of the three high problems;
  • 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;

lIS

Microsoft; ASP., Windows comes with

Tomcat

Programming for Baidu:

Tomcat is a core project in the jakarta project of the Apache Software Foundation (Apache Software Foundation). The latest Servlet and JSP specifications can always be reflected in Tomcat, because Tomcat has advanced technology, stable performance, and is free.

Therefore, it is deeply loved by lava lovers and recognized by some software developers, and has become a relatively popular Web application server.

Tomcat server is a free and open source web application server, which is a lightweight application server. It is widely used in small and medium-sized systems and occasions where there are not many concurrent access users. It is the first choice for developing and debugging JSP programs. For a Java beginner web person

It is the best choice for

Tomcat actually runs JSP pages and Serlets. The latest version of Tornct easy 9.0

After working for 3-5 years, you can try handwriting Tomcat server;

Download tomcat:

  1. install or extract
  2. Understand the configuration file and directory structure
  3. what this thing does

3、Tomcat

3.1 Install tomcat tomcat

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

3.2, Tomcat startup and configuration

Folder function:

Access test: http://localhost:8080/

Possible problems:

1. The Java environment variable is not configured

2. Flashback problem: need to configure compatibility

3. Garbled characters: set in the configuration file

You can modify java.util.logging.ConsoleHandler.encoding = GBK in conf/logging.properties to solve garbled characters

question

3.3. Configuration

The port number that can be configured to start

  • The default port number of tomcat is: 8080
  • mysql:3306
  • http:80
  • https:443
<Connector port="8081" protocol="HTTP/1.1"
      connectionTimeout="20000"
      redirectPort="8443" />

The name of the configurable host

  • The default hostname is: localhost->127.0.0.1
  • The default website application storage location is: webapps
<Host name="www.qinjiang.com"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

Difficult interview questions:

Please talk about how the website is accessed!

  1. Enter a domain name; press Enter
  2. Check whether there is this domain name mapping under the C:\Windows\System32\drivers\etc\hosts configuration file of this machine;

1. Yes: Directly return the corresponding ip address. In this address, there is a web program we need to access, which can be directly accessed

 127.0.0.1 www.qinjiang.com

3. No: go to the DNS server to find, if found, it will return, if not found, it will return not found;

4. You can configure environment variables (optional)

3.4 Publish a web site

If not, imitate first

  • Put the website you wrote on the server (Tomcat) under the specified web application folder (webapps), and you can access it

The structure a website should have

--webapps :Tomcat服务器的web目录
	-ROOT
	-kuangstudy :网站的目录名
		- WEB-INF
			-classes : java程序
			-lib:web应用所依赖的jar包
			-web.xml :网站配置文件
		- index.html 默认的首页
		- static 
            -css
            	-style.css
            -js
            -img
         -.....

HTTP Protocol: Interview

Maven: build tool

  • Maven installation package

Getting Started with Servlets

  • HelloWorld!
  • Servlet Configuration Principles

4、Http

4.1, what is HTTP

HTTP (Hypertext Transfer Protocol) is a simple request-response protocol that usually runs on top of TCP.

  • text: html, string, ...
  • Hypertext: pictures, music, video, location, map...  
  • Port: 80

Https: secure

4.2. Two eras

  • http1.0
    • HTTP/1.0: After the client can connect to the web server, it can only obtain one web resource and disconnect
  • http2.0
    • HTTP/1.1: After the client can connect to the web server, it can obtain multiple web resources.

4.3, Http request

Client--Send a request (Request)--Server

Baidu:

Request URL:https://www.baidu.com/   请求地址
Request Method:GET    get方法/post方法
Status Code:200 OK    状态码:200
Remote(远程) Address:14.215.177.39:443

Accept:text/html  
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.9    语言
Cache-Control:max-age=0
Connection:keep-alive

1. Request line

  • Request method in the 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, which is not safe but efficient
    • post: There is no limit to the parameters that the request can carry, and there is no limit to the size, and the data content will not be displayed in the URL address bar of the browser. It is safe, but not efficient.

2. Message header

Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../.

4.4 , Http response

server --response....client

Baidu:

Cache-Control:private 缓存控制 
Connection:Keep-Alive 连接 
Content-Encoding:gzip 编码 
Content-Type:text/html 类型 

1. Response body

Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../.
Refresh:告诉客户端,多久刷新一次;
Location:让网页重新定位;

2. Response status code

  • 200: request response success 200
  • 3xx: Request redirection Redirection: You go to the new location I gave you;
  • 4xx: Resource not found 404 The resource does not exist;
  • 5xx: Server Code Error 500 502: Gateway Error

Common interview questions:

When you enter the address in the address bar of your browser and press Enter, the page can be displayed back, what happened?

5、Maven

Why should I learn this technique?

1. In Javaweb development, a large number of jar packages need to be used, and we manually import them;

2. How can I let something automatically import and configure this jar package for me.

Thus, Maven was born!

5.1 Maven project architecture management tool

We are currently using it to facilitate the import of jar packages!

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

There are constraints, don't violate them.

Maven will stipulate how you should write our Java code, and you must follow this specification;

5.2 Download and install Maven

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

After the download is complete, unzip it;

Xiao Kuangshen's friendly suggestion: all the environments on the computer are placed in one folder for easy management;

5.3 Configure environment variables

Configure the following configuration in our system environment variables:

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

Test whether Maven is installed successfully, and ensure that the configuration must be completed!

5.4 Alibaba Cloud Mirroring

  • mirror: mirrors
  • Role: Speed ​​up our downloads
  • It is recommended to use the image of Alibaba Cloud in China
<mirror>
    <id>nexus-aliyun</id>  
    <mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>  
    <name>Nexus aliyun</name>  
    <url>http://maven.aliyun.com/nexus/content/groups/public</url> 
</mirror>

D:Enmvironment\apache-maven-3.6.2conf\ettings.xml

(Teacher Kuangshen configures the file location of the source and warehouse)

5.5 Local Warehouse

In the local warehouse, remote warehouse; create a local warehouse: localRepository

<localRepository>D:\Environment\apache-maven-3.6.2\maven-repo</localRepository>

5.6 ~ 5.13 notes - download address

(Refused to accept the degree plate) Download address: https://lanzoui.com/ibuibxi

The following 5.6 ~ 5.13 + case demonstration (picture)

The notes in the remaining part of Chapter 5 are recommended to cooperate with Mad God

"javaweb-06 : Maven operation in IDEA " , "javaweb-07 : solve some problems you encounter "

look carefully (back)

6、Servlet

6.1 Introduction to Servlets

  • Servlet is a technology developed by sun company 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 that implements the Serlet interface
    • Deploy the developed java class to the web server.

The Java program that implements the Servlet interface is called Servlet

6.2、HelloServlet

Serlvet interface Sun has two default implementation classes: HttpServlet, GenericServled

1. Build an ordinary Maven project, equal to the sc directory of the rationale, and we will build Moudel in this project in the future for our study; this empty project is the main Maven project;

2. Understanding of Maven father-son project;

In the parent project there will be

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

Subprojects will have

 <parent>
        <artifactId>javaweb-02-servlet</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

The java subproject in the parent project can be used directly

son extends father

3. Maven environment optimization

  1. Modify web.xml to the latest
  2. Complete the structure of maven

4. Write a Servlet program

1. Write a common class

2. Implement the Servlet interface, here we directly inherit HttpServlet

 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,Serlvet");
         }
     
         @Override
         protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
             doGet(req, resp);
         }
     }

5. Write Servlet mapping

Why do we need mapping: We write a JAVA program, but we need to access it through a browser, and the browser needs to connect to the web server, so we need to register the Servlet we wrote in the web service, and give him a path that the browser can access ;

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

6. Configure Tomcat

Note: It is enough to configure the path of the project release

7. Start the test, OK!

6.3 Principles of Servlets Servlets are invoked by web servers . After receiving browser requests, web servers will:

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>/hello2</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
          <servlet-name>hello</servlet-name>
          <url-pattern>/hello3</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
          <servlet-name>hello</servlet-name>
          <url-pattern>/hello4</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
          <servlet-name>hello</servlet-name>
          <url-pattern>/hello5</url-pattern>
      </servlet-mapping>

3. A servlet can specify a common mapping path

<servlet-mapping>
          <servlet-name>hello</servlet-name>
          <url-pattern>/hello/*</url-pattern>
      </servlet-mapping>

4. Default request path

<!--默认请求路径-->
       <servlet-mapping>
           <servlet-name>hello</servlet-name>
           <url-pattern>/*</url-pattern>
       </servlet-mapping>

5. Specify some suffix or prefix etc....

<!--可以自定义后缀实现请求映射
      注意点,*前面不能加项目映射的路径
      hello/sajdlkajda.qinjiang
      -->
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>*.qinjiang</url-pattern>
  </servlet-mapping>

6. Priority issues

The specified inherent mapping path has the highest priority, and if it cannot be found, the default processing request will be taken;

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

6.5、ServletContext

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

1. Sharing data

The data I saved in this servlet can be obtained in another servlet;

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 = "秦疆"; //数据
        context.setAttribute("username",username); //将一个数据保存在了ServletContext中,名字为:username 。值 username

    }

}
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);
    }
}
<servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.kuang.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.kuang.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>

test access results;

2. Obtain initialization parameters

 <!--配置一些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);
}

3. Request forwarding

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

4. Read resource files

Properties

  • Create new properties in the java directory
  • Create new properties in the resources directory

Discovery: all are packaged in the same path: classes, we commonly call this path classpath:

Idea: need a file stream

username=root12312
password=zxczxczxc

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

        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties");

        Properties prop = new Properties();
        prop.load(is);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");

        resp.getWriter().print(user+":"+pwd);

    }

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

The access test is ok;

6.6HttpServletResponse

The web server receives the http request from the client, and for this request, creates an HttpServletRequest 
object representing the request and an HttpServletResponse 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

1. Simple classification

The method responsible for sending data to the browser

servletOutputstream getOutputstream() throws IOException;
    Printwriter getwriter() throws IOException;

The method 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 varl,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 varl,int var2);

response status code

2. Download files

1. Output messages to the browser (always talking about it, so I won’t say it)

2. Download the file

1. To get the path of the downloaded file

2. What is the name of the downloaded file?

3. Set up and find a way to make the browser support downloading what we need

4. Get the input stream of the downloaded file

5. Create a buffer

6. Get the OutputStream object

7. Write the FileOutputStream stream to the buffer buffer

8. Use OutputStream to output the data in the buffer to the client!

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1. 要获取下载文件的路径
    String realPath = "F:\\班级管理\\西开【19525】\\2、代码\\JavaWeb\\javaweb-02-servlet\\response\\target\\classes\\秦疆.png";
    System.out.println("下载文件的路径:"+realPath);
    // 2. 下载的文件名是啥?
    String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
    // 3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码
    resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
    // 4. 获取下载文件的输入流
    FileInputStream in = new FileInputStream(realPath);
    // 5. 创建缓冲区
    int len = 0;
    byte[] buffer = new byte[1024];
    // 6. 获取OutputStream对象
    ServletOutputStream out = resp.getOutputStream();
    // 7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!
    while ((len=in.read(buffer))>0){
        out.write(buffer,0,len);
    }

    in.close();
    out.close();
}

3. Verification code function

How did the verification come about?

    • Front-end implementation
    • For backend implementation, you need to use Java image class to produce an image
package com.kuang.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class ImageServlet extends HttpServlet {

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

        //如何让浏览器3秒自动刷新一次;
        resp.setHeader("refresh","3");
        
        //在内存中创建一个图片
        BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D g = (Graphics2D) image.getGraphics(); //笔
        //设置图片的背景颜色
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);
        //给图片写数据
        g.setColor(Color.BLUE);
        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");
        }
        num = sb.toString() + num;
        return num;
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
<servlet>
	<servlet-name>ImageServlet</servlet-name>
	<servlet-class>com.kuang.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>Imageservlet</servlet-name>
	<url-pattern>/img</url-pattern>
</servlet-mapping>

Common scenarios:

User login

void sendRedirect(String var1) throws IOException;

test:

@override
protected void doGet(HttpservletRequest req, HttpservletResponse resp) throws ServletException, IOException {

    resp. sendRedirect("/r/img");//重定向
    /*
    resp. setHeader("Location","/r/img");
    resp. setstatus (302);
    *
}

<html>
	<body>
		<h2>Hel1o World!</h2>
		
		《%--这里超交的路径,需要寻找到项目的路径--%>
		<%--${pageContext. request, contextPath}代表当前的项目--%>
		<form action="${pageContext. request.contextPath}/login" method="get">
			用户名: <input type="text" name="username"> <br>
			密码: <input type="password" name="password"> <br>
			<input type="submit">
		</form>
	
	</body>
</html>
public class RequestTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //处理方求
    String username = req.getParameter( s: "username");
    String password  rea.getParameter( s: "password");

    System.out.println(username+":"+password);

    resp.sendRedirect(s: "/r/success.jsp");
}
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
    <head>
	    <title>Title</title>
	    </head>
    <body>
    	<h1>success</h1>
    </body>
</html>
 <servlet>
    <servlet-name>requset</servlet-name>
    <servlet-class>com. kuang. servlet. RequestTest</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>requset</servlet-name>
    <url-pattern>/login</url-pattern>
    </servlet-mapping>

Import dependent jar packages

 <dependencies>
    <!-- https://mvnrepository. com/artifact/javax. servLet/javax. servlet-opi -->
    <dependency>
    <groupld>javax.servlet</grouptd>
    <artifactId>javax. servlet-api</artifactId>
    <version>4.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax. servLet.jsp/javax. servLet.jsp-opi -->
    <dependency>
    <groupId>javax.servlet.jsp</groupld>
    <artifactId>javax. servlet.jsp-api</artifactId>
    <version>2.3.3</version>
    </dependency>
    </dependencies>
    </project>

6.7、HttpServletRequest

HttpServletRequest represents the request of the client. When the user accesses the server through the Http protocol, all the information in the HTTP request will be encapsulated into the HttpServletRequest. Through this HttpServletRequest method, all the information of the client can be obtained;

Get parameters , request forwarding

Create your own class and need to inherit the HttpServlet class

@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("============");
	system. out.println(req.getContextPath());
	//通过请求转发
	//这里的/代表当前的web应用
	req.getRequestDispatcher("/success.jsp").forward(req,resp);
}

7、Cookie、Session

7.1. Session

Session : The user opens a browser, clicks many hyperlinks, visits multiple web resources, and closes the browser. This process can be called

for the session;

Stateful conversation : A classmate has been to the classroom, and next time we come to the classroom, we will know that this classmate has been here before, which is called a stateful conversation;

How can you prove that you are a student of Xikai?

you drive west

1. Invoice West will issue you an invoice

2. The school registration Xikai marks that you have been here

A website, how to prove that you have been there?

client server

1. The server sends a letter to the client, and the next time the client visits the server, it is enough to bring the letter; cookie

2. The server registers that you have come, and I will match you when you come next time; seesion

7.2. Two techniques for saving sessions

cookie

Client technology (response, request)

session

Server technology, using this technology, can save the user's session information? We can put information or data in Session!

Common: After you log in to the website, you don’t need to log in again next time, and you will go directly to it the second time you visit!

7.3、Cookie

1. Get the cookie information from the request

2. The server responds to the client cookie

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

cookie : generally saved in appdata in the local user directory ;

Is there an upper limit for a website cookie! talk about details

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

delete cookies ;

  • If the validity period is not set, the browser will be closed and it will automatically expire;
  • Set the validity period to 0;

encode decode:

URLEncoder.encode("秦疆","utf-8")
URLDecoder.decode(cookie.getValue(),"UTF-8")

7.4, Session (key)

What is Session:

  • The server will create a Seesion object for each user (browser);
  • A Seesion monopolizes a browser, as long as the browser is not closed, the Session exists;
  • After the user logs in, it can access the entire website! --> save user information; save shopping cart information.....

The difference between Session and cookie:

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

scenes to be used:

  • Save the information of a logged-in user;
  • shopping cart information;
  • Data that is often used throughout the website, we save it in Session;

Use Session:

 
 
package com.kuang.servlet;

import com.kuang.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 {
        
        //解决乱码问题
        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("秦疆",1));
        //获取Session的ID
        String sessionId = session.getId();

        //判断Session是不是新创建
        if (session.isNew()){
            resp.getWriter().write("session创建成功,ID:"+sessionId);
        }else {
            resp.getWriter().write("session以及在服务器中存在了,ID:"+sessionId);
        }

        //Session创建的时候做了什么事情;
//        Cookie cookie = new Cookie("JSESSIONID",sessionId);
//        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
//得到Session
HttpSession session = req.getSession();

Person person = (Person) session.getAttribute("name");

System.out.println(person.toString());

HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销Session
session.invalidate();
 
 

Automatic session expiration: web.xml configuration

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

8、JSP

8.1, what is JSP

Java Server Pages: Java server-side pages, like Servlets, are used for dynamic Web technology!

The greatest feature:

  • Writing JSP is like writing HTML
  • the difference:
    • HTML only provides static data to the user
    • JAVA code can be embedded in JSP pages to provide users with dynamic data;

8.2, JSP principle

Ideas: How does JSP execute!

  • There is no problem at the code level
  • inner workings of the server

There is a work directory in tomcat;

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

The address of my computer:

C:\Users\Administrator.IntelliJIdea2018.1\system\tomcat\Unnamed_javaweb-session-cookie\work\Catalina\localhost\ROOT\org\apache\jsp

It is found that the page has been transformed into a Java program!

When the browser sends a request to the server, no matter what resource is accessed, it is actually accessing the Servlet !

The JSP will eventually be converted into a Java class too!

JSP is essentially a Servlet

 
 
//初始化
  public void _jspInit() {
      
  }
//销毁
  public void _jspDestroy() {
  }
//JSPService
  public void _jspService(.HttpServletRequest request,HttpServletResponse response)
1. 判断请求

2. 内置一些对象

final javax.servlet.jsp.PageContext pageContext;  //页面上下文
javax.servlet.http.HttpSession session = null;    //session
final javax.servlet.ServletContext application;   //applicationContext
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. The code added before the output 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;

4. We can use the above objects directly in the JSP page!

In the JSP page;

As long as it is JAVA code, it will be output intact;

If it is HTML code, it will be converted to:

out.write("<html>\r\n");

Such a format, output to the front end!

8.3, JSP Basic Syntax

Any language has its own grammar, and there are , in JAVA. As an application of java technology, JSP has some self-extended grammars (understand, just know!), and all Java grammars are supported!

JSP expression

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

jsp script fragment

 <%--jsp脚本片段--%>
  <%
    int sum = 0;
    for (int i = 1; i <=100 ; i++) {
      sum+=i;
    }
    out.println("<h1>Sum="+sum+"</h1>");
  %>

Reimplementation of script snippets

  <%
    int x = 10;
    out.println(x);
  %>
  <p>这是一个JSP文档</p>
  <%
    int y = 2;
    out.println(y);
  %>

  <hr>


  <%--在代码嵌入HTML元素--%>
  <%
    for (int i = 0; i < 5; i++) {
  %>
    <h1>Hello,World  <%=i%> </h1>
  <%
    }
  %>

JSP declaration

<%!
    static {
      System.out.println("Loading Servlet!");
    }

    private int globalVar = 0;

    public void kuang(){
      System.out.println("进入了方法Kuang!");
    }
  %>

JSP statement: will be compiled into the class that JSP generates Java! Others will be generated into the _jspService method!

In JSP, just embed Java code!

JSP comments will not be displayed on the client side, but HTML will!

8.4 , JSP instruction

<%@page args.... %>
<%@include file=""%>

<%--@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, 9 built-in objects

  • PageContext stores things
  • Request to save something
  • Response
  • Session saves things
  • Application [SerlvetContext] save things
  • config 【SerlvetConfig】
  • out
  • page , no need to understand
  • exception
pageContext.setAttribute("name1","秦疆1号"); //保存的数据只在一个页面中有效
request.setAttribute("name2","秦疆2号"); //保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3","秦疆3号"); //保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","秦疆4号");  //保存的数据只在服务器中有效,从打开服务器到关闭服务器

request: The client sends a request to the server, and the generated data is useless for the user after reading it. For example: news, it is useless for the user after reading it!

session: The client sends a request to the server, and the generated data is still useful after the user finishes using it, such as a shopping cart;

application: The client sends a request to the server, and the generated data, once used up by one user, may be used by other users, such as: chat data;

8.6, JSP tags, JSTL tags, EL expressions

<!-- JSTL表达式的依赖 -->
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>
<!-- standard标签库 -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

EL expressions: ${ }

  • retrieve data
  • perform calculations
  • Get common objects for web development

JSP tags

<%--jsp:include--%>

<%--
http://localhost:8080/jsptag.jsp?name=kuangshen&age=12
--%>

<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="name" value="kuangshen"></jsp:param>
    <jsp:param name="age" value="12"></jsp:param>
</jsp:forward>

JSTL expressions

The use of the JSTL tag library is to make up for the lack of HTML tags; it customizes many tags that can be used by us, and the functions of the tags

Same as Java code!

formatting tags

SQL tags

XML tags

core tags (mastering part)

JSTL tag library usage steps

  • Import the corresponding taglib
  • use the method
  • The jstl package also needs to be introduced in Tomcat, otherwise an error will be reported: JSTL parsing error

cif

<head>
    <title>Title</title>
</head>
<body>


<h4>if测试</h4>

<hr>

<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:choose c:when

<body>

<%--定义一个变量score,值为85--%>
<c:set var="score" value="55"/>

<c:choose>
    <c:when test="${score>=90}">
        你的成绩为优秀
    </c:when>
    <c:when test="${score>=80}">
        你的成绩为一般
    </c:when>
    <c:when test="${score>=70}">
        你的成绩为良好
    </c:when>
    <c:when test="${score<=60}">
        你的成绩为不及格
    </c:when>
</c:choose>

</body>

c:forEach

<%

    ArrayList<String> people = new ArrayList<>();
    people.add(0,"张三");
    people.add(1,"李四");
    people.add(2,"王五");
    people.add(3,"赵六");
    people.add(4,"田六");
    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="1" >
    <c:out value="${people}"/> <br>
</c:forEach>

9、JavaBean

Entity class

JavaBean has a specific way of writing:

  • There must be a no-argument constructor
  • Property must be private
  • There must be a corresponding get/set method;

Generally used to map ORM with database fields;

ORM: Object Relational Mapping

  • table ---> class
  • field --> attribute
  • line record ----> object

people table

class People{
    private int id;
    private String name;
    private int id;
    private String address;
}

class A{
    new People(1,"秦疆1号",3,"西安");
    new People(2,"秦疆2号",3,"西安");
    new People(3,"秦疆3号",3,"西安");
}
  • filter
  • File Upload
  • email sending
  • JDBC review: how to use JDBC, JDBC crud, jdbc transaction

10. MVC three-tier architecture

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

10.1, the previous architecture

Users directly access the control layer, and the control layer can directly operate the database;

servlet--CRUD-->数据库
弊端:程序十分臃肿,不利于维护  
servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码

架构:没有什么是加一层解决不了的!
程序猿调用
↑
JDBC (实现该接口)
↑
Mysql Oracle SqlServer ....(不同厂商)

10.2, MVC three-tier architecture

Model

  • Business processing: business logic (Service)
  • Data Persistence Layer: CRUD (Dao - Data Persistence Object)

View

  • display data
  • Provide a link to initiate a Servlet request (a, form, img...)

Controller (Servlet)

  • Receive user's request: (req: request parameters, Session information...)
  • Hand over the corresponding code to the business layer
  • Control view jump
Login ---> Receive the user's login request ---> Process the user's request (obtain the user's login parameters, username, password) ----> Hand over to the business layer to process the login business (judging whether the user name and password are correct: transaction ) ---> Dao layer query user name and password are correct --> database

11. Filter (emphasis)

For example, the Shiro security framework technology is implemented with Filter

Filter: filter, used to filter the data of the website;

  • Dealing with Chinese garbled characters
  • Login authentication….

(For example, if it is used to filter swearing words on the Internet, I *** myself 0-0)

Filter development steps:

1. Guide package

2. Write the filter

1. Do not make mistakes in importing packages (note)

Implement the Filter interface and rewrite the corresponding method

 public class CharacterEncodingFilter implements Filter {
      
          //初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现!
          public void init(FilterConfig filterConfig) throws ServletException {
              System.out.println("CharacterEncodingFilter初始化");
          }
      
          //Chain : 链
          /*
          1. 过滤中的所有代码,在过滤特定请求的时候都会执行
          2. 必须要让过滤器继续同行
              chain.doFilter(request,response);
           */
          public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
              request.setCharacterEncoding("utf-8");
              response.setCharacterEncoding("utf-8");
              response.setContentType("text/html;charset=UTF-8");
      
              System.out.println("CharacterEncodingFilter执行前....");
              chain.doFilter(request,response); //让我们的请求继续走,如果不写,程序到这里就被拦截停止!
              System.out.println("CharacterEncodingFilter执行后....");
          }
      
          //销毁:web服务器关闭的时候,过滤器会销毁
          public void destroy() {
              System.out.println("CharacterEncodingFilter销毁");
          }
      }

3. Configure Filter in web.xml

  <filter>
       <filter-name>CharacterEncodingFilter</filter-name>
       <filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
   </filter>
   <filter-mapping>
       <filter-name>CharacterEncodingFilter</filter-name>
       <!--只要是 /servlet的任何请求,会经过这个过滤器-->
       <url-pattern>/servlet/*</url-pattern>
       <!--<url-pattern>/*</url-pattern>-->
       <!-- 别偷懒写个 /* -->
   </filter-mapping>

12. Listener

Implement a listener interface; (there are n kinds of listeners)

1. Write a listener

Implementing the listener's interface...

Dependent jar packages

//统计网站在线人数 : 统计session
public class OnlineCountListener implements HttpSessionListener {

    //创建session监听: 看你的一举一动
    //一旦创建Session就会触发一次这个事件!
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();

        System.out.println(se.getSession().getId());

        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);

    }

    //销毁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);

    }


    /*
    Session销毁:
    1. 手动销毁  getSession().invalidate();
    2. 自动销毁
     */
}

2. Register the listener in web.xml

<!--注册监听器-->
<listener>
    <listener-class>com.kuang.listener.OnlineCountListener</listener-class>
</listener>

3. Use it according to the situation!

13. Common applications of filters and listeners

Listener: often 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) {
                super.windowClosing(e);
            }
        });

    }
}

The user can only enter the home page after logging in! After the user logs out, he cannot enter the home page!

1. After the user logs in, put the user's data into the Sesison

2. When entering the homepage, it is necessary to determine whether the user has logged in; requirement: implement in the 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);

14、JDBC

What is JDBC: Java connects to the database!

The support of the jar package is required:

  • java.sql
  • javax.sql
  • mysql-conneter-java... connection driver (must be imported)

Experimental environment construction

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

<!--mysql的驱动-->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    </dependency>

Connect to the database in IDEA:

JDBC fixation steps:

1. Load the driver

2. Connect to the database, representing the database

3. Send SQL object Statement to the database: CRUD

4. Write SQL (different SQL according to business)

5. Execute SQL

6. Close the connection (open first, then close)

public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解决中文乱码
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.向数据库发送SQL的对象Statement,PreparedStatement : CRUD
        Statement statement = connection.createStatement();

        //4.编写SQL
        String sql = "select * from users";

        //5.执行查询SQL,返回一个 ResultSet  : 结果集
        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();
    }
}

precompiled SQL

   public class TestJDBC2 {
    public static void main(String[] args) throws Exception {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解决中文乱码
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.编写SQL
        String sql = "insert into  users(id, name, password, email, birthday) values (?,?,?,?,?);";

        //4.预编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1,2);//给第一个占位符? 的值赋值为1;
        preparedStatement.setString(2,"狂神说Java");//给第二个占位符? 的值赋值为狂神说Java;
        preparedStatement.setString(3,"123456");//给第三个占位符? 的值赋值为123456;
        preparedStatement.setString(4,"[email protected]");//给第四个占位符? 的值赋值为1;
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第五个占位符? 的值赋值为new Date(new java.util.Date().getTime());

        //5.执行SQL
        int i = preparedStatement.executeUpdate();

        if (i>0){
            System.out.println("插入成功@");
        }

        //6.关闭连接,释放资源(一定要做) 先开后关
        preparedStatement.close();
        connection.close();
    }
}

affairs

Either all succeed, or both fail!

ACID principles: to ensure data security.

Open transaction 
Transaction commit() 
Transaction rollback rollback() 
Close transaction 

Transfer: 
A:1000 
B:1000 

A(900) --100--> B(1100)

Junit unit test

rely

<!--单元测试-->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

easy to use

The @Test annotation is only valid on the method, as long as the method with this annotation is added, it can be run directly!

@Test
public void test(){
    System.out.println("Hello");
}

Red on failure:

build an environment

CREATE TABLE account(
  id INT PRIMARY KEY AUTO_INCREMENT,
  `name` VARCHAR(40),
  money FLOAT
);

INSERT INTO account(`name`,money) VALUES('A',1000);
INSERT INTO account(`name`,money) VALUES('B',1000);
INSERT INTO account(`name`,money) VALUES('C',1000);
@Test
public void test() {
    //配置信息
    //useUnicode=true&characterEncoding=utf-8 解决中文乱码
    String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
    String username = "root";
    String password = "123456";
    
    Connection connection = null;
    
    //1.加载驱动
    try {
        Class.forName("com.mysql.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();//以上两条SQL都执行成功了,就提交事务!
        System.out.println("success");
    } catch (Exception e) {
        try {
            //如果出现异常,就通知数据库回滚事务
            connection.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }finally {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

15. SMBMS (Supermarket Management Project)

30~37 episodes of SMBMS project experiments

Bilibili Kuangshen said-Eclipse-SMBMS project experiment

https://blog.csdn.net/bell_love/article/details/106157413

Guess you like

Origin blog.csdn.net/qq_45220508/article/details/123563767