[toc]

JavaWeb

Static Web resources (such as HTML pages) : The data in a Web page for people to browse is always the same.

Dynamic Web resources: The data in a Web page for people to browse is generated by the program, and the content of the Web page is different at different points in time.

Static Web resource development techniques: HTML, CSS, JavaScript.

Dynamic Web resource development technology: JSP/Servlet, ASP, PHP, etc. In Java, dynamic Web resource development techniques are collectively known as the Java Web.

The Web server

Technical advice

ASP: Microsoft, the earliest domestic popular is ASP, embedded in THE HTML VB script, ASP+COM, high maintenance costs.

PHP: fast development, powerful, cross-platform, simple code, but can’t handle heavy traffic (limitations).

JSP/Servlet: SUN’s B/S architecture, based on the Java language, can carry three high problems (high concurrency, high availability, high performance).

B/S: browser and server; C/S: client and server.

The Web server

The server is used to process some requests from the user, and gives the user some data in response.

IIS: Microsoft, mainly used in ASP, Windows built-in server.

* * Tomcat: **Tomcat is a core project of the Apache Software Foundation’s Jakarta project. The latest Servlet and JSP specifications are always present in Tomcat. Tomcat 5 supports the latest Servlet 2.4 and JSP 2.0 specifications. Because of its advanced technology, stable performance, and free, Tomcat is deeply loved by Java enthusiasts and recognized by some software developers, and has become a popular Web application server.

Tomcat server is a free open source Web application server, belongs to lightweight application server, in small and medium-sized systems and concurrent access users are not many occasions is widely used, is the first choice for developing and debugging JSP programs. For a JavWeb beginner, is the best choice.

Tomcat actually runs JSP pages and servlets.

Tomcat

Install Tomcat: Download the Tomcat package from the official website (tomcat.apache.org/) and decompress it to the specified directory.

Bat in the bin directory to start the startup, and enter localhost:8080 in the web address box.

How the site is accessed:

  • Enter the user name and press Enter
  • Check the local C:\Windows\System32\drivers\etc\hosts configuration file for this domain name mapping
    • If yes, return the corresponding IP address directly
    • If you don’t find one, look for it on the DNS server. If you find one, return

Http

Http (Hypertext Transfer Protocol) : Http is a simple request-response protocol that typically runs on top of TCP. (Default port: 80)

Https: 443

  • Http1.0: A client can connect to a Web server and only get one Web resource, disconnecting.
  • Http1.1: A client can connect to a Web server and obtain multiple Web resources.

The Http request

  • Client —- Sends requests to —- server

Take Baidu as an example:

Request URL: https://www.baidu.com/ request an addressRequest Method: GET Request Method Status Code:200Remote Address:180.10149.11.:443Remote address Referrer Policy: no-referrer-when- retractedCopy the code

The Http response

  • Server —- Sends requests to —- client

Baidu’s response:

Cache-Control: privateCache control Connection: keep-alive Content-Encoding: gzip Encoding Content-Type: text/ HTML; charset=utf-8typeCopy the code

Request method:

Get: A request can carry a small number of parameters with a limited size. The parameters are displayed in the browser address bar, which is insecure but efficient.

Post: There is no limit on the size of the parameters that can be carried by the request. The content of the parameters will not be displayed in the browser address bar, which is secure but inefficient.

Response status code:

200: The request response succeeded

3** : Requests redirection

404: Resource not found

500: server code error, 502: gateway error

Maven

Maven: Project architecture management tool that automatically imports JAR packages (convention > configuration).

After downloading Maven, decompress it, configure environment variables, set the path of the bin directory to path, enter MVN -version in CMD, and check whether the configuration is successful

Configure the local repository under Setting in the conf directory

D: \ Environments \ apache maven – 3.6.3 \ maven repo

In conf directory under the setting to configure ali cloud mirror

<! Maven </id> <mirrorOf> Central </mirrorOf> <name> Aliyun </name> <url>https://maven.aliyun.com/repository/public/</url> </mirror>Copy the code

pom.xml

Pom.xml: The core configuration file for Maven

Since the maven convention is larger than the configuration, the configuration file we write later may not be exported or not take effect, so we need to configure resouce under maven configuration.

Servlet

Servlet is a technology for sun Company to develop dynamic Web. Sun company provides an interface called servlet in THE API. If you need to develop a servlet program, you need to write a class to realize the servlet interface, and then deploy the developed Java class to the Web server.

HelloServlet

Sun has two default implementation classes for the Servlet interface: HttpServlet and GenericServlet

  1. Create a Maven project, delete the SRC project, and then create a new Model. The empty project is maven’s main project.

  2. Maven parent-child Project:

There will be in the parent project

<modules>
    <module>servlet-01</module>
</modules>
Copy the code

Subprojects have

 <parent>
        <artifactId>javaweb-02-servlet</artifactId>
        <groupId>com.zr</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
Copy the code
  1. Maven environment optimization: Update web.xml to the latest to complete Maven’s architecture.

  2. Write a common class to implement the Servlet interface, inherit HttpServlet.

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //ServletOutputStream outputStream = resp.getOutputStream();
        PrintWriter writer = resp.getWriter();  / / response flow
        writer.println("Hello Servlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp); }}Copy the code
  1. Write a Servlet mapping: We are writing a Java program, but we need to access it through a browser, and the browser connects to the Web server, so we need to register our Servlet with the Web server and give it a path that the browser can access.
<! - the registration Servlet -- -- >
<servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.zr.servlet.HelloServlet</servlet-class>
</servlet>
<! --Servlet request path -->
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>
Copy the code
  1. Configure Tomcat
  2. Start the test

The Servlet principle

A Servlet is invoked by a Web server. Upon receiving the request, the Web server:

Mapping

  1. A Servlet can specify a mapping path

    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    Copy the code
  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>
    Copy the code
  3. A Servlet can specify a generic mapping path

    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello/*</url-pattern>
    </servlet-mapping>
    
    Copy the code
  4. The default request

    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/ *</url-pattern>
    </servlet-mapping>
    Copy the code
  5. A Servlet can specify suffix or prefix mapping paths

    <! --* Can't add any mapped path -->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>*.zzr</url-pattern>
    </servlet-mapping>
    Copy the code

Priority issues:

The default mapping path is specified, which has the highest priority. If it cannot be found, the request will be processed by default.

Handling 404 pages

<! - $404 - >
<servlet>
    <servlet-name>error</servlet-name>
    <servlet-class>com.zr.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>error</servlet-name>
    <url-pattern>/ *</url-pattern>
</servlet-mapping>
Copy the code

ServletContext

When the Web container is started, it creates a ServletContext object for each Web application, which represents the current Web application.

  • Shared data

    The data I save in one Servle is available in the other

    public class HelloServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("hello");
            //this.getInitParameter(); Initialization parameter
            //this.getServletConfig(); The Servlet configuration
            //this.getServletContext(); The Servlet context
    
            ServletContext context = this.getServletContext();
            String username = "Week";
            context.setAttribute("username",username);// Save a data in a ServletContext}}Copy the code
    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.setCharacterEncoding("utf-8");
            resp.setContentType("text/html");
            resp.getWriter().println("Name:"+username);
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}}Copy the code
    <servlet>
            <servlet-name>hello</servlet-name>
            <servlet-class>com.zr.servlet.HelloServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
    <servlet>
        <servlet-name>get</servlet-name>
        <servlet-class>com.zr.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>get</servlet-name>
        <url-pattern>/get</url-pattern>
    </servlet-mapping>
    Copy the code

    Test access results

  • Gets initialization parameters

    <! -- Set a web application initialization parameter -->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybaits</param-value>
    </context-param>
    
    <servlet>
            <servlet-name>gp</servlet-name>
            <servlet-class>com.zr.servlet.ServletDemo03</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>gp</servlet-name>
            <url-pattern>/gp</url-pattern>
        </servlet-mapping>
    Copy the code
    public class ServletDemo03 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext context = this.getServletContext();
            String url = context.getInitParameter("url");
            resp.getWriter().println(url);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp); }}Copy the code
  • Forward requests

    public class ServletDemo04 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext context = this.getServletContext();
            RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");// Forward the request path
            requestDispatcher.forward(req,resp);/ / forwarding
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp); }}Copy the code
    <servlet>
        <servlet-name>sd4</servlet-name>
        <servlet-class>com.zr.servlet.ServletDemo04</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>sd4</servlet-name>
        <url-pattern>/sd4</url-pattern>
    </servlet-mapping>
    Copy the code
  • Reading resource files

    properties

    • Create propreties in the Java directory (resources need to be configured under POM.xml)
    • Create new Properties under the Resources directory

    The discovery is packaged into the target class directory, which we call the classpath.

    public class ServletDemo05 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
            Properties properties = new Properties();
            properties.load(is);
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");
            resp.getWriter().println("username:"+username);
            resp.getWriter().println("password:"+password);
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
    <servlet>
        <servlet-name>sd5</servlet-name>
        <servlet-class>com.zr.servlet.ServletDemo05</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>sd5</servlet-name>
        <url-pattern>/sd5</url-pattern>
    </servlet-mapping>
    Copy the code
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>**/*.properties</exclude>
                    <exclude>**/*.xml</exclude>
                </excludes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
    Copy the code
    / / file db.properties
    username=root
    password=123456
    Copy the code

HttpServletResponse

The Web server receives an HTTP request from the client, and for this request creates an HttpServletRequest object representing the request, representing an HttpServletResponse.

  • If you want to get the argument from the client: HttpServletRequest
  • If you want to give the client response some information: HttpServletResponse

Simple classification

The method responsible for sending data to the browser

ServletOutputStream getOutputStream(a) throws IOException;

PrintWriter getWriter(a) throws IOException;
Copy the code

The method responsible for sending the response header 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);
Copy the code

The status code of the response

int SC_OK = 200; .int SC_MULTIPLE_CHOICES = 300;
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_INTERNAL_SERVER_ERROR = 500;
int SC_BAD_GATEWAY = 502;
Copy the code

The download file

  1. Output a message to the browser

  2. The download file

    1. Gets the path to the downloaded file
    2. Download file name
    3. Let the browser support downloading what we need
    4. Gets the input stream for the downloaded file
    5. Creating a buffer
    6. Get the OutputStream object
    7. Writes the FileOutputStream to the buffer buffer
    8. Outputs objects in the OutputStream buffer to the client
    public class FileServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1. Obtain the downloaded file path
            String realPath = "D:\\IDEACode\\javaweb-02-servlet\\response\\src\\main\\resources\\1.PNG";
            System.out.println("Download file path:"+realPath);
            //2. File name of the download
            String fileName = realPath.substring(realPath.lastIndexOf("\ \") + 1);
            //3. Let the browser support downloading what we need
            resp.setHeader("Content-Disposition"."attachment; filename="+fileName);
            //4. Get the input stream for the downloaded file
            FileInputStream in = new FileInputStream(realPath);
            //5. Create buffer
            int len = 0;
            byte[] buffer = new byte[1024];
            //6. Get the OutputStream object
            ServletOutputStream out = resp.getOutputStream();
            //7. Write the FileOutputStream to the buffer buffer. Output objects in the OutputStream buffer to the client
            while ((len=in.read(buffer))>0){
                out.write(buffer,0,len);
    
            }
            in.close();
            out.close();
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code

Verification code function

How to generate captcha:

  • The front end
  • Back end: Need to use Java image class, generate a picture
public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Refresh the browser every 5 seconds
        resp.setHeader("refresh"."5");
        // Create the image
        BufferedImage image = new BufferedImage(300.60,BufferedImage.TYPE_INT_RGB);
        // get the image
        Graphics g = image.getGraphics(); / / pen
        // Set the background color of the image
        g.setColor(Color.green);
        g.fillRect(0.0.300.60);
        // Write data to the image
        g.setColor(Color.magenta);
        g.setFont(new Font(null,Font.BOLD,70));
        g.drawString(makeNum(),0.60);
        // The browser opens as an image
        resp.setContentType("image/png");
        // There is a cache on the site. Don't let the browser cache
        resp.setDateHeader("expires", -1);
        resp.setHeader("Cache-Control"."no-cache");
        resp.setHeader("Pragma"."no-cache");

        // Display the image
        boolean write = ImageIO.write(image,"jpg",resp.getOutputStream());

    }
    // Generate a random number
    private String makeNum(a){
        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); }}Copy the code
<! - the registration Servlet -- -- >
<servlet>
    <servlet-name>image</servlet-name>
    <servlet-class>com.zr.servlet.ImageServlet</servlet-class>
</servlet>
<! --Servlet request path -->
<servlet-mapping>
    <servlet-name>image</servlet-name>
    <url-pattern>/image</url-pattern>
</servlet-mapping>
Copy the code

Implement redirection

void sendRedirect(String var1) throws IOException;/ / redirection
Copy the code
public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       /* resp.setHeader("Location","/r/image"); resp.setStatus(302); * /
       
        resp.sendRedirect("/r/image");
    }

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

Configure the web.xml test

The difference between redirection and forwarding:

Similarities: All pages will jump

Difference:

  • When requesting a forward, the URL does not change 307
  • The URL address bar will change when redirected

index.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java" %><html>
<body>
<h2>Hello World!</h2><%-- The submitted path needs to find the path to the current project --%><form action="${pageContext.request.contextPath}/login" method="post">User name:<input type="text" name="username"><br>Password:<input type="password" name="password"><br>
    <input type="submit">

</form>
</body>
</html>
Copy the code

success.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java" %><html>
<head>
    <title>Title</title>
</head>
<body>
<h1>success</h1>
</body>
</html>
Copy the code
public class RequestTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("Enter this request.");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username:"+username);
        System.out.println("password:"+password);
        resp.sendRedirect("/r/success.jsp");
        
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
<! - the registration Servlet -- -- >
<servlet>
    <servlet-name>test</servlet-name>
    <servlet-class>com.zr.servlet.RequestTest</servlet-class>
</servlet>
<! --Servlet request path -->
<servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>
Copy the code

HttpServletRequest

HttpServletRequest represents the request from the client. The user accesses the server through HTTP protocol. All information in the HTTP request is encapsulated in HttpServletRequest.

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

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

        // Request forwarding
        // The/here represents the current Web application
        req.getRequestDispatcher("/success.jsp").forward(req,resp); }}Copy the code

index.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java" %><html>
<head>
    <title>The login</title>
</head>
<body>
<h1>The login</h1>
<div style="text-align: center">
    <form action="${pageContext.request.contextPath}/login" method="post">User name:<input type="text" name="username"><br>Password:<input type="password" name="password"><br>Hobbies:<input type="checkbox" name="hobbys" value="Sing">Sing a song<input type="checkbox" name="hobbys" value="Girl">The girl<input type="checkbox" name="hobbys" value="Write">write<input type="checkbox" name="hobbys" value="Code">code<br>
        <input type="submit">
    </form>

</div>
</body>
</html>
Copy the code

success.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java" %><html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Login successful</h1>
</body>
</html>
Copy the code

web.xml

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.zr.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>
Copy the code

Cookie, Session

cookie

  • Client technology (response, request)

session

  • Server technology, we can store the user’s session information, we can put information or data in the session

Common application: After logging in to a website once, you can directly access it next time.

Cookie

Retrieve cookie information from the request

The server responds to the client with a cookie

// Save the user's last access time
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Resolve Chinese garbled characters
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");

        PrintWriter out= resp.getWriter();
        // Cookie, which the server obtains from the client
        Cookie[] cookies = req.getCookies();// Return an array. There may be multiple cookies
        // Check whether the cookie exists
        if(cookies! =null) {// If yes
            out.write("The last time you visited was:");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                // Get the name of the cookie
                if (cookie.getName().equals("lastlogintime")) {// Get the value in the cookie

                    long lastlogintime = Long.parseLong(cookie.getValue());
                    Date date = newDate(lastlogintime); out.write(date.toLocaleString()); }}}else{
            out.write("This is your first visit to this site!");
        }
        // The server sends a cookie to the client
        Cookie cookie = new Cookie("lastlogintime", System.currentTimeMillis()+"");
        // Valid for 1 day
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }

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

web.xml

<servlet>
    <servlet-name>CookieDemo01</servlet-name>
    <servlet-class>com.zr.servlet.CookieDemo01</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>CookieDemo01</servlet-name>
    <url-pattern>/c1</url-pattern>
</servlet-mapping>
Copy the code

Cookie: generally, it is saved in the local user directory AppData.

  • A cookie can only hold one piece of information
  • A Web site can send multiple cookies to the browser, up to 20
  • Cookie size is limited to 4KB
  • The maximum number of cookie browsers is 300

Delete the cookie

  • If you do not set the validity period, close the browser
  • Set the validity period to 0

Session

The session:

  • The server creates a Session object for each user (browser)

  • A session monopolizes a browser and exists as long as the browser is not closed

  • After the user logs in, the whole website can be accessed, –> save the user’s information

The difference between session and cookie:

  • Cookie is to write the user’s data to the user’s browser, the browser saves (can save more than one)
  • Session is to write data to the user’s exclusive session, and the server saves (saves important information and reduces the waste of resources).
  • The Session object is created by the server

Session saves data

package com.zr.pojo;

public class Person {
    private String name;
    private int age;

    public Person(a) {}public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString(a) {
        return "Person{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                '} '; }}Copy the code
public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Resolve Chinese garbled characters
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        / / get the session
        HttpSession session = req.getSession();

        // Save something to session
        session.setAttribute("name".new Person("Week".1));
        // Get the session ID
        String id = session.getId();
        // Check whether the session is newly created
        if(session.isNew()){
            resp.getWriter().write(Session created successfully, ID:+ id);
        }else {
            resp.getWriter().write("Session already exists, ID:"+ id); }}@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
public class SessionDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Resolve Chinese garbled characters
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        // Get session data
        HttpSession session = req.getSession();

        Person person = (Person) session.getAttribute("name");
        System.out.println(person);

    }

    @Overridejava
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
<servlet>
    <servlet-name>SessionDemo01</servlet-name>
    <servlet-class>com.zr.servlet.SessionDemo01</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SessionDemo01</servlet-name>
    <url-pattern>/s1</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>SessionDemo02</servlet-name>
    <servlet-class>com.zr.servlet.SessionDemo02</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SessionDemo02</servlet-name>
    <url-pattern>/s2</url-pattern>
</servlet-mapping>
Copy the code

Session manual logout

public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("name");
        // Manually cancel the session
        session.invalidate();
    }

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

Session logout Automatically

<! -- Set session logout time -->
<session-config>
    <! -- Automatic expiration after 1 minute -->
    <session-timeout>1</session-timeout>
</session-config>
Copy the code

JSP

What is a JSP

JSP: Java Server Pages, Java server-side interface, like servlets, for the development of dynamic Web technology.

The characteristics of

  • Writing JSP is like writing HTML
  • The difference between
    • HTML only provides static data to the user
    • JSP pages can embed Java code to provide dynamic data to the user

JSP principle

Inside the server, tomcat has a work directory where JSPS are eventually converted into Java classes, which are essentially servlets.

Index_jsp. Java source code

/ / initialization
 public void _jspInit(a) {}/ / destroy
  public void _jspDestroy(a) {}//jspService
  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
Copy the code

Determine the request

Some built-in objects

    final javax.servlet.jsp.PageContext pageContext; // Page context
    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 to the current page
	HttpServletRequest request  / / request
    HttpServletResponse respons  / / response


Copy the code

The added code in front of the output page

	  response.setContentType("text/html"); // Set the page type for the response
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null.true.8192.true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
Copy the code

The above objects can be used directly in a JSP

In a JSP page, Java code is printed as it is, and HTML code is converted to out.write(“…..”). );

JSP Basic Syntax

Any language has its own syntax. JSP, as an application of Java technology, has some of its own expanded syntax (understand). It supports all Java syntax.

JSP expressions

<%--JSP expression output time to the client --%> <%=new java.util.Date()%>
Copy the code

JSP script snippet

<%-- JSP script fragment --%> <%int sum=0;
  for (int i = 0; i < 100; i++) {
    sum+=i;
  }
  out.println("<h1>sum="+sum+"</h1>"); % >Copy the code

Re-implementation of script fragments

The < %int x=10; out.print(x); %> <p> This is a JSP document </p> <%int y=20; out.print(y); %> <%-- Embed HTML elements in your code --%> <%for (int i = 0; i < 5; i++) {
%>
  <h1>helloworld<%=i%></h1>
<%
  }
%>
Copy the code

JSP declaration

The < %!static {
    System.out.println("loding...");
  }
  private int globalvar=0;
  public void jspInit(a){
    System.out.println("Into the method."); } % >Copy the code

JSP declarations: are compiled into Java classes generated by JSPS. Others will be generated into jspServer methods.

JSP comments are not displayed in the client source code, HTML comments are displayed in the source code.

Customizing error pages

<error-page>
    <error-code>404</error-code>
    <location>/error/404.jsp</location>
</error-page>

<error-page>
    <error-code>500</error-code>
    <location>/error/500.jsp</location>
</error-page>
Copy the code
<%@ page contentType="text/html; charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
</head>
<body>
<img src="img/500.jpg" alt="500">
</body>
</html>
Copy the code

JSP directive

The < %@page% args... > < %@include file=""%> <%- will merge the pages into one -%> <%@include file="common/header.jsp"%> <h1> Body </h1> <%@include file="common/footer.jsp"%> <hr> <%-- JSP tag splicing page --%> < JSP :include page="common/header.jsp"/> <h1> Body </h1> < JSP :include page="common/footer.jsp"/>
Copy the code

Nine built-in objects

  • The PageContext save things
  • The Request to save things
  • Response
  • The Session to save things
  • Application [ServletContext] saves things
  • The config [ServletConfig]
  • out
  • page
  • exception

Four scopes

<%-- built-in object --%> <% pagecontext.setAttribute ("name1"."Week 1");// The saved data is only valid in one page
    request.setAttribute("name2"."Week 2");// The saved data is only valid in one request, which is carried by request forwarding
    session.setAttribute("name3"."Three weeks");// The saved data is only valid for one session, from opening the browser to closing the browser
    application.setAttribute("name4".Week of "4");// The saved data is valid in the server, open the server to close the server%> <%-- value via pageContext --%> <%// By way of finding
    String name1 = (String) pageContext.findAttribute("name1");
    String name2 = (String) pageContext.findAttribute("name2");
    String name3 = (String) pageContext.findAttribute("name3");
    String name4 = (String) pageContext.findAttribute("name4");
    String name5 = (String) pageContext.findAttribute("name5");/ / does not exist${}--%> <h1> </h1> <h3>${name1}</h3> <h3>${name2}</h3> <h3>${name3}</h3> <h3>${name4}</h3> <h3>${name5}</h3> <hr> <%=name5%>Copy the code

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

Session: The client sends data to the server, generating data that the user will use later, such as a shopping cart

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

JSP tags, JSTL tags, EL expressions

 <! -- JSTL expression dependencies -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>

        <! -- Standard tag library -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
Copy the code

${}

  • To get the data
  • Perform operation
  • Get common objects for Web development

JSP tags:

< % - the JSP: include -- % > < % - carry forward time parameters - % > < JSP: forward page ="/jsptag2.jsp">
    <jsp:param name="name" value="zr"/>
    <jsp:param name="age" value="22"/>

</jsp:forward>
Copy the code

JSTL expression

The JSTL tag library is used to make up for the deficiency of HTML tags. It has many custom tags that can be used by us, and the function of the tag is the same as Java code.

Core tag (master), format tag, SQL tag, XML tag

<%-- Introduces the JSTL core tag library --%> <% @taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"% >Copy the code

JSTL label usage procedure

  • Import the corresponding taglib
  • Use one of the methods
  • The JSTL package must be imported into Tomcat; otherwise, a JSTL parsing error will be reported

c:if

<body>
<h1>ifTest </h1> <hr> <form action="coreif.jsp" method="get"${param. parameter name} --%> <input type="text" name="username" value="${param.username}"/>
    <input type="submit" name="Login"> </form> <%-- if the user is an administrator, the login is successful --%> <c:if test="${param.username=='admin'}" var="isadmin">
    <c:out value="The caretaker welcomes you!"/>
</c:if>
<c:out value="${isadmin}"/>
</body>
Copy the code

c:choose

<body> <%-- define a variable score value as88--%>
<c:set var="score" value="88"/>
<c:choose>
    <c:when test="${score>=90}"Your grades are excellent! </c:when> <c:when test="${score>=80}"> your grades are good! </c:when> <c:when test="${score>=60}""> < p style =" max-width: 100%; clear: both; </c:when> <c:when test="${score<=60}"> < p style = "max-width: 100%; clear: both; </c:when> </c:choose> </body>Copy the code

c:forEach

<body>
<%
    ArrayList<String> people = new ArrayList<String>();
    people.add(0."Zhang");
    people.add(1."Bill");
    people.add(2."Fifty");
    people.add(3."Daisy");
    people.add(4."Cropland 7");
    request.setAttribute("list",people); - % > < %varItems traversal the object traversed each time --%> <c:forEachvar="people" items="${list}">
    <c:out value="${people}"/ > < br > < / c: forEach > < hr > < % - start end step - % > < c: forEachvar="people" items="${list}" begin="2" end="4" step="2">
    <c:out value="${people}"/><br>
</c:forEach>

</body>
Copy the code

JavaBean

Entity class

Javabeans are written in a specific way:

  • There must be a no-parameter construct
  • Attributes must be privatized
  • There must be a corresponding get/set method

General used and database field mapping ORM;

ORM object relational mapping

  • Table – > class
  • Field > Properties
  • Line record –> object

People watch

id name age address
1 Week 1 18 wuhan
2 Week 2 22 Guangzhou
3 Week 3 100 foshan

Create the Java entity class after the database fields are created

package com.zr.pojo;
// Entity classes generally correspond to table structures in a database
public class People {
    private int id;
    private String name;
    private int age;
    private String address;

    public People(a) {}public People(int id, String name, int age, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public int getId(a) {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress(a) {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString(a) {
        return "People{" +
                "id=" + id +
                ", name='" + name + '\' ' +
                ", age=" + age +
                ", address='" + address + '\' ' +
                '} '; }}Copy the code
<%@ page import="com.zr.pojo.People" %><%--
  Created by IntelliJ IDEA.
  User: zr
  Date: 2020/10/11
  Time: 22:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
// People people = new People();
// people.setAddress();
// people.setId();
// people.setAge();
// people.setName();
 // This is equivalent to the following
%>
<jsp:useBean id="people" class="com.zr.pojo.People" scope="page"/>
<jsp:setProperty name="people" property="address" value="Wuhan"/>
<jsp:setProperty name="people" property="id" value="1"/>
<jsp:setProperty name="people" property="age" value="18"/>
<jsp:setProperty name="people" property="name" value="Chou"/> Name: < JSP :getProperty name="people" property="name"/> id: < JSP :getProperty name="people" property="id"/> Age: < JSP :getProperty name="people" property="age"/> Address: < JSP :getProperty name="people" property="address"/>
</body>
</html>
Copy the code

MVC three-tier architecture

MVC: Model, View, Controller

Model

  • Business processing, Business logic (Service)
  • Data Persistence Layer, CRUD (Dao)

View

  • Display data
  • Provide operations to initiate Servlet requests (a, form, img….)

The Controller (Servlet)

  • Receive the request, (REq: request parameters, session information…)
  • Hand over the corresponding code to the business layer
  • Controls the jump of the view
Login --> receive user login request --> process user request (get user login parameter username password) --> hand over business layer to process login business (judge whether username password is correct) -->Dao layer query user password is correct --> databaseCopy the code

The filter

9. A Filter used to Filter data from a website:

  • Handle Chinese garbled characters
  • Login verification…

Filter preparation: the first configuration Servlet, JSP dependency

Implement the Filter(Servlet) interface and override the corresponding method

public class CharacterEncodingFilter implements Filter {
    The web server is initialized as soon as it starts, waiting for the listener to appear
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter Initialization");
    }
    / / Chain: Chain
    /* 1, all code in the filter will execute 2 when filtering a specific request, and the filter must filter the peer 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; character=UTF-8");

        System.out.println("CharacterEncodingFilter before execution....");
        chain.doFilter(request,response);// Let our request continue to go if not written, the program is intercepted and stopped
        System.out.println("CharacterEncodingFilter after execution....");

    }
    // Destroy The filter is destroyed when the Web server is down
    public void destroy(a) {
        System.out.println("CharacterEncodingFilter destroyed"); }}Copy the code

The servlet displays garbled characters

public class ShowServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //resp.setCharacterEncoding("utf-8");
        //resp.setContentType("text/html");
        resp.getWriter().write(Hello world.);
    }

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

Configure web. XML

<servlet>
    <servlet-name>showServlet</servlet-name>
    <servlet-class>com.zr.servlet.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>CharacterEncoding</filter-name>
    <filter-class>com.zr.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharacterEncoding</filter-name>
    <! -- Any request for /servlet will pass through this filter -->
    <url-pattern>/servlet/*</url-pattern>
</filter-mapping>
Copy the code

The listener

Statistics website online number:

Implements a listener interface

// Count the number of online users. Count the number of sessions
public class OnlineCountListener implements HttpSessionListener {
    // Create Session listener
    // This event is emitted once a Session is created
    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);
    }
    // Destroy Session listeners
    // This event is emitted once a Session is destroyed
    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); }}Se.getsession ().invalidate(); 2. The 
      
        */ configuration in the XML is automatically destroyed
      
Copy the code

Display number of online users

<%@ page contentType="text/html; charset=UTF-8" language="java"< HTML > <head> <title>$title $</title> </head> <body> <h1"color: hotpink"> < % =this.getServletConfig().getServletContext().getAttribute("OnlineCount"</h1> </body> </ HTML >Copy the code

Configure web. XML

<! -- Register listener -->
    <listener>
        <listener-class>com.zr.listener.OnlineCountListener</listener-class>
    </listener>
Copy the code

Filters and listeners are common applications

Listeners are often used in GUI programming

GUI application

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame("Happy Mid-Autumn Festival!"); // Create a new form
        Panel panel = new Panel(null); / / panel
        frame.setLayout(null); // Sets the layout of the form
        frame.setBounds(300.300.500.500); / / coordinates
        frame.setBackground(new Color(0.0.255)); // Background color

        panel.setBounds(50.50.300.300);
        panel.setBackground(new Color(0.255.255));

        frame.add(panel);
        frame.setVisible(true);

        // Listen on events, listen on closed events
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0); }}); }}Copy the code

Users can access the home page only after login, but cannot access the home page after logout

1. After the user logs in, the user data is added to the session

2. When entering the home page, determine whether the user is logged in, requiring login.jsp to be implemented in the filter

Login.jsp (under web package)

<body> <h1> Login </h1> <form action=" /servlet/login" method="post">
    <input type="text" name="username">
    <input type="submit">
</form>
</body>
Copy the code

Success.jsp (web/sys package)

<body> <h1> Home </h1> <a href="/servlet/loginout"</a> </body>Copy the code

Error.jsp (under web package)

<body> <h1> error </h1> <h3> Username error </h3> <a href="/login.jsp"> Return to the login page </a> </body>Copy the code

Login

public class login extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get the parameters of the front-end request
        String username = req.getParameter("username");
        if (username.equals("admin")){
            req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else {
            resp.sendRedirect("/error.jsp"); }}@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code

LoginOut

public class LoginOut extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object user_session = req.getSession().getAttribute("USER_SESSION");
        if(user_session! =null){
            req.getSession().removeAttribute("USER_SESSION");
            resp.sendRedirect("/login.jsp");
        }else {
            resp.sendRedirect("/login.jsp"); }}@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code

SysFilter: filter

public class SysFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {}public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        filterChain.doFilter(request, response);

        if (req.getSession().getAttribute("USER_SESSION") = =null){
            resp.sendRedirect("/error.jsp"); }}public void destroy(a) {}}Copy the code

web.xml

<servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.zr.servlet.login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/servlet/login</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>loginOut</servlet-name>
        <servlet-class>com.zr.servlet.LoginOut</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>loginOut</servlet-name>
        <url-pattern>/servlet/loginout</url-pattern>
    </servlet-mapping>


    <filter>
        <filter-name>CharacterEncoding</filter-name>
        <filter-class>com.zr.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncoding</filter-name>
        <! -- Any request for /servlet will pass through this filter -->
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.zr.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <! -- Any request from /sys will pass through this filter -->
        <url-pattern>/sys/*</url-pattern>
    </filter-mapping>
Copy the code

JDBC

Connect to database using mysql-connector-java

public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // Configuration information
        String url = "jdbc:mysql://localhost:3306/jdbc? useUnicode=true&characterEncoding=utf8";
        String username = "root";
        String password = "123456";
        // Load the driver
        Class.forName("com.mysql.jdbc.Driver");
        // Connect to the database
        Connection connection = DriverManager.getConnection(url, username, password);
        // Send the SQL object to the database
        Statement statement = connection.createStatement();
        / / write SQL
        String sql = "select * from users";
        // Execute the query SQL and return a result set
        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"));
        }
        // Close the connectionrs.close(); statement.close(); connection.commit(); }}Copy the code

Precompiled SQL

public class TestJdbc2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // Configuration information
        String url = "jdbc:mysql://localhost:3306/jdbc? useUnicode=true&characterEncoding=utf8";
        String username = "root";
        String password = "123456";
        // Load the driver
        Class.forName("com.mysql.jdbc.Driver");
        // Connect to the database
        Connection connection = DriverManager.getConnection(url, username, password);
        // Send the SQL object to the database
        Statement statement = connection.createStatement();

        String sql = "insert into users(id,name,password,email,birthday) values(? ,? ,? ,? ,?) ";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1.4);
        preparedStatement.setString(2."Sunday");
        preparedStatement.setString(3."888888");
        preparedStatement.setString(4."[email protected]");
        preparedStatement.setString(5, String.valueOf(new Date(new java.util.Date().getTime())));
        int i = preparedStatement.executeUpdate();
        if (i>0){
            System.out.println("Insert successful");
        }
        // Close the connectionstatement.close(); connection.commit(); }}Copy the code

The transaction

It’s all or nothing!

ACID principle to ensure data security.

Open the transaction

Transaction commit commi ()

Rollback ()

Close the transaction

Junit unit tests

Rely on

<! --> <dependency> <groupId>junit</groupId> <artifactId> <version>4.12</version>
    <scope>test</scope>
</dependency>
Copy the code

Simple to use

The @test annotation is valid only for methods, and can be run as long as the method is annotated.

public class TestJdbc3 {

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

Transfer transactions (create account table, field ID, name, money), using unit tests

public class TestJdbc3 {

    @Test
    public void test(a) {
        // Configuration information
        String url = "jdbc:mysql://localhost:3306/jdbc? useUnicode=true&characterEncoding=utf8";
        String username = "root";
        String password = "123456";
        Connection connection=null;
        // Load the driver
        try {
            Class.forName("com.mysql.jdbc.Driver");
        // Connect to the database
        connection = DriverManager.getConnection(url, username, password);
        // Notify the database to start a transaction
        connection.setAutoCommit(false);
        String sql1 = "update account set money=money-100 where name='A'";
        connection.prepareStatement(sql1).executeUpdate();

        // make an error
        int i=1/0;

        String sql2 = "update account set money=money+100 where name='B'";
        connection.prepareStatement(sql2).executeUpdate();

        connection.commit();// Commit only after all the above SQL has been executed successfully
        System.out.println("Submission successful!");
        } catch (Exception e) {
            try {
                If an exception occurs, the transaction is rolled back
                connection.rollback();
                System.out.println("Transfer failed!");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                connection.close();
            } catch(SQLException throwables) { throwables.printStackTrace(); }}}}Copy the code