Java Web Learning Notes

javaweb

1. Basic concepts

1.1 Preface

web development:

  • Meaning of web page www.bilibili.com com

  • Static web

    • html css
    • The data provided to everyone will not change
  • Dynamic web

    • Everyone sees different information at different times and places

    • Technology stack: servlet/jsp, ASP, PHP

In java, the technology of dynamic web resource development is collectively referred to as java Web

1.2 web application

web application: a program that can provide 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 you can access exists on a computer somewhere in the world

  • URL

  • This unified web resource will be placed in the same folder, web application - > Tomcat: server

  • A web application consists of many parts

    • html css js

    • jsp servlet

    • java program

    • jar package

    • configuration file

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

1.3 static web

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

  • Disadvantages of static web

    • The web page cannot be updated. All users see the same page

      • Rotation chart, click special effect: pseudo dynamic
      • JavaScript
    • It cannot interact with the database (data cannot be persisted and users cannot interact)

1.4 dynamic web

The page will display dynamically: "the effect of web display varies from person to person";

Disadvantages:

  • If there are errors in the dynamic web resources of the server, we need to rewrite our background program and publish it again
    • Shutdown maintenance

advantage:

  • web pages can be updated, and all users don't see the same page

  • It can interact with the database (data persistence: registration, product information)

2. web server

2.1 technical explanation

ASP:

  • ASP is the most popular in China
  • Embedded VB script in HTML, ASP + COM;
  • In the development of ASP, there are thousands of lines of business code in a basic page, and the page is very chaotic
  • High maintenance cost!

PHP

  • PHP has fast development speed, powerful functions, cross platform, and simple code (70%)
  • Unable to carry large traffic

JSP/Servlet

  • B/S: browser and server
  • C/S: client and server
  • B/S architecture mainly promoted by sun company
  • Based on Java language (all large companies or some open source components are written in Java)
  • It can bear the impact of three heights
  • Syntax is like ASP, which strengthens the strength of the market

2.2 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:

  • Free, stable performance
  • Lightweight server

3. Tomcat

3.1 installation

3.2 startup and configuration

Start close

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wpmrvoro-162020428070) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210419102025812. PNG)]

Access test: http://localhost:80/

Possible problems:

  1. The java environment is not configured
  2. Flash back problem: compatibility needs to be configured
  3. Garbled code problem

3.3 configuration

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-pcppekcu-162020412872) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210419104207244. PNG)]

You can configure the default port number for startup

  • My default port is 80cat, but it's 80cat here
  • mysql: 3306
  • http:80
  • https:443

You can configure the name of the host

  • The default host name is: localhost - > 127.0.0.1
  • The default location of web apps is webapps

Difficult interview questions

Please talk about how the website is accessed:

  1. Enter a domain name: Enter

  2. Check whether there is a mapping of this domain name 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
    2. No: go to the DNS server to find it. If it is found, it will be returned. If it is not found, it will be returned. If it is not found, it will be returned

3.4 publish a web site

If not, imitate first

  • The website written by yourself can be accessed by putting it under the folder of the specified web application in the server

The structure that a website should have

--webapps : tomcat Server web catalogue
    -ROOT
    -FIRST_WEB_TEST
    	- WEB-INF
    		- web.xml
    		- lib:web Application dependent jar package
        	- classes: java program
    	- index.html Default home page
        - static
                -css
                -js
                -img
        - ...

4. HTTP

4.1 what is HTTP

HTTP is a simple request response protocol, which usually runs on TCP

  • Text: html, string
  • Hypertext: picture music video location map
  • 80

HTTPS: Secure

  • 443

4.2 two times

  • http 1.0
    • HTTP/1.0: after the client can connect with the web server, it can only obtain one web resource
  • http 2.0
    • HTTP/1.1: after the client can connect with the web server, it can obtain multiple web resources

4.3 HTTP request

  • Client - > send request - > server

Baidu:

Request line

  • Request method in request line: GET
  • Request method: GET POST
  • GET: the request can carry fewer parameters, and the size will be limited. The data content will be displayed in the URL address bar of the browser, which is unsafe but efficient
  • POST: the parameters that the request can carry are not limited, and the size is not limited. The data content will not be displayed in the URL address bar of the browser, which is not safe and efficient
request URL: https://www.baidu.com / request address
 Request method: GET						get method/post method
 Status code: 200 OK					Status code: 200
 Remote address: 14.215.177.39:443

Message header

Accept: text/html						Tells the browser what data types are supported
Accept-Encoding: gzip, deflate, br		Coding format
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6  Language environment
Cache-Control: max-age=0
Connection: keep-alive					Tell the browser whether to disconnect or remain connected when the request is completed

4.4 HTTP response

  • Server - > response - > client

Baidu:

Bdpagetype: 2
Bdqid: 0xdfb748bb0000f142
Cache-Control: private
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html;charset=utf-8

Responder

Accept: text/html						Tells the browser what data types are supported
Accept-Encoding: gzip, deflate, br		Coding format
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6  Language environment
Cache-Control: max-age=0
Connection: keep-alive					Tell the browser whether to disconnect or remain connected when the request is completed
HOST: 									host.../
Refresh:								Tell the client how often to refresh
Location: 								Repositioning web pages

Response status code

200: request response succeeded

3 * *: request redirection

4xx: resource not found

5xx: server code error, 502 gateway error

Common interview questions

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

5. Maven

Why learn Maven?

  1. In Java Web development, we need to use a large number of jar packages, which we need to import manually
  2. How can I make something automatically import and configure jar packages for me

Thus maven was born

5.1 Maven project architecture management tool

We are currently using to import Jar packages

Maven's core idea: Convention is greater than configuration

Maven will specify how you should write our java code. You must follow this specification

5.2 download and install Maven

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-jjfxwes7-162020428073) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420150408639. PNG)]

After downloading, unzip it

5.3 configuration environment

The configuration is as follows:

  • M2_HOME: bin directory under maven directory
  • MAVEN_HOME: directory of maven
  • Configure Maven in the path of the system_ HOME

[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-dgb25dh2-162020428074) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420152454575. PNG)]

5.4 Alibaba cloud image

<mirror>
		<id>nexus-aliyun</id>
		<name>Nexus aliyun</name>
 		<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
 		<mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
</mirror>

5.5 local warehouse

Local warehouse

<localRepository>G:\java_environment\apache-maven-3.8.1-bin\apache-maven-3.8.1\maven-repo</localRepository>

5.6 using Maven in IDEA

  1. Start IDEA
  2. Create a Maven project

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-xowuhyxw-162020428075) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420161225584. PNG)]

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-svitdswz-162020412876) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420161453192. PNG)]

  1. The project was built successfully

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-gdsljjgi-162020428076) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420162924921. PNG)]

  1. Watch what's in Maven's warehouse

  2. Maven settings in IDEA

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vxtputs-162020428077) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420163608630. PNG)]

  3. At this point, maven's configuration in IDEA is completed

5.7 create a normal maven project

Clean maven project

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ldufreo0-162020428077) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420164255419. PNG)]

5.8 marking folders in IDEA

5.9 configure TOMCAT in IDEA (refer to https://www.cnblogs.com/weixinyu98/p/9822048.html )

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zpfolncx-162020428078) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420165015425. PNG)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8a4ucquz-162020428078) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420171608706. PNG)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-klkd1irh-162020428078) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210420171624927. PNG)]

5.10 pom documents

pom.xml is the core configuration file of maven

 <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>

5.11 IDEA operation

6. Servlet

6.1 introduction to Servlet

  • Servlet is a technology for sun company to develop dynamic web
  • Sun provides a structure 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

6.2 Hello Servlet

  1. Build a Maven project, delete the src directory, and then create Moudle in this project

  2. Understanding of Maven father son project:

    There will be a moudle in the parent project

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

    Sub projects will have

    <parent>
            <artifactId>javaweb-02-servlet2</artifactId>
            <groupId>com.fan</groupId>
            <version>1.0-SNAPSHOT</version>
    </parent>
    

Update web xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

</web-app>
  1. Maven environment optimization

    1. Modify web XML is the latest
    2. Complete the structure of maven
  2. Write a servlet program

    Write a common class to implement the servlet interface. The servlet interface has two default implementation classes: HttpServlet and GenerateServlet

    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.println("Hello servlet");
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp);
        }
    }
    
  3. Write Servlet mapping

    Why mapping is needed: we write java programs, but we need to access them through the browser, and the browser needs to connect to the web server, so we need to register the Servlet we write in the web service and give it a path that the browser can access;

    <!-- register Servlet -->
        <servlet>
            <servlet-name>hello</servlet-name>
            <servlet-class>com.fan.servlet.HelloServlet</servlet-class>
        </servlet>
        <!-- servlet Request path for -->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
  4. Configure Tomcat

  5. Start test

6.3 Servlet principle

6.4 Mapping problems

  1. A Servlet can specify a mapping path

  2. A Servlet can specify multiple mapping paths

  3. A Servlet can specify a common mapping path

  4. Specify some suffixes or prefixes, etc

  5. Priority issues

    It specifies that the inherent mapping path has the highest priority. If it cannot be found, it will go to the default processing request;

6.5 ServletContext

When the web container starts, it will create a corresponding Servlet 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 parameters
//        this.getServletConfig();  servlet configuration
//        this.getServletContext(); servlet context

        ServletContext context = this.getServletContext();

        String username = "Qin Dynasty";
        context.setAttribute("username", username);//Save a data in Servlet

        System.out.println("Hello");
    }
}
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().println( "name" + username);
    }
}

<servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.fan.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.fan.servlet.GetServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Getc</servlet-name>
        <url-pattern>/Getc</url-pattern>
    </servlet-mapping>
  1. Get initialization parameters
<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().println(url);
    }
  1. Request forwarding

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext context = this.getServletContext();
            System.out.println("Entered ServletDemo01");
    //        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");
    //        requestDispatcher.forward(req,resp);
            context.getRequestDispatcher("/gp").forward(req,resp);
        }
    
  2. Read resource file

    Properties

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

    Discovery: they are all packaged in the same path: classes. We commonly call this path class path

    Idea: need a file stream

    username=qingjiang
    password=123456
    
    public class ServletDemo02 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 + ":" + password);
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp);
        }
    }
    

6.6 HttpServletResponse

The web server receives the HTTP request from the client and creates an object representing the request and response respectively for this request;

  • If you want to get the parameter requested by the client: request
  • If you want to respond to some requests to customers: response

1. Simple classification

Method responsible for sending data to browser
    ServletOutputStream getOutputStream() throws IOException;

    PrintWriter getWriter() throws IOException;
Method responsible for sending response header to browser
	void setCharacterEncoding(String var1);

    void setContentLength(int var1);

    void setContentLengthLong(long var1);

    void setContentType(String var1);
Response status code

2. Common applications

  1. Output message to browser

  2. Download File

    1. To get the path of the downloaded file
    2. What is the name of the downloaded file
    3. Set up a way to make the browser support what we download
    4. Gets the input stream of the downloaded file
    5. Create cache
    6. Get OutStream object
    7. Write FileStream to buffer
    8. Use outputStream to output the data of the cache to the client
    public class FileServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //        1. To get the path of the downloaded file
    //        String path = this.getServletContext().getRealPath("/1.jpg");
            String path = "G:\\java_project\\javaweb-02-servlet2\\Ao Mei.jpg";
            System.out.println("Path to download file" + path);
    //        2. What is the name of the downloaded file
            String fileName = path.substring(path.lastIndexOf("\\") + 1);
    //        3. Set the Chinese file name urlencoder to make the browser support what we download Encode, otherwise it may be garbled
            resp.setHeader("Content-Disposition", "attachment; " +
                    "filename="+ URLEncoder.encode(fileName, "UTF-8"));
    //        4. Obtain the input stream of the downloaded file
            FileInputStream in = new FileInputStream(path);
    //        5. Create cache
            int len = 0;
            byte[] buffer = new byte[1024];
    //        6. Get the OutStream object
            ServletOutputStream out = resp.getOutputStream();
    //        7. Write the FileOutStream to the buffer buffer
            while ((len = in.read(buffer)) > 0){
                out.write(buffer,0,len);
            }
            in.close();
            out.close();
    //        8. Use outputStream to output the data of the cache to the client
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doGet(req, resp);
        }
    }
    

    Verification code function

    How did the verification come from?

    • Front end implementation
    • The back-end implementation needs to use the java picture class to generate a picture
    public class ImageServlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //How to refresh the browser every 5 seconds
            resp.setHeader("refresh","3");
    
            //Create a picture in memory
            BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
            //Get pictures
            Graphics2D graphics = (Graphics2D) image.getGraphics();
            //Set picture background color
            graphics.setColor(Color.white);
            graphics.fillRect(0,0,80,20);
            //Write data to pictures
            graphics.setColor(Color.BLACK);
            graphics.setFont(new Font(null,Font.BOLD,20));
            graphics.drawString(makeNum(),0,20);
            //Tell the browser to open the request as a picture
            resp.setContentType("image/jpg");
            //There is a cache in the website. Do not let the browser 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());
        }
        //Generate random number
        private String makeNum(){
            Random random = new Random(System.currentTimeMillis());
            String num = random.nextInt(9999999) + "";
            StringBuffer buffer = new StringBuffer();
            for(int i = 0; i < 7 - num.length(); i++){
                buffer.append("0");
            }
            num = buffer.toString() + num;
            return num;
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doGet(req, resp);
        }
    }
    
    

    redirect

    After a web resource is requested by the client, it will notify the client to access another web resource. This process is called redirection

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            /*resp.setHeader("Location","/r/img");
            resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);*/
            
            resp.sendRedirect("/r/img");
        }
    

    Interview question: can you talk about the difference between redirection and forwarding?

    Similarities:

    • The page will jump

    difference:

    • When the request is forwarded, the url will not change
    • The url will change when redirecting

6.7 HttpServletRequest

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ylzmbo6y-162020418079) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210422213351792. PNG)]

Request forwarding

Get front-end parameters

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zujw0syb-162020428079) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210422213526989. PNG)]

@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[] hobbies = req.getParameterValues("hobbies");
        System.out.println("=========================");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbies));
        System.out.println("=========================");
        req.getRequestDispatcher("/success.jsp").forward(req,resp);

    }

7. Cookie Session

7.1 conversation

Session: the user opens the browser, creates many hyperlinks and accesses many web resources. This process is called a session

Stateful conversation: a classmate has been to the classroom. Next time we come back to the classroom, we will know that this classmate has been to the classroom

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

  1. I'll give you the invoice

  2. Sign up for Xikai. You've been here

How does a website prove you've been here?

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 next time; cookie
  2. The server registers that you have been here, and I will match you when you come next time;

7.2 two techniques for saving sessions

cookie

  • Client Technology (response, request)

session

  • Server technology, which can save the user's Session information. We can put the information in the Session

Common scenario: website login

7.3 Cookie

  1. Get cookie from request
  2. The server responds to the client cookie
Cookie[] cookies = req.getCookies();
cookie.getName()
cookie.getValue()
new Cookie("LastLoginTime", System.currentTimeMillis() + "");
cookie.setMaxAge(60);
resp.addCookie(cookie);

cookie: generally saved in the local user directory appdata;

Whether there is an upper limit for a website cookie!

  • A cookie can only hold one piece of information
  • A web site can send more than 20 cookie s to the browser
  • cookie size is limited

Delete cookie:

  • Do not set the validity period, close the browser and take effect automatically
  • Set the validity period to 0

7.4 Session (key)

What is Session:

  • The server will create a Session object for each user
  • 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

The difference between Session and cookie:

  • cookie is to write the user's data to the user's browser, which saves it
  • 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)
  • The Session object is created by the server

Usage scenario:

  • Save a user's login information
  • Shopping cart information
  • The data often used in the whole website is saved in Session
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve garbled code
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        resp.setCharacterEncoding("utf-8");

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

        //Save things in Session
        session.setAttribute("name", new Person("Qin Jiang",24));

        //Get the ID of the Session
        String id = session.getId();

        //Judge whether the Session is newly created
        if(session.isNew()){
            resp.getWriter().write("session Created successfully, ID: "+id);
        } else {
            resp.getWriter().write("session Already exists in the server, ID: "+id);
        }
        //What did the Session do when it was created
//        Cookie cookie = new Cookie("JSESSIONID",id);
//        resp.addCookie(cookie);
    }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve garbled code
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        resp.setCharacterEncoding("utf-8");

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

        Person person = (Person) session.getAttribute("name");
        System.out.println(person.toString());
    }
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        //Manual logoff
        session.removeAttribute("name");
        session.invalidate();
    }

Automatic session Expiration:

  <!-- set up Session Default effective time of -->
  <session-config>
    <!-- 15 Automatic failure after minutes -->
    <session-timeout>1</session-timeout>
  </session-config>

8.JSP

8.1 what is JSP

java server pages: java server-side pages, like servlets, are used for dynamic page design

Biggest features:

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

8.2 JSP principle

How does JSP execute

  • There are no problems at the code level

  • Server internal work

    There is a work directory in tomcat;

    Using Tomcat in IDEA will generate a work directory in Tomcat in IDEA

route:

C:\Users\11482\.IntelliJIdea2019.3\system\tomcat\Unnamed_javeweb-session-cookie\work\Catalina\localhost\ROOT\org\apache\jsp

The discovery page is transformed into a Java program

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-m37skalb-162020428080) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210423203437157. PNG)]

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

JSP will eventually be converted into java classes

JSP is essentially a Servlet

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-h0suwzg6-162020428080) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210423210852536. PNG)]

In a 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");

Front end output format

8.3 JSP basic syntax

Any language has its own syntax. JSP, as an application of java counting, has some expanded syntax (just understand it), which is supported by java syntax.

JSP expression

<%--JSP expression
    Used to output the program to the client
    <%= Variable or expression%>
  --%>
  <%= new java.util.Date()%>

JSP script fragment

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

Re implementation of script fragments

<%
    int x = 10;
    out.println(x);
  %>
  <p>This is a JSP file</p>
  <%
    int y = 2;
    out.println(y);
  %>
  <hr>

  <%--Embedding in code HTML element--%>
  <%
    for(int i = 0; i < 5; i++){

  %>
  <h1>Hello world <%=i%></h1>
  <%
    }

  %>

JSP declaration

<%!
    %>

JSP declaration: it will be compiled into the java class generated by JSP, and others will be generated into_ jspServlet method

8.4 instructions of JSP

<%@page args...%>
<%@include file = " "%>
<jsp:include page = ""/>

8.5 9 built in objects

  • PageContext store things
  • Request to store things
  • Response
  • Session storage
  • Application(ServletContext) stores things
  • config(ServletConfig)
  • out
  • page
  • exception
	pageContext.setAttribute("name1","Qinjiang 1");//The saved data is only valid in one page
    request.setAttribute("name2","Qinjiang 2");//The saved data is only valid in one request, and the request forwarding will carry this data
    session.setAttribute("name3","Qinjiang 3");//The saved data is valid only in one session, from opening the browser to closing the browser
    application.setAttribute("name4","Qinjiang 4");//The saved data is valid in the server, from opening the server to closing the server

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

session: the client sends a request to the server, and the generated data is still useful when the user runs out, such as a shopping cart;

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

8.6 JSP tag, JSTL tag, EL expression

EL expression: ${}

  • get data
  • Perform operations
  • Get common objects of web Development
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/taglibs/standard -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

JSP tag

<jsp:forward page="jspStag2.jsp">
    <jsp:param name="name" value="bai"></jsp:param>
    <jsp:param name="age" value="24"></jsp:param>
</jsp:forward>

JSTL expression

The use of JSTL tag library is to make up for the deficiency of HTML tags; It has customized many tags that can be used by us. The function of tags is the same as that of java code.

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

Core label

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-n2bkxahz-162020428080) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210425200935608. PNG)]

Format label

SQL tag

XML tag

JSTL tag usage steps

  • Introduce the corresponding taglib
  • Use one of the methods
  • jst packages are also required in Tomcat
<html>
<head>
    <title>Title</title>
</head>
<body>

<h4>if test</h4>

<hr>

<form action="coreif.jsp" method="get">
    <input type="text", name="username", value="${param.username}">
    <input type="submit" value="Sign in">
</form>

<%--Judge that if the submitted user name is administrator, the login is successful--%>
<c:if test="${param.username=='admin'}" var="isAdmin" >
    <c:out value="Administrator, welcome!"/>
</c:if>
<c:out value="${isAdmin}"/>


</body>
</html>

<c:set var="score" value="85"/>

<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>=70}">
        Your grades are average!
    </c:when>
    <c:when test="${score>=60}">
        Your grade is pass!
    </c:when>
</c:choose>
<%
    ArrayList<String> people = new ArrayList<>();
    people.add("Zhang San");
    people.add("Li Si");
    people.add("Wang Wu");
    people.add("Zhao Liu");
    request.setAttribute("list",people);
%>
<%--
var : Variables traversed each time
items: Traversal object
begin: start
end  : end
step : step
--%>
<c:forEach var="people" items="${list}">
    <c:out value="${people}"/><br>
</c:forEach>

<hr>

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

8.7 JavaBean

JavaBean s have specific ways of writing:

  • There must be a parameterless construct
  • Property must be privatized
  • There must be a corresponding get method

It is generally used to map fields in the database: ORM

ORM: Object Relational Mapping

  • Table - > class
  • Fields - > Properties
  • Row record - > object
indexnameageaddress
1Qinjiang 13Xi'an
2Qinjiang 218Xi'an
3Qinjiang 3100Xi'an
class people{
    private int idx;
    private String name;
    private int age;
    private String address;
}

class A{
    new people(1, "Qinjiang 1", 3, "Xi'an");
}

9.JDBC

What is JDBC: java connection database

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-lr5qahoo-162020418081) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210425212153658. PNG)]

jar package support is required:

  • java.sql
  • javax.sql
  • mysql-connector-java...

Construction of experimental environment

INSERT INTO users(id, `name`, `password`, email, birthday)
VALUES (1, 'Zhang San', '123456', 'zs@qq.com','2000-01-01');
INSERT INTO users(id, `name`, `password`, email, birthday)
VALUES (2, 'Li Si', '123456', 'ls@qq.com','2000-02-02');
INSERT INTO users(id, `name`, `password`, email, birthday)
VALUES (3, 'Wang Wu', '123456', 'ww@qq.com','2000-03-03');

Import database dependencies

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

Connect to database in IDEA

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-q9dqv3cn-162020418081) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210425221023070. PNG)]

JDBC fixed steps

  1. Load driver
  2. Connect database
  3. Object Statement: CRUD to send SQL to database
  4. Write SQL
  5. Execute SQL
  6. Close connection
public class TestJDBC {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //configuration information
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characteoEncoding=utf-8";
        String username = "root";
        String password = "123";

        //1. Load drive
        Class.forName("com.mysql.jdbc.Driver");
        //2. Connect to the database
        Connection connection = DriverManager.getConnection(url, username, password);
        //3. Send SQL object Statement to the database
        Statement statement = connection.createStatement();

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

        //5. Execute SQL query and return a result set
        ResultSet resultSet = statement.executeQuery(sql);

        while (resultSet.next()){
            System.out.println("id = " + resultSet.getObject("id"));
            System.out.println("name = " + resultSet.getObject("name"));
            System.out.println("password = " + resultSet.getObject("password"));
            System.out.println("email = " + resultSet.getObject("email"));
            System.out.println("birthday = " + resultSet.getObject("birthday"));
        }

        //6. Close the connection to release resources. Turn it on first and then turn it off
        resultSet.close();
        statement.close();
        connection.close();
    }
}

Precompiled SQL

public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //configuration information
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characteoEncoding=utf-8";
        String username = "root";
        String password = "123";

        //1. Load drive
        Class.forName("com.mysql.jdbc.Driver");
        //2. Connect to the database
        Connection connection = DriverManager.getConnection(url, username, password);

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


        //4. Precompile
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1, 4);//For the first placeholder? The value of is assigned to 1
        preparedStatement.setString(2, "Madness theory JAVA");
        preparedStatement.setString(3, "123456");
        preparedStatement.setString(4, "24736743@qq.com");
        preparedStatement.setDate(5, new Date(new java.util.Date().getTime()));

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

        if(i > 0){
            System.out.println("Insert successful~");
        }
        //6. Close the connection to release resources. Turn it on first and then turn it off
        preparedStatement.close();
        connection.close();
    }

affair

Either all succeed or all fail

Open transaction
 Transaction commit
 Transaction rollback
 Close transaction
    
    transfer accounts:
    A: 1000
    B: 1000
    A --100--> B
    

Junit unit test

	<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

Build an environment

@Test
    public void test() throws ClassNotFoundException, SQLException {
        //configuration information
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characteoEncoding=utf-8";
        String username = "root";
        String password = "123";
        Connection connection = null;
        try {
            //1. Load drive
            Class.forName("com.mysql.jdbc.Driver");
            //2. Connect to the database
            connection = DriverManager.getConnection(url, username, password);

            //3. Notify the database to start the transaction
            connection.setAutoCommit(false);

            String sql = "update account set money = money - 100 where name = 'A'";
            connection.prepareStatement(sql).executeUpdate();

            //Manufacturing error
            //int i = 1 / 0;

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

            connection.commit();
            System.out.println("Submitted successfully~");
        } catch (Exception e){
            connection.rollback();
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }

10. MVC three-tier architecture

What is MVC: model view controller

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-o8p3p8wu-162020412882) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210426145246418. PNG)]

model

  • Business processing: business logic (Service)
  • Data persistence layer: CRUD

view

  • Display data
  • Provide link to initiate Servlet request

Controller

  • Accept the user's request: req: request parameters, session information

  • Give it to the business layer to process the corresponding code

  • Control view jump

Sign in -------> Accept user login request -----> Handle the user's request (get the user login parameters, username´╝îpassword) 
------>Give it to the business layer to handle the login business (judge whether the user name and password are correct)-------->Dao Whether to query the user name and password of the layer -->database

11. Filter

Filter: filter, which is used to filter the data of the website

  • Deal with Chinese garbled code
  • validate logon

It is suggested to save the picture directly to the external link (javaassg-1625g-image. 2020203) (it is suggested to upload the picture directly to the external link: \ javaassg-1625g-image. 2020203)

Filter development steps

1. Guide Package

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-6s3rkss9-162020418082) (G: \ vscode_files \ blog \ JavaWeb. Assets \ image-20210426204447136. PNG)]

2. Write filter

public class CharacterEncodingFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter initialization");
    }
    //chain: chain

    /**
     * 1.All code in the filter will be executed when filtering specific requests
     * 2.The filter must continue to peer filterchain doFilter
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");


        System.out.println("CharacterEncodingFilter Before execution...");
        filterChain.doFilter(servletRequest,servletResponse);//Let our program go on
        System.out.println("CharacterEncodingFilter After execution...");
    }

    public void destroy() {
        System.out.println("CharacterEncodingFilter Destroy");
    }
}
  1. On the web Configure Filter in XML
	<filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>com.fan.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>

12. Listener

Implement a listener interface

public class OnlineCountListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        ServletContext context = httpSessionEvent.getSession().getServletContext();

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

        Integer onlineCount = (Integer) context.getAttribute("OnlineCount");

        if(onlineCount == null){
            onlineCount = new Integer(1);
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count + 1);
        }
        context.setAttribute("OnlineCount",onlineCount);
    }

    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext context = httpSessionEvent.getSession().getServletContext();
        Integer onlineCount = (Integer) context.getAttribute("OnlineCount");

        if(onlineCount == null){
            onlineCount = new Integer(0);
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count - 1);
        }
        context.setAttribute("OnlineCount",onlineCount);
    }
}

		<listener>
        <listener-class>com.fan.Listener.OnlineCountListener</listener-class>
    </listener>

13. Common applications of filters and monitors

Listener: often used in GUI programming

Users can enter the home page only after logging in. They can't enter the home page after logging out!

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

  2. When entering the home page, judge whether the user has logged in

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    if(request.getSession().getAttribute("USER_SESSION") == null){
        response.sendRedirect("/error.jsp");
    }
    
    filterChain.doFilter(request,response);
    

ated(HttpSessionEvent httpSessionEvent) {
ServletContext context = httpSessionEvent.getSession().getServletContext();

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

    Integer onlineCount = (Integer) context.getAttribute("OnlineCount");

    if(onlineCount == null){
        onlineCount = new Integer(1);
    } else {
        int count = onlineCount.intValue();
        onlineCount = new Integer(count + 1);
    }
    context.setAttribute("OnlineCount",onlineCount);
}

public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    ServletContext context = httpSessionEvent.getSession().getServletContext();
    Integer onlineCount = (Integer) context.getAttribute("OnlineCount");

    if(onlineCount == null){
        onlineCount = new Integer(0);
    } else {
        int count = onlineCount.intValue();
        onlineCount = new Integer(count - 1);
    }
    context.setAttribute("OnlineCount",onlineCount);
}

}

```xml
		<listener>
        <listener-class>com.fan.Listener.OnlineCountListener</listener-class>
    </listener>

13. Common applications of filters and monitors

Listener: often used in GUI programming

Users can enter the home page only after logging in. They can't enter the home page after logging out!

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

  2. When entering the home page, judge whether the user has logged in

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    if(request.getSession().getAttribute("USER_SESSION") == null){
        response.sendRedirect("/error.jsp");
    }
    
    filterChain.doFilter(request,response);
    

Added by wanttoshop on Fri, 18 Feb 2022 06:57:13 +0200