Java Web Learning Notes

Posted by phpjaco on Thu, 17 Feb 2022 22:25:42 +0100

JavaWeb

Basic concepts

preface

web development

  • web page
  • Static web
    • html, css
    • The data provided to everyone will never change
  • Dynamic web
    • The data provided to everyone will always change, and everyone will see different information at different times and places
    • Technology stack: Servlet / JSP, ASP, PHP

In Java, the technology of dynamic resource web development is collectively referred to as JavaWeb

web application

web application: a program that provides browser access

  • a.html, b.html... Multiple web resources, which can be accessed by the outside world and provide services to the outside world
  • Any page or resource that can be accessed exists on a computer
  • URL
  • These unified web resources will be placed in the same folder, web application - > Tomcat: server
  • A web application consists of many parts (static web, dynamic web)
    • html,css
    • jsp,servlet
    • java program
    • jar package
    • Configuration file (properties)

After the web application is written, if you want to provide access to the outside world, you need a server to manage it uniformly

Static web
  • *.htm,*. html these are web page suffixes. If these things always exist on the server, we can read them directly (through the network)

  • Disadvantages of static web

    • web pages cannot be updated dynamically. All users see the same page
    • Unable to interact with the database (data cannot be persisted and users cannot interact)
Dynamic web

The page will be displayed dynamically: the page display of the web varies from person to person

Disadvantages of dynamic web

  • There is an error in the dynamic web resources added to the server. The background program needs to be rewritten and republished

Advantages of dynamic web

  • web pages can be updated dynamically
  • Can interact with database (data persistence)

web server

Server is a passive operation, which is used to process some requests of users and give users some response information

IIS (Microsoft)
Tomcat

Tomcat

Install Tomcat

Tomcat official website: https://tomcat.apache.org/

to configure

The port number of startup can be configured

  1. Tomcat default port number: 8080
  2. MySQL: 3306
  3. http: 80
  4. https: 443
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

You can configure the name of the host

  1. The default host name is localhost (127.0.0.1)
  2. The default site application location is webapps
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

Difficult interview question: please talk about how the website is accessed?

  1. Enter a domain name; 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 are web programs we need to access, which can be accessed directly
    	127.0.0.1       localhost
    
    1. No: go to the DNS server (domain names all over the world are managed here). If you find them, return them. If you can't find them, return them. If you can't find them, you can't find them
Publish a web site
  • Put the website written by yourself under the specified web apps folder in the server (Tomcat), and you can access it

The website should have the following structure:

-- webapps: Tomcat Server web catalogue
	- ROOT
	- JarvisStudy: Directory name of the web site
		- WEB-INF
			- classes: java program
			- lib: web Application dependent jar package
			- web.xml: Site profile
		- index.html Default home page
		- static
			- css
				- style.css
			- js
			- img
		- ...

Http

What is Http

Hypertext Transfer Protocol (HTTP) is a simple request response protocol, which usually runs on TCP.

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

Https: safe (s)

  • Default port: 443
Two times
  • http1.0
    • HTTP/1.0: after the client connects with the web server, only one web resource can be obtained. Disconnect
  • http2.0
    • HTTP/1.1: after the client connects with the web server, it can obtain multiple web resources
request
  • Client - send request - server

Baidu

Request URL: https://www.baidu.com/ 					 Request address
Request Method: GET									get method / post method
Status Code: 200 OK									Status code
Remote Address: 180.101.49.11:443					Remote address
Accept:text/html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6	language
Cache-Control: max-age=0
Connection: keep-alive
  • Request line
    • Request method in request line: GET
    • Request method: Get / Post
      • get: the request can carry fewer parameters, and the size is limited. The data content will be displayed in the URL address bar of the browser, which is unsafe but efficient
      • post: there is no limit on the parameters carried in the request, and there is no limit on the size. The data content will not be displayed in the URL address bar of the browser. It is safe but inefficient
  • Message header
Accept				Tell the browser what data types it supports
Accept-Encoding		Which encoding format is supported: GBK,UTF-8,GB2312
Accept-Language		Tell the browser its locale
Cache-Control		Cache control
Connection			Tell the browser whether to disconnect or remain connected when the request is completed
response
  • Server response client

Baidu

Cache-Control: private					Cache control
Connection: keep-alive					connect
Content-Encoding: gzip					code
Content-Type: text/html;charset=utf-8	type
  • Responder
Accept				Tell the browser what data types it supports
Accept-Encoding		Which encoding format is supported: GBK,UTF-8,GB2312
Accept-Language		Tell the browser its locale
Cache-Control		Cache control
Connection			Tell the browser whether to disconnect or remain connected when the request is completed
Refresh				Tell the client how often to refresh
Location			Repositioning web pages
  • Response status code
    • 200 request response successful
    • 3xx request redirection (redirection: you go back to the new location I gave you)
    • 4xx resource not found (resource does not exist) (404)
    • 5xx server code error (502 gateway error)

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

Maven

Maven's core idea: Convention is greater than configuration
Maven will specify how to write Java code, which must be followed

Servlet

Introduction to Servlet
  • Servlet is a technology for sun company to develop dynamic web
  • sun provides an interface called Servlet in these API s. If you want to develop a Servlet program, you only need two steps:
    • Write a class to implement the Servlet interface
    • Deploy the developed Java classes to the web server
  • The Java program that implements the Servlet interface is called Servlet
HelloServlet
  1. Component is an ordinary Maven project. Delete the src directory and then create a Module in it. This empty project is the Maven parent project
  2. Maven environment optimization
  3. Write a Servlet program
    1. Write a common class
    2. Implement Servlet interface (HttpServlet)
package com.jarvis.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {

    // Because get or post are only different ways of request implementation, they can call each other, and the business logic is the same

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // ServletOutputStream outputStream = resp.getOutputStream();
        PrintWriter writer = resp.getWriter();// Response flow
        writer.print("Hello, Servlet");
    }

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

  1. Write the mapping of Servlet

Why do I need mapping? We write a java program, but we need to access it through the browser, and the browser needs to connect to the web server, so we need to register the Servlet written in the web service and give it a path that the browser can access

	<!--register Servlet-->
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.jarvis.servlet.HelloServlet</servlet-class>
    </servlet>
    <!--Servlet Request path for-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
  1. Configure Tomcat
  2. Start test
Servlet principle

Servlet is called by the web server, which receives the browser request

Mapping
  1. A Servlet can specify a path
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
  1. A Servlet can specify multiple mapping paths
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello1</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>
  1. A Servlet can specify a common mapping path
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello/*</url-pattern>
    </servlet-mapping>
  1. Default request path
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
  1. Specify suffix or prefix
	<!--* The path cannot be preceded by a project mapping-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>*.jarvis</url-pattern>
    </servlet-mapping>
  1. Priority issues

The inherent mapping path is specified with the highest priority. If it cannot be found, the default processing request will be found

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

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

  1. Shared 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() initialization parameter
//        this. Getservletconfig() servlet configuration
//        this. Getservletcontext() servlet context

        ServletContext servletContext = this.getServletContext();
        String username = "Jarvis";
        servletContext.setAttribute("username", username);// Save a data in ServletContext

        
    }
}
public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        String username = (String) servletContext.getAttribute("username");

        resp.setContentType("text/html;charset=utf-8");

        resp.getWriter().write("name:" + username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.jarvis.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>getContext</servlet-name>
        <servlet-class>com.jarvis.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getContext</servlet-name>
        <url-pattern>/getContext</url-pattern>
    </servlet-mapping>
  1. Get initialization parameters
    <!--Configure some web Application initialization parameters-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
public class ServletDemo03 extends HelloServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();

        String url = servletContext.getInitParameter("url");
        resp.getWriter().print(url);
    }

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

The forwarding path remains unchanged and the redirection path changes

public class ServletDemo04 extends HelloServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        System.out.println("get into ServletDemo04");
        // RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/getParameter");//  Forwarded request path
        // requestDispatcher.forward(req, resp);//  Call forward to forward the request
        servletContext.getRequestDispatcher("/getParameter").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  1. Read resource file

Properties:

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

Are packaged in the same path: classes, which we call classpath

Idea: need a file stream

username=root
password=123456
public class ServletDemo05 extends HelloServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties prop = new Properties();
        prop.load(resourceAsStream);
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");

        resp.getWriter().print(username + ":" + password);
    }

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

The web server receives an http request from the client. For this request, create an HttpServletRequest object representing the request and an HttpServletResponse object representing the response

  • If you want to get the parameters requested by the client, find HttpServletRequest
  • If you want to respond to some information for the client, find HttpServletResponse
  1. Simple classification

Method responsible for sending data to browser:

public ServletOutputStream getOutputStream() throws IOException;
public PrintWriter getWriter() throws IOException;

Method responsible for sending response header to browser

public void setCharacterEncoding(String charset);
public void setContentLength(int len);
public void setContentLengthLong(long len);
public void setContentType(String type);
......
  1. Common applications
  1. Output message to browser
  2. Download File
    1. To get the path of the downloaded file
    2. What is the download file name?
    3. Set up a way to make the browser support what we need
    4. Gets the input stream of the downloaded file
    5. Create buffer
    6. Get OutputStream object
    7. Write FileOutputStream to buffer buffer
    8. Output the data in the buffer to the client
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realPath = "E:\\IntelliJ IDEA\\javaweb-02-servlet\\response\\src\\main\\resources\\urger king.jpg";
        System.out.println("Path to download file:" + realPath);
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        // chinese
        resp.setHeader("Content-disposition", "attachment;filename" + URLEncoder.encode(fileName, "UTF-8"));
        FileInputStream fileInputStream = new FileInputStream(realPath);
        byte[] buffer = new byte[1024];
        int len = 0;
        ServletOutputStream outputStream = resp.getOutputStream();
        while((len = fileInputStream.read()) > 0){
            outputStream.write(buffer, 0, len);
        }
        fileInputStream.close();
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  1. Verification code function

How did the verification code come from?

  • Front end implementation
  • The back-end implementation needs to use Java picture class to produce a picture

Super class (general anesthesia)

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // How to make the browser refresh automatically every 5 seconds
        resp.setHeader("refresh", "3");
        // Create pictures in memory
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        // Get pictures
        Graphics2D g = (Graphics2D)image.getGraphics();
        // Set picture background color
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);
        // Write data to pictures
        g.setColor(Color.blue);
        g.setFont(new Font(null, Font.BOLD, 20));
        g.drawString(makeNum(), 0, 20);
        // Tell the browser to open the request as a picture
        resp.setContentType("image/jpg");
        // The site has a cache
        resp.setDateHeader("expires", -1);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Program", "no-cache");
        // Write the picture to the browser
        ImageIO.write(image,"jpg", resp.getOutputStream());
    }

    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7 - num.length(); i++) {
            sb.append(0);
        }
        String s = sb.toString() + num;
        return num;
    }

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

After a web resource receives a client request, it will notify the client to access another web resource. This process is called redirection
Common scenarios:

  • User login
public void sendRedirect(String location) throws IOException;
public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
//        resp.setHeader("Location", "/response/image");
//        resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);

        resp.sendRedirect("/response/image");
    }

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

Difference between redirection and forwarding:

  • The URL will not change when the request is forwarded
  • The URL will change during redirection
HttpServletRequest

HttpServletRequest represents the request of the client. The user accesses the server through the HTTP protocol. All the information in the HTTP request will be encapsulated in the HttpServletRequest. Through this HttpServletRequest, all the information of the client can be obtained

  1. Get the parameters passed by the front end and request forwarding
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbies = req.getParameterValues("hobbies");
        System.out.println(username);
        System.out.println(password);
        // Background receiving Chinese garbled code
        System.out.println(Arrays.toString(hobbies));

        // Forward request through
        req.getRequestDispatcher("success.jsp").forward(req, resp);
    }

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

Cookie s and sessions

conversation

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

  1. The server gives a mark to the client, and the client can bring the mark when accessing the server next time: cookie
  2. The server registers that you have been here. The next time you come, the server will match you: session
Two techniques for saving sessions

cookie:

  • Client Technology (response, request)

session:

  • Server technology, which can save the user's session information and put the information or data in the session

Common scenario: after the first visit to the website, the second visit directly to the website

Cookie
  1. Get cookie information in the request
  2. The server responds to the client cookie
// Save the time when the user last visited
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();

        // Cookie, which is obtained by the server from the client
        Cookie[] cookies = req.getCookies();// There may be more than one Cookie
        // Determine whether the Cookie is empty
        if(cookies != null){
            // What if it exists
            out.write("Your last visit was:");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                // Get the name of the cookie
                // Avoid null pointer exceptions
                if("lastLoginTime".equals(cookie.getName())){
                    // Gets the value of the cookie
                    long l = Long.parseLong(cookie.getValue());
                    Date date = new Date(l);
                    out.write(date.toLocaleString());
                }
            }
        }else{
            out.write("This is your first visit to this site");
        }
        // The server responds with a Cookie to the client
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");

        // Cookies are valid for one day
        cookie.setMaxAge(24 * 60 * 60);

        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
// Delete a cookie and respond to a cookie that expires immediately, that is, set the effective time to 0
public class CookieDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");

        cookie.setMaxAge(0);

        resp.addCookie(cookie);
    }

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

Cookies are usually 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, and each site can store up to 20 cookies
cookie size is limited
Up to 300 browsers

Session (key)

Session:

  • The server will create a Session object for each user (browser)
  • A Session monopolizes a browser. As long as the browser is not closed, the Session exists
  • After the user logs in, 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, and the browser saves it (multiple can be saved)
  • Session is to write the user's data into the user's exclusive session and save it on the server side (save important information and reduce the waste of server resources)
  • Session is created by the server

Usage scenario:

  • Save a user's login information and shopping cart information
  • Data that is often used in the whole website. We save it in Session

Using Session

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Solve the problem of garbled code
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        // Get Session
        HttpSession session = req.getSession();

        // Store something in the Session
        session.setAttribute("person", new Person("Hu Tutu", 1));

        // Get the ID of the Session
        String id = session.getId();
        if(session.isNew()){
            resp.getWriter().write("Session Created successfully, SessionID For:" + id);
        }else{
            resp.getWriter().write("Session Already exists in the server, SessionID For:" + id);
        }

        // What was done when the Session was created
//        Cookie cookie = new Cookie("JESSIONID", id);
//        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
public class SessionDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Solve the problem of garbled code
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        // Get Session
        HttpSession session = req.getSession();

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

        System.out.println(person);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        // Remove Session saved objects
        session.removeAttribute("person");
        // Log off Session manually
        session.invalidate();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
	<!--Responsive servlet and servlet-mapping Omitted here-->
	
    <!--set up Session Default expiration time (session expires automatically)-->
    <session-config>
        <!--1 Minutes later Session Automatic failure-->
        <session-timeout>1</session-timeout>
    </session-config>

Topics: Java Web Development java web