Java Web from introduction to actual combat

Posted by bookchiq on Mon, 28 Feb 2022 06:41:49 +0100

Personal homepage: Hello Code.
This column: Java Web from introduction to actual combat
It is long and not finished, and the follow-up content will be continuously updated
This article will also be published in sections for your convenience
If you don't have Java foundation, please go first Java zero foundation guide Column learning corresponding knowledge
If you have any questions, please correct them and study together~~

Linux

First knowledge of Linux

Operating system: computer program that manages computer hardware and software resources. It is also the core and cornerstone of computer system.

Mainstream operating system

  • Desktop operating system: Window series, macOS, Linux
  • Server operating system: Linux, Windows Server
  • Embedded operating system: Linux
  • Mobile device operating system: Unix (Linux, ios)

Development history of Linux

  • Minix 1984 (for teaching only)
  • The driver was written in 1991 and the source code of Linux kernel was released at the end of the year
  • 1994 Linux 1 0(Linus Torvalds)
  • So far, it has become popular

Linux features

  • Linux is a Unix like operating system that is free to use and spread
  • It is a multi-user, multi task, multi thread and multi CPU operating system based on POSIX and Unix
  • It can run major Unix tools, software, applications and network protocols. It supports 32-bit and 64 bit hardware
  • Inheriting the design idea of Unix with network as the core, it is a multi-user network operating system with stable performance
  • Two basic ideas
    • Everything is a document
    • Each software has a definite purpose
  • Fully compatible with posix1 0 standard
  • Multi user and multi task
  • Good interface
  • Support multiple platforms

Differences between Linux and other operating systems

  • Open source situation
  • Hardware applicable
  • Different in essence
  • System interface
  • Driver
  • System use
  • Software and support

Windows is more suitable for home and personal use

Linux is more suitable for enterprise servers

Linux publishers and popular distributions

  • Redhat company ------- Red Hat Linux (the most famous version of Linux, charging) --- Free CentOS
  • CentOS features: mainstream, free and easy to update

Installation and use of Linux

Install the virtual machine before installing Centos

Vmware

Introduction to Vmware

  • You can use more than two operating systems on the same PC without partition or reboot
  • Completely isolate and protect the environment of different operating systems and all software and data
  • Different operating systems can also interact with each other
  • With recovery function
  • Be able to set and modify the operating environment of the operating system at any time
  • Common virtual machine software: VMware workstation, VirtualBox

Vmware Download: https://www.vmware.com/cn.html

CentOS image download: https://www.centos.org/download/
High speed download address

SecureCRT

Introduction: SecureCRT is a terminal emulator that supports SSH (SSH1 and SSH2). In short, it is the software to log in to Unix or Linux server host under Windows.

Directories and files

  • Linux doesn't have the concept of drive letter. There is only one root directory /, and all files are under it
  • etc represents the configuration file in the system
  • Usr, usr/bin and usr/sbin all indicate the directory where the system preset execution files are placed
  • var/log indicates the storage directory of program running logs
  • Switch root directory: cd/
  • View directory contents: ls -l

time synchronization

Clone and snapshot

Cloning: make a complete copy of the original system. After the original system is lost, the cloned system can still be used normally

  • Large occupied space
  • The original system does not exist, and the clone can still be used

Snapshot: records the current state of the system and does not copy the system completely

  • Small footprint
  • If the original system does not exist, the snapshot cannot be used

The virtual machine needs to be shut down when cloning and taking snapshots

System and setup commands

account management

User related commands can only be executed with administrator privileges

Command: su root

  • Create user: useradd (option) user name
  • User password: passwd (option) user name
    • The password cannot be a palindrome
    • The length must be greater than 8 bits
    • It must be a combination of letters and numbers

Switch under root permission. Other users can switch directly without entering password

  • Modify user: usermod option user name

  • Delete user: userdel (option) user name

User group

Divide users into groups to facilitate the management of users

  • Create user group: groupadd (option) user group name
  • Modify user group: groupmod (option) user group name
  • Query the user's group: groups user name
  • Delete user group: groupdel user group name
  • Members in the management user group: gpasswd (optional) group name

    gpasswd is a management tool under Linux, which is used to add or remove a user from a group

    • -a: Add user to group
    • -d: Remove user from group
    • -A: Designated administrator
    • -M: The purpose of designated team members is similar to that of - A
    • -r: Delete password
    • -R: Restrict users to log in to the group. Only members of the group can join the group with newgrp

System management related commands

  • Date management: date [parameter option]
    Parameter options:
    • -d "string": displays the date and time indicated by the string. The string must be preceded by double quotes
    • -s "string": set the date and time according to the string. The string must be preceded by double quotes
    • -u: Display GMT (Beijing time is CST)
    • --Help: online help
    • --Version: displays version information
  • Display login account information: logname
  • Switch user: su user name
  • View the details of the current user (user id, group id, group): id user name
  • Improve the operation authority of ordinary users: sudo [parameter option]

Process related commands

Display the dynamic of process in real time: top

pid: id of each process

User: which user does the process belong to

PR: priority of process

NI: process priority (negative number means high priority and positive number means low priority)

VIRT: the total amount of virtual memory occupied by the current process

S: Status of the current process

  • Display all process information in real time (display full command): top -c
  • Display the information of the specified process in real time: top -p PID
  • End real-time monitoring: q

View the currently running process information: ps

  • Display all process information in the system: ps -A
  • Display all process information in the system (complete information): ps -ef
  • Displays the process information of the specified user: ps -u user name

Interrupt the program in execution: kill PID

  • For example: kill 1111 means to kill the process with PID 1111
  • kill -9 PID: force to kill the process with the specified PID
  • Kill - U user name: kill all processes in this user
  • kill -9 $(ps -ef|grep user name): kill all processes of the specified user
  • kill -l: check the corresponding number

Shutdown command: shutdown (delayed shutdown)

  • shutdown -h now: shutdown immediately
  • Shutdown + 1 "shutdown after 1 minute": shutdown after one minute delay and give warning information
  • shutdown -r +1 "ready to restart": restart after a delay of one minute and give a warning message
  • shutdown -c: cancel shutdown command
    Restart command: reboot

Display the user currently logged in to the system: who

  • who -H: display details (title) information

Correct server time and time zone: timedatectl

Several small concepts

projectexplain
time zoneDue to different time zones, the displayed time is different, which involves problems such as daylight saving time and adjustment. The date command can be viewed
System Clock: System ClockThe time of Linux OS can be viewed with the date command
Hardware clock: RTC:Real Time ClockThe BIOS time powered by battery on the motherboard can be viewed by hwlock - R
NTP:Network Time ProtocolThere are often differences between the local time and the actual time. Generally, NTP server is used for time calibration
  • timedatectl status: displays the current time and date of the system
  • Timedatectl list timezones: view all available time zones
  • Timedatectl set timezone "Asia / Shanghai": set the local time zone
  • Timedatectl set NTP false: disable time synchronization
  • Timedatectl set time "2022-02-22 20:20:00": set the time
  • Timedatectl set NTP true: enables time synchronization

Clear screen: clear

Directory management

Common commandseffect
lsList directory
cdSwitch directory
pwdShow current directory
mkdirCreate a new directory
rmdirremove empty directories
cpCopy files or directories
rmDelete file or directory
mvMove files or directories
Modify the name of the file or directory
  • ls command is equivalent to opening a folder in Windows system and seeing the directory and file details.
    • Syntax: ls [parameter options] directory name
    • -a: Show all files or directories (including hidden)
    • -d: List only the directory itself, not the file data in the directory (common)
    • -l: Long data list, including file attributes, permissions and other data (common)

    ls: Show files and folders that are not hidden
    ls -l: show details of files and folders that are not hidden
    ls -al: displays the details of all files and folders

  • pwd -P: view the current directory
  • cd [relative path or absolute path]: switch directories
    • cd ..: Return to the previous directory
  • mkdir
    • Name of mkdir folder: create a single level directory
    • To create a multi-level folder, use mkdir -p aaa/bbb
  • rmdir
    • rmdir folder name: delete empty directory
    • rmdir -p aaa/bbb: delete multi-level directories (delete bbb first. If aaa is empty after deletion, aaa will be deleted together)
  • rm
    • rm file path: delete files
    • rm -r directory path: delete the directory and all contents in the directory (single level directory or multi-level directory are OK)
  • touch file name Suffix: create a file
  • cp
    • cp data source destination: file copy (file only)
    • Copy - aaa / * and all files in - ccc directory
  • mv
    • mv data source destination: Rename (data source and destination are the same), move files or folders
    • mv file name: change the source file name to the target file name
    • mv directory name directory name: the target directory already exists. Move the source directory to the target directory; If the target directory does not exist, rename it

File basic properties

  • File permissions (10 digits in total)
    • The first digit is d, indicating a folder; Yes - indicates that it is a file| Indicates a linked document (shortcut)
    • r means readable; w means writable; x means executable- Indicates that you do not have current permissions
    • 2-4 bits indicate the master permission (what the user to which the file belongs can do)
    • 5-7 bits indicate group permission (what the user group where the file is located can do to it)
    • 8-10 bits indicate other user permissions
  • chgrp command (change group)
    • chgrp [option parameter] [group] [file or directory...]: Change group
    • chgrp root aaa: change the group of aaa folder to root
    • chgrp -v root aaa: change the group of aaa to root (- v will have one more prompt)
  • chown command
    • chown owner name file name: change owner name
    • chown [parameter option] owner name: owner group name file name: change owner and owner group
    • -R: Process all files in the specified directory and its subdirectories
  • chmod command
    • Function: modify the permissions of owner, group and other users
    • Numeric syntax: chmod [parameter options] numeric permission file or directory
    • Syntax of symbol mode: Chmod, u = RWX, g = Rx, o = R, a.txt
    • -R: Make the same permission change for all files and subdirectories under the current directory (i.e. change one by one in a recursive manner)

Modification method

  • Digital mode
    • r-----4
    • w----2
    • x----1
    • -----0

    When setting, three numbers will be added together
    For example: rwx is 7

  • Symbolic mode
    • user belongs to master permission ----- u
    • Group belongs to group permission ----- g
    • others other permissions - o
    • all full identities - a
    • +(add), - (remove), = (set)
    • r (readable), w (writable), x (executable)

Comprehensive case

Requirements: a company's development team has three users: Java, erlang and golang
There is a file directory tmp/work for them to develop. How to make these three users have write permission

thinking

  • Create three users and add them to the corresponding dev group
  • Change the group of tmp/work folder to dev group
  • Modify the permissions of the group to which the folder belongs

file management

touch

  • Syntax: touch [parameter options] file name

    If the file does not exist, create the file. If it does exist, modify the time attribute

  • touch a{1..10}.txt: create A1 Txt all the way to a10 Txt a total of 10 files (create empty files in batch)
  • stat a.txt: view the details of the file

vi/vim editor

  • vi editor: it can only edit text content, and cannot typeset fonts and paragraphs
    • Mouse operation is not supported
    • No menu
    • Only command
  • vim editor: vim is a text editor developed from vi.
    • Code completion, compilation, error jump and other convenient programming functions are particularly rich, which are widely used by programmers

In short:
vi is an old-fashioned word processor, but it has complete functions, but there are still areas for improvement
vim can be said to be a very useful tool for programmers and developers

  • Three modes of vi/vim
    • Reading mode (command mode)
    • Edit mode (edit mode)
    • Save mode (last line mode)

    In command mode, you can only read but not write
    In the command mode, enter i to enter the editing mode. After editing, press Esc to exit the command mode
    Input in the command mode: you can enter the last line mode. After saving, you can press Esc twice to continue to return to the command mode

  • Open and new files
    • Syntax: vim file name
    • If the file already exists, it will be opened directly (command mode)
    • If the file does not exist, open a temporary file. After saving and exiting, a new file will be created
  • Enter edit mode
commandenglishfunctionCommonly used
iinsertInsert text before current characterCommonly used
IinsertInsert text at the beginning of the lineMore commonly used
aappendAdd text after current character
AappendAdd text at the end of the lineMore commonly used
oInsert an empty line after the current lineCommonly used
OInserts an empty line before the current lineCommonly used
  • Enter the last line mode to save the file
    • : q: when vim enters the file without any operation on the file content, you can press "q" to exit
    • :q!: When vim enters a file, it operates on the contents of the file but does not want to save and exit
    • : wq: normal save exit
    • :wq!: Forcibly save and exit, only for root user or file owner
  • vim positioning line
    • Syntax: vim file name + number of lines: view the file and locate the specific number of lines
    • vim a.txt +5: view the a.txt file and navigate to line 5
  • exception handling
    • If vim exits abnormally, swap files may be saved on disk

    When modifying a file (a.txt), in order to ensure the security of the file, vim will not modify the source file, but will generate a new file (a.txt.swp) and edit the file
    The new file is written back to the source file only when it is saved

    • If there is an exchange file, the next time you edit the file with vim, the system will prompt whether to continue the operation on the exchange file (delete the exchange file)

File view

commandfunction
cat file nameView small file content
less -N file nameSplit screen display of large file content
head -n file nameView the previous section of the file
tail -n file nameView the last part of the file
grep keyword file nameSearch text file content by keyword
  • cat -n a.txt: you can add the parameter option - n to display the line number
    • Only small files can be read
    • Reading large files may display incompletely
  • less file name: view large files
    • Add - N to display the line number
    • ctrl + F: move one screen forward
    • ctrl + B: move one screen backward
    • ctrl + D: move half screen forward
    • ctrl + U: move half screen backward
    • j: Move one line forward
    • k: Move back one line
    • G: Move to last line
    • g: Move to first row
    • q/ZZ: exit less command
  • tail file name: view the last 10 lines of the file by default
    • tail -3 b.txt: view the last 3 lines of the file
    • tail -f b.txt: dynamically display the last 10 lines of the file (ctrl + C stop)
    • tail -n +2 b.txt: displays the contents of the file b.txt, from line 2 to the end of the file
    • tail -c 45 b.txt: displays the last 45 characters of the file
  • head file name: view the first 10 lines of the file
    • Other contents are similar to tail
  • grep command
    • Similar to the search function of ctrl+F after opening a file under Windows
    • Find the corresponding process
    • Syntax: grep [parameter options] keyword file: search the contents of text files according to keywords
    • -n: Display the line number containing the keyword
    • -i: Display the lines containing keywords and ignore case when searching
    • -v: Show the lines without keywords
    • ps -ef | grep sshd: show the process containing sshd in the process
    • ps -ef | grep -c sshd: display the number of processes containing sshd in the process

echo command

  • echo string: display text
  • echo string > File Name: write the string to the file (overwrite the file content)
  • echo string > > File Name: write the string to the file (do not overwrite the original content)
  • cat nonexistent Directory & > > existing file: append the failure result of the command to the specified file

awk command

  • AWK is a language for processing text files and a powerful text analysis tool (the name is taken from the letters in the names of the three founders)
  • Syntax: awk [parameter options] 'syntax' file
  • Filter: cat a.txt | awk '/zhang|li /': view the lines containing zhang or li in the a.txt file
  • cutting
optionmeaning
-F ','Use specified character segmentation
Number $+Get what paragraph
$0Get the content of the current line
OFS = "character"Segment split string when outputting out
toupper()Convert characters to uppercase
tolower()Convert characters to lowercase
length()Return character length

Cat a.txt | awk - f '' {print $1, $2, $3} ': divide the contents of a.txt by spaces and print columns 1-3
Cat a.txt | awk - f '' {print toupper ($1), $2, $3} ': separate the contents in a.txt and convert the contents in $1 into uppercase characters for output
Cat a.txt | awk - f '' {ofs = "---"} {print $1, $2, $3} ': separate the contents in a.txt and re separate them with -. Then output

  • calculation
commandmeaning
awk
BEGIN {initialize operation}
{execute every line}
END {operation at END}
file name
Fixed grammar
BEGIN {here is the statement before execution}
{here is the statement to be executed for each line}
END {this is the statement to be executed after all rows are processed}
file name

Cat a.txt | awk - f '' 'begin {} {totle = totle + $2} end {print totle}': after dividing a.txt, add the value of $2 and output it
Cat a.txt | awk - f '' 'begin {} {totle = totle + $2} end {print totle}': output totle and total number of people (lines)

Soft connection

  • Similar to the shortcut in Windows
  • Syntax: ln -s target file path shortcut path
  • ln -s aaa/bbb/ccc/ddd/eee/a.txt a.txt

Compression command

Find command

  • Syntax: find [parameter option] < specified directory > < specified condition > < specified content >: find files in the specified directory
  • Parameter options
    • -name filename: find a file named filename
    • -ctime -n or + N: find files by time, - N refers to within n days and + n refers to before n days
  • find . -name "*.txt": find all files with txt suffix in the current directory
  • find . -ctime -1: files operated within 1 day under the current folder

    Will Replace with / to search in the whole range

gzip command

  • Syntax: gzip [parameter options] [file]: compressed file
  • gzip a.txt: compress the a.txt file
  • gzip *: compress all files in the current directory (those already compressed cannot be compressed again)
  • gzip -dv file name: unzip the file and display the details

gunzip command

  • Syntax: gunzip [parameter] [file]: extract the file
  • gunzip compressed file: unzip the compressed file
  • gunzip *: unzip all compressed files in the current directory

tar command

  • Syntax: tar [required parameters] [select parameters] [file]: package, compress and decompress (file / folder)
  • Note: tar itself does not have compression function. It is implemented by calling compression function
  • Parameter options
    • -c: Create a new compressed file
    • -v: Display instruction execution process
    • -F < backup file >: Specifies the compressed file
    • -z: Process compressed files through the gzip instruction
    • -t: Lists the contents of the compressed file
    • -x: Indicates decompression
  • tar -cvf package file name file name: package the file and specify the file name after packaging (only package without compression)
  • tar -zcvf b.gz b.txt: compress b.txt into b.gz through gzip instruction and display the process (package compression)
  • tar -zcvf aaa.gz aaa: compress AAA folder to AAA gz
  • tar -ztvf aaa.gz: view the contents of the compressed file
  • tar -zxvf aaa.gz: unzip AAA GZ file

zip command

  • Syntax: zip [required parameters] [select parameters] [file]: compression
  • Note: zip is a widely used compression program. After the file is compressed, another compressed file with ". Zip" extension will be generated
  • Parameter options
    • -q: Instruction execution is not displayed
    • -r: Recursive processing, which processes all files and subdirectories under the specified directory together
  • zip -q -r compressed file name file / folder: compress the corresponding file / folder

unzip command

  • Syntax: unzip [required parameters] [select parameters] [file]: unzip
  • Note: only compressed files with ". zip" extension can be decompressed
  • Parameter options
    • -l: Displays the files contained in the compressed file
    • -D < Directory >: specify the directory to store the file after decompression
  • unzip -l aaa.zip: View AAA Files contained in zip compressed files
  • unzip -d aaa aaa.zip: AAA Unzip the zip file into the AAA folder (AAA folder may not exist and will be created automatically)

bzip2 command

  • Syntax: bzip2 [parameter options] file: compressed file
  • Note: using the new compression algorithm, compared with zip, the compressed file is smaller than the original, but it takes longer
  • If no parameters are added, the compressed file of bz2 will be generated after bizp2 compresses the file, and the original file will be deleted
  • bzip2 a.txt: compress and delete a.txt
  • Bunzip2 command: bunzip2 [parameter options] file: unzip
    • -v: When you unzip a file, detailed information is displayed
    • bunzip2 -v a.bz2: unzip and display details

Network and disk management

Network management

  • ifconfig command
    • Syntax: ifconfig [parameter option]: command to display or configure network devices
    • ifconfig ens37 down: close this network card
    • ifconfig ens37 up: enable the network card ens37
    • ifconfig ens37 192.168.23.199: change the ip address of the ens37 network card to 192.168.23.199
    • ifconfig ens37 192.168.23.199 netmask 255.255.255.0: configure ip address and subnet mask
  • ping command
    • Syntax: ping [parameter option]: check whether it is connected with the host
    • -C < completion times >: set the number of times to complete the request response
    • ping -c 2 www.baidu.com: Specifies the number of packets received
  • netstat command
    • Syntax: netstat [parameter option]: displays the network status
    • -a: Displays the sockets in all connections
    • -i: Display network card list

Disk management

  • lsblk command
    • Syntax: lsblk [parameter option]: lists the usage of the hard disk
    • English abbreviation of list block
    • lsblk -f: display system information
  • df command
    • Syntax: df [parameter option]: displays the current disk usage on the Linux system
    • – total: displays all information
    • -h: Converted into KB, MB, GB and other forms for display (easy to read)
    • df: displays the usage of the entire hard disk
    • df folder: displays folder usage
    • df --total: display all information
    • df -h: display the results in kb, mb, gb and other forms, which is conducive to reading
  • mount command
    • Syntax: Mount [parameter option] Directory: used to mount devices outside the Linux system
    • Similar to the USB flash disk in Windows, but in Linux, you need to manually create a new folder and associate the folder with the USB flash disk (mount point and mount)

    Note: the directory of "mount point" requires the following requirements:
    The directory exists in advance. You can create a new directory with mkdir command
    The mount point directory cannot be used by other processes
    The original files under the mount point will be hidden

    • mount -t auto /dev/cdrom PPP: mount the optical drive and PPP folder
    • umount PPP: uninstall the optical drive mounted in the PPP folder

yum

  • In Linux, if we need to find, install, download or uninstall other software, we need to operate through yum. Full English Name: Yellow dog Updater,Modified
  • yum common commands
    • List all updatable software commands: yum check -update
    • Update all software commands: yum update
    • Install only the specified software command: Yum install < package_ name>
    • Update only the specified software commands: Yum update < package_ name>
    • List all installable software commands: yum list
    • Delete package command: Yum remove < package_ name>
    • Find package command: Yum search < keyword >
    • Clear cache command:
      • yum clean packages: clear the packages in the cache directory
      • yum clean headers: clear headers under cache directory
      • Yum clean oldheads: clear old headers in cache directory
      • Yum clean, yum clean all (= Yum clean packages; Yum clean oldheads): clear the packages and old headers in the cache directory
  • -y: During the installation process, if there is a selection prompt, select y for all
  • Note: using yum must be networked and under root permission
  • yum -y install tree:
  • Tree: execute the tree to display the current directory structure
  • yum remove tree: remove tree
  • yum list tom *: find software names starting with tom
  • yum source
    • When downloading the software, it is obtained from the yum source. By default, it is the default Yum source in centos (in foreign countries, the download speed is slow)
    • Replace domestic yum source
      • yum -y install wget: install a download tool
      • cd /etc/yum.repos.d /: enter the relevant folder of Yum
      • mv CentOS-Base.repo CentOS-Base.repo.back: rename the original yum file (backup)
      • wget -O CentOS-Base. repo http://mirrors.aliyun.com/repo/Centos-7.repo : Download Alibaba yum source file
      • yum clean all: clean up the cache and reload yum
      • yum makecache: create a cache file for the new yum source
      • yum search tomcat: find the software to verify whether the yum source of Alibaba cloud can be used normally

rpm

  • Initially, the RedHat Linux distribution was dedicated to managing programs for various Linux suites
  • The difference between and yum
    • rpm can only install rpm packages that have been downloaded to the local machine
    • yum can download and install rpm packages online, update the system, and automatically handle the dependency between packages, which is not available in rpm tools

shell

First shell

In computer science, shell is a command interpreter
shell is located between the operating system and the application program, and it is the most important interface between them.
The shell is responsible for interpreting the input command information of the application program to the operating system, and interpreting the results of the operating system instruction processing to the application program

In a word, the shell is a command translation tool between the operating system and the application.

shell in Windows and Linux

  • Windows system: CMD Exe command prompt character
  • Linux system: SH / CSH / KSH / bash (default) /

How to use shell

  • Manual mode

Manually tap the keyboard, directly Enter the command, and press Enter.
Execute the command and display the result of the command execution
Key points: enter the command line by line and confirm the execution line by line

  • Script mode

We write the manually executed command into a file, and then run the file to achieve the effect of executing the command.
This file is called a script file

Write the first shell script

  • Create a new file with the suffix sh
  • Writing content
    #! /bin/bash
    #This is a temporary shell script
    echo 'nihao'
    echo 'hello'
    
  • implement

Comments and variables

notes

  • Single-Line Comments
#!/bin/bash
# This is a single line comment
echo 'hello world'
  • multiline comment
#!/bin/bash
:<<! This is a multiline comment
 multiline comment 
multiline comment 
!
echo 'hello world'
:<<character
	Note Content 
character

variable

  • Define variables
    • Common variable
      • Method 1: variable name = variable value (variable value must be a whole without special characters in the middle)
      • Method 2: variable name = 'variable value' (content in single quotation marks, assignment as is)
      • Method 3: variable name = "variable value" (if there are other variables in double quotation marks, the variable results will be spliced and then assigned)

      Habit: numbers are not enclosed in quotation marks, others are enclosed in double quotation marks by default

    • Command variable (assign the result of the command to the variable)
      • Method 1: variable name = ` command '(here is the backquote < tab >)
      • Method 2: variable name = $(command) (common)
  • Use variables
    • Method 1: $variable name (non-standard writing, easy to use)
    • Mode 2: "$variable name" (non-standard writing, easy to use)
    • Method 3: ${variable name} (use the value of the variable in double quotation marks)
    • Mode 4: "${variable name}" (standard usage)
  • Read only variable: readonly variable name
  • Delete variable: unset variable name

array

Define arrayArray name = (value 1, value 2... Value n)arr=(1 2 3 4 5)
Assign values to the elements of the arrayArray name [index] = valuearr[0]=1
Get element${array name [subscript]}${arr[0]}
Get length${# array name [*]}
${# array name [@]}
${#arr[*]}
${#arr[@]}

operator

operatorexplaingive an example
+additionexpr $a + $b
-subtractionexpr $a - $b
*multiplicationexpr $a \* $b
/divisionexpr $b / $a
%Surplusexpr $b % $a
=assignmenta=$b (assign the value of b variable to a variable)
++ / –Self increasing / self decreasing((a++))

Attention

  1. Native bash does not support simple mathematical operations. It can be implemented by other commands: expr
  2. There should be spaces between expressions and operators
  3. The complete expression should be enclosed in backquotes
  4. * cannot be used directly in multiplication. It needs to be preceded by \ escape

Example: ` expr 2 + 2`

String operator

operatorexplaingive an example
=Check whether two strings are equal, and return true if they are equal[ $a = $b ]
!=Detect whether two strings are not equal, and return true if they are not equal[ $a != $b ]
-zCheck whether the string length is 0, and return true if it is 0[ -z $a ]
-nCheck whether the string length is not 0, and return true if it is not 0[ -n $a ]
$Check whether the string is empty. If not, return true[ $a ]

[] is separated from the code command inside by a space and cannot be pasted together

$? You can get the execution result of the previous statement

In the shell, 0 is true and 1 is false

${# string} get string length

Relational operator

operatorexplaingive an example
-eqCheck whether two numbers are equal, and return true(equals) if they are equal[ $a -eq $b ]
-neCheck whether the two numbers are not equal, and return true (not equal) if they are not equal[ $a -ne $b ]
-gtCheck whether the number on the left is greater than that on the right. If so, return (true creator than)[ $a -gt $b ]
-ltCheck whether the number on the left is less than that on the right. If so, return true(less than)[ $a -lt $b ]
-geCheck whether the number on the left is greater than or equal to that on the right. If so, return true(greater equals)[ $a -ge $b ]
-leCheck whether the number on the left is less than or equal to that on the right. If so, return true (less equal)[ $a -le $b]

Relational operators only support numbers, not strings, unless the value of the string is a number

Boolean operator

operatorexplaingive an example
!Inverse operation[! false] returns true
-oOr operation. If one expression is true, true (or) will be returned[ $a -lt 20 -o $b -gt 100 ]
-aAnd operation, both expressions return true(and) only when they are true[ $a -lt 20 -a $b -gt 100 ]

Logical operator

operatorexplaingive an example
&&Logical AND[[true & & true]] returns true
||Logical OR[[false | false]] return false

Select statement

if syntax

if[ condition ]
then
	Statement body
fi
if [ condition ]
then
	Statement body
else
	Statement body
fi
if [ Condition 1 ]
then
	Statement body
elif [ Condition 2 ]
	Statement body
else
	Statement body
fi

Little practice

#!/bin/bash
# if statement

#The first format of if:
#Find a process. If the process exists, print true
if [ $(ps -ef | grep -c "ssh") -gt 1 ]
then
	echo "true"
fi

case syntax

case value in
 Mode 1 )
	Statement body 1
	;;
Mode 2 )
	Statement body 2
	;;
esac
v="hhxx"
case "${v}" in
"hhxx")
	echo "study hard"
	;;
"ttxs")
	echo "make progress every day"
	;;
esac

Circular statement

for loop

for variable in Range
do
	Circulatory body
done
for loop in A B C
do
	echo $loop
done

while Loop

while condition
do
	Circulatory body
done
a=1
while [ "${a}" -le 10 ]
do
	echo "${a}"
	((a++))
done

function

No parameter, no return value

Function name(){
	Function body
}
test(){
	echo "Function test!"
}
echo "==========="
test
echo "============"

Return value with or without parameters

method(){
	echo "First parameter $1"
	echo "Second parameter $2"
}

method a b

There are parameters and return values

method(){
	echo "Parameter received $1 and $2"
	return $(($1 + $2))
}

method 10 20
echo $?

Little practice

read variable name: indicates that the data entered by the keyboard is assigned to this variable

#!/bin/bash
#Enter two integers on the keyboard in the method and return the sum of the two integers

method(){
        echo "Please enter the first number:"
        read num1
        echo "Please enter the second number:"
        read num2
        echo "The two numbers are: ${num1},${num2}"
        return $(($num1 + $num2))
}

method
echo "The sum of the two numbers is: $?"

Nginx

This part should be HTML + CSS + Nginx, because HTML and CSS were learned before. At that time, I didn't take notes. This part is also quite simple. If you haven't learned, you can search materials and learn by yourself~

summary

  • Nginx is a server software
  • Its core function is that it can be combined with the server hardware, so that the program can be published to the Nginx server for more users to browse

install

  1. Upload compressed package: put nginx compressed package location (press alt+p key in CRT to enter sftp)

  2. Decompress the compressed package: tar -zxvf compressed package name

  3. Enter the decompression Directory: cd nginx decompression directory

  4. Installation dependent environment

    yum -y install pcre pcre-devel

    yum -y install zlib zlib-devel

    yum -y install openssl openssl-devel
    yum -y install gcc

  5. Installing nginx
    ./configure
    make
    Make install (there will be an nginx directory under / usr/local / after installation)

  6. Enter the corresponding directory: cd /usr/local/nginx/sbin

  7. Start nginx service:/ nginx
    Stop:/ nginx -s stop
    Restart:/ nginx -s reload

  8. View nginx service status: ps -ef | grep nginx

  9. Test nginx service: the browser opens the ip address of the corresponding Linux server

Finally, the corresponding ip address cannot be accessed when the browser is opened. Solution:
Step 1: configure the firewall for port 80: firewall CMD -- zone = public -- add port = 80 / TCP -- permanent
Step 2: restart the firewall service: systemctl restart firewalld service
Then access your ip again in the browser, and you should be able to access it.

Publish project

  1. Create a web directory under / home: mkdir web

  2. Upload the project to this directory: put web project compressed package

  3. Unzip the project zip: unzip web application zip

  4. Edit nginx configuration file: VIM / home / nginx-1.18.0/conf/nginx conf
    Find the brace range of server and modify the path of location

  5. Enter the corresponding directory: cd /usr/local/nginx/sbin

  6. Turn off nginx service:/ nginx -s stop

  7. Start nginx service and load configuration file: / usr / local / nginx / SBIN / nginx - C / home / nginx-1.18.0/conf/nginx conf

  8. Test the website through the browser

Java web core

Introduction to enterprise development

Java EE specification

  • Java EE (Java Enterprise Edition): Java Enterprise Edition
  • It is an industrial standard jointly formulated and widely recognized by various manufacturers under the leadership of SUN company.
  • Java EE was called J2EE in the early days, but it did not continue to adopt its naming rules. The version of J2EE starts from 1.0 and ends at 1.4. The JavaEE version starts from the JavaEE 5 version, and the latest version is JavaEE 8.
  • Java EE specification is the general name of many java development technologies. These technical specifications are adopted from J2EE. A total of 13 technical specifications are included.
  • Including: JDBC, JNDI, EJB, RMI, IDL/CORBA, JSP, Servlet, XML, JMS, JTA, JTS, JavaMail, JAF.

WEB overview

summary

  • WEB represents the network in the computer field.
  • Like the WWW we used before, it is the abbreviation of three words of World Wide Web, which is called the world wide web
  • The emergence of network related technology is to enable us to obtain resources in the network world. The storage place of these resources is called website.
  • By entering the address (web address) of the website, we can access the resources provided in the website (regardless of LAN or WAN)

Resource classification

  • Static resources
    The resources provided to people in the website are invariable, that is to say, the content seen by different people or at different times is the same.
    As developers, the HTML, CSS and JavaScript we write belong to static resources.
  • dynamic resource
    The resources provided to people in the website are generated by the program. At different times or different people, the content they see is different due to different identities.
    As a website developer, the JSP and Servlet we write belong to dynamic resources.

System structure

In the previous study, we developed Java projects. These projects are called projects or products in enterprises. All have system architecture!

  • Infrastructure Division
    • CS structure: (Client Server) client + server mode (install different applications directly on the client)
    • BS structure: (Browser Server) browser + server mode
  • Division of technology selection
    • Model1 model
    • Model2 model
    • jsp
    • Three tier architecture + MVC model
  • Deployment mode Division
    • Integrated structure
    • Vertical split structure
    • Distributed structure
    • Microservice architecture

tomcat

The server

  • Server is a kind of computer. It runs faster, has higher load and is more expensive than ordinary computers== The server provides computing or application services for other clients (such as PC, intelligent device, etc.) in the network== The server has high-speed CPU computing power, long-time reliable operation, strong I/O external data throughput and better scalability.
  • The server we are talking about here is actually a web server or an application server. Its essence is a software, which combines with hardware to help us publish applications and let users access our applications through clients.
  • Common application servers
    Server nameexplain
    weblogicIt implements the Java EE specification, a heavyweight server, also known as the Java EE container
    websphereASJava EE specification and heavyweight server are realized
    JBOSSASJava EE specification, heavyweight server, free
    TomcatIt realizes the jsp/servlet specification. It is a lightweight server, open source and free of charge

Tomcat

  • Tomcat is a core project of the Jakarta project team of the Apache Software Foundation, which is jointly developed by Apache, Sun and some other companies and individuals. With the participation and support of Sun, the latest Servlet and JSP specifications can always be reflected in Tomcat. Because Tomcat technology is advanced, stable and free, it is loved by Java enthusiasts and has been recognized by some software developers. It has become a popular Web application server.
  • Tomcat official website: https://tomcat.apache.org/
  • Support required by various versions of Tomcat

Download and install

  • Download: Official Website
  • Installation: just unzip it directly
  • Directory composition
    • bin: some binary executables
    • conf: path to save the configuration file
    • lib: the jar package required by Tomcat during operation
    • logs: log file
    • temp: temporary file
    • webapps: Project publishing directory (a folder represents a web application) (ROOT represents the ROOT project)
    • work: working directory

Basic use

  1. start-up
    startup.bat: startup execution file under Windows
    startup.sh: startup execution file under Linux

    Browser access after startup: http://localhost:8080 You can enter the welcome interface (the default port of Tomcat is 8080)

  2. stop it
    shutdown.bat: close the executable file under Windows
    shutdown.sh: close the executable file under Linux

  3. Deployment project
    Create a folder in the webapps directory
    Put resources in this folder
    Start tomcat and enter the correct path

common problem

  1. Startup problem
    The startup window flashed by: the jdk environment variable was not configured

    java.net.BindException: Port 8080 is occupied

  2. Console garbled code problem solving
    conf-logging.properties
    Modify Java util. logging. ConsoleHandler. encoding = UTF-8

    Tomcat defaults to UTF-8, and CMD command window defaults to GBK. Changing UTF-8 to GBK can solve the problem of garbled code

IDEA integration Tomcat

  1. Click Run - Edit Configurations
  2. Click Defaults - Tomcat Servlet - Local
  3. Click Configure - Tomcat Home - select the path where tomcat is located

Installation under Linux

  1. Upload the compressed package to / home path: put D: / apache-tomcat-9.0.58 tar. gz
  2. Decompress the compressed package: tar -zxvf compressed package name
  3. Enter the bin directory: cd apache-tomcat-9.0.58/bin
  4. Start tomcat service:/ startup.sh
  5. Test with browser: open the browser and the corresponding Linux server ip address: 8080

Java WEB project

  1. Create a new project model and select Java Enterprise
    Determine JDK version and application server version
  2. Right click Add Framework Support
  3. Check the web application option

Detailed explanation of project composition

  • src: store Java source code
  • web: store project related resources (html, css, js, jsp, pictures, etc.)
  • WEB-INFO: store related configuration (web.xml, etc.)

IDEA publishing project

  1. Click Run - Edit Configurations
  2. Click Tomcat Server - Deployment
    Application Context is the project access path, / represents the default path, and there can only be one default path in multiple projects
  3. Click Tomcat Server -
    Set associated browser
    Two Update resources settings
    Set JDK and port number
  4. Start Tomcat service
  5. Validation results (browser)

Publish project through war package

  1. Type the war package under the web path of the project: Jar - CVF myweb war .
  2. Cut the war package to the webapps path of tomcat
  3. Start the tomcat service and automatically decompress the war package
  4. Verification results

configuration file

Configure default port number

Master profile server xml

In the < connector > tag, the port attribute represents the Tomcat default port number (8080)

The default port number of http protocol is 80, which is inconsistent with that of Tomcat. Therefore, the port number needs to be added every time you visit the website
If it is port 80, you do not need to add the port number
When publishing a website, you need to change the default port number of tomcat to 80, so you don't need to add a port number when visiting the website

Configure virtual directory

  • Function: you can publish items in any directory
  1. Edit server XML configuration file, find the < host > tag

  2. Add the following
    <Context path="/mytest" docBase="e:/test" />

    Path: the name of the virtual directory to access the resource (indicating the access path in the browser address bar)
    docBase represents the real path of the project to be published

Configure virtual host

  • Function: you can specify the name of the access path
  1. Edit server XML configuration file, find the < Engine > tag
  2. Add the following

Name: virtual host name
appBase: the root path saved by the project
unpackWARs: whether to automatically decompress the war package
autoDeploy: whether to publish automatically
Context: same as virtual directory

  1. Modify hosts file
    Bind IP address and corresponding domain name
    File path: c:\Windows\System32\drivers\etc

HTTP protocol

summary

  • HTTP(Hyper Text Transfer Protocol): Hypertext Transfer Protocol
  • HTTP protocol is based on TCP/IP protocol (Security)
  • Hypertext: more powerful than normal text (pictures, audio, etc.)
  • Transmission protocol: communication rules between client and server (handshake rules)

component

  • Request: the client initiates a request to the server
  • Response: the server sends a response to the client after receiving the request from the client

In addition to manually initiated requests, JavaScript, CSS, images and other resources will automatically initiate requests

Request for agreement

Components of the request

  1. Request line: request mode submission path (submission parameter) HTTP / version number

  2. Request header

    nameexplain
    AcceptMIME types supported by client browsers
    Accept-EncodingThe compressed encoding format supported by the client browser. The most commonly used is gzip compression
    Accept-LanguageThe language supported by the client browser. Usually zh_CN or en_US et al
    RefererInform the server of the current request
    Content-TypeThe MIME type supported by the request body
    Content-LengthLength of request body
    User-AgentBrowser related information
    ConnectionStatus of the connection. Keep alive keep connected
    If-Modified-SinceThe last modification time of the client browser cache file
    CookieSession management is very important
  3. Request blank line: ordinary line feed, which is used to distinguish the request header from the request body

  4. Request body: only the POST submission method has a request body, which is used to display the submission parameters

Request mode

GET

POST

Only the POST request method has a request body, and the GET request method has no request body
The parameters submitted by get are in the request line, and the parameters submitted by post are in the request body

Protocol response

Components of response

  1. Response line: request method HTTP / version number status code status description
    Common status codes

    Status codeexplain
    200Everything is OK
    302/307Request redirection, two requests, address bar changes
    304The requested resource has not changed, use cache
    404Requested resource not found
    500Server error
  2. Response header

    nameexplain
    LocationThe address requesting redirection is often used with 302307
    ServerServer related information
    Content-TypeMIME type of response body
    Content-LengthLength of response body
    Content-DispositionTell the client browser to open the response body by downloading
    RefreshTimed refresh
    Last-ModifiedLast modification time of server resource
    Set-CookieSession management is very important
    Expires:-1Cache time after server resources to client browser
    Catch-Control:no-catchDo not cache
  3. Response blank line: ordinary line feed, which is used to distinguish between response header and response body

  4. Response body: send the resource file to the client browser for parsing

Publish resource cases

Publish static assets

  1. Create a Java WEB project

  2. Import the resources required by the static page into the web directory of the project

  3. Modify web XML configuration file, modify the default home page

    <!--stay web.xml Join in-->
    <welcome-file-list>
        <welcome-file>/route/file name.html</welcome-file>
    </welcome-file-list>
    
  4. Deploy the project to tomcat

  5. Start tomcat service

  6. Open the browser to view the page

Introduction to Servlet

  • Servlet is a program running on the Java server, which is used to receive and respond to requests from the client based on HTTP protocol.
  • If you want to realize the function of servlet, you can implement javax servlet. Servlet interface or the implementation class that inherits it.
  • Core method: service(), which will be used for any client's request.

Publish Dynamic Assets

  1. Create a Java Web project

  2. Import the resources required by the static page into the web directory of the project

  3. Modify web XML configuration file, modify the default home page

  4. Write a class under the src path of the project to implement the Servlet interface

  5. Rewrite the service method and output one sentence

  6. Modify web XML configuration file to configure servlet related resources

    <!--Servlet statement-->
    <servlet>
        <servlet-name>Custom name</servlet-name>
        <servlet-class>java Full class name (package name).Class name)</servlet-class>
    </servlet>
    
    <!--Servlet mapping-->
    <servlet-mapping>
        <servlet-name>Consistent with the name in the declaration</servlet-name>
        <url-pattern>/Access path(The access path to be entered in the browser address bar)</url-pattern>
    </servlet-mapping>
    
  7. Deploy the project to tomcat

  8. Start tomcat service

  9. Open browser test function

Execution process

  1. Access the specified resource path through the browser
  2. Find the corresponding name tag through URL pattern
  3. Find the corresponding Servlet declaration through name
  4. Find the corresponding Java implementation class in the declaration
  5. Execute service method

Servlet

summary

  • Servlet is a program running on the Java server, which is used to receive and respond to requests from the client based on HTTP protocol
  • It is an interface (javax.servlet.Servlet). Common implementation classes: GenericServlet and httpservlet (inherited from GenericServlet)
  • All client requests will be processed through the service method
  • init method will be called during initialization and destroy method will be called during destruction

Execution process

  1. The client browser sends a request to the Tomcat server
  2. Tomcat server resolves the request address (URL)
  3. Tomcat finds the corresponding item according to the address
  4. Find the web. In the project XML file
  5. Resolve request resource address (URI)
  6. Find the resource of the project (corresponding Java class)
  7. Execute the service method and respond to the client browser

Relational view

Implementation mode

  1. Implement Servlet interface and all abstract methods. This method supports customization to the greatest extent
  2. To inherit the GenericServlet abstract class, the service method must be overridden. Other methods can be overridden. This approach makes it easy for us to develop servlets. But this method has nothing to do with HTTP protocol
  3. To inherit the HttpServlet abstract class, you need to override the doGet and doPost methods. This means that both request and response need to be related to HTTP protocol

life cycle

  • The life cycle of an object is the process from birth to death. That is: birth = alive = dead. The official statement is the process from object creation to destruction
  • Birth: the first time the request reaches the Servlet, the object is created and initialized successfully. Only born once, put the object in memory
  • Alive: during the whole process of providing services by the server, the object always exists, and the service method is executed every time
  • Death: when the server stops or the server goes down, the object dies

The birth corresponds to the init method
The corresponding method is the service method (doGet and doPost methods)
Death corresponds to the destroy method

Conclusion: Servlet objects can only be created once and destroyed once. So the Servlet object has only one instance. If an object instance exists only in the application, it is called singleton mode

Thread safety issues

  • Because the Servlet adopts the single instance design mode, that is, there is only one instance object in the whole application. Therefore, we need to analyze whether the class members in this unique instance object are thread safe
  • Simulate the user login function to check whether the Servlet thread is safe

Conclusion: one browser represents one thread and multiple browsers represent multiple threads. Reasonably speaking, every browser should view its own information. But as a result, the data in the browser is chaotic. Therefore, we can think that servlets are thread unsafe!

Solution: be careful when defining class members. If it is shared, and it will only be assigned during initialization, and it is obtained at other times, it is no problem. If it is not shared, or it is possible to assign a value to it every time it is used, it is necessary to consider the problem of thread safety. You can define it in the doGet or doPost method or use the synchronization function

Mapping mode

  1. How to specify the name. The accessed resource path must be exactly the same as the mapping configuration [common]

    <servlet>
    	<servlet-name>Demo</servlet-name>
    	<servlet-class>study.servlet.Demo</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>Demo</servlet-name>
    	<url-pattern>/Demo</url-pattern>
    </servlet-mapping>
    
  2. /Start with + wildcard. As long as it conforms to the directory structure, it doesn't matter what the end is

    <servlet>
            <servlet-name>Demo2</servlet-name>
            <servlet-class>study.servlet.Demo2</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Demo2</servlet-name>
            <url-pattern>/Demo2/*</url-pattern>
        </servlet-mapping>
    
  3. Wildcard + fixed format ending. As long as it conforms to the fixed end format, the previous path is not considered

    <servlet>
            <servlet-name>Demo2</servlet-name>
            <servlet-class>study.servlet.Demo2</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Demo2</servlet-name>
            <url-pattern>*.test</url-pattern>
        </servlet-mapping>
    

Note: priority issues. The more specific, the higher the priority, and the more fuzzy, the lower the priority. First > second > Third

Multipath mapping

  • We can configure multiple access mappings for a Servlet to realize different functions according to different request paths
  • Scene analysis
    If the accessed resource path is / vip, the commodity price will be reduced by 10%
    If the accessed resource path is / vvip, the commodity price will be reduced by 50%
    If the accessed resource path is other, the commodity price will not be discounted
  • Use the second mapping method to realize multi-path mapping (/ + wildcard)
package study.servlet;

import javax.servlet.ServletException;
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 Demo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get browser path
        String requestURI = req.getRequestURI();
        // Separate path
        String path = requestURI.substring(requestURI.lastIndexOf("/"));
        // Path judgment and price differentiation
        if(path.equals("/vip")){
            System.out.println("100 element");
        }else if(path.equals("/vvip")){
            System.out.println("200 element");
        }else System.out.println("300 element");
    }

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

Creation timing

  1. Created on first visit
    • Advantage: reduce the waste of server memory. The efficiency of server startup is improved
    • Disadvantages: if there are some initialization operations to be done when the application is loaded, it cannot be completed
  2. Created when server loads
    • Advantages: create objects in advance, which improves the efficiency of first execution. You can complete some initialization operations to be completed when the application is loaded
    • Disadvantages: it occupies more memory of the server, which affects the efficiency of server startup
  3. Modify the Servlet creation time. In the < Servlet > tag, add the < load on startup > tag
    <load-on-startup>1</load-on-startup>
    A positive integer represents the creation when the server is loaded. The smaller the value, the higher the priority. A negative integer or no write represents the first access created

Default Servlet

  • The default Servlet is a Servlet provided by the server. It is configured in the web. Com directory of Tomcat's conf directory In XML

  • Its mapping path is < URL pattern > / < URL pattern >. When we send the request, we will first in the web If it is found in the XML configuration, perform the search. However, when the corresponding Servlet path cannot be found, the default Servlet will be found and processed by the default Servlet. So everything is a Servlet

ServletConfig

  • ServletConfig is the configuration parameter object of Servlet. In the specification of Servlet, it is allowed to provide some initialization configuration for each Servlet. Therefore, each Servlet has its own ServletConfig
  • Function: when initializing the Servlet, pass some configuration information (in the form of key value pairs) to the Servlet
  • Life cycle: same as Servlet

collocation method

  • In the < servlet > tag, configure it through the < init param > tag. There are two sub tags
    • < param name >: the key representing the initialization parameter
    • < param value >: value representing initialization parameter
<servlet>
    <servlet-name>servletConfigDemo</servlet-name>
      <servlet-class>study.servlet.servletConfigDemo</servlet-class>
      
    <init-param>
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>desc</param-name>
        <param-value>This is ServletConfig</param-value>
    </init-param>
</servlet>

common method

Return valueMethod nameexplain
StringgetInitParameter(String name)Get the value of the parameter according to the parameter name
EnumerationgetInitParameterNames()Gets an enumeration of all parameter names
StringgetServletName()Gets the name of the Servlet
ServletContextgetServletContext()Get ServletContext object

Assign a value to the ServletConfig object through the init method

private ServletConfig config;
public void init(ServletConfig config) throws ServletException{
	this.config = config;
}

Enumeration item traversal

Enumeration<String> keys = config.getInitParameterNames();
while(keys.hasMoreElements()){
	String key = keys.nextElement();
    String value = config.getInitParameter(key);
    System.out.println(key + "--" + value);
}
// ServletConfigDemo test code
package study.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

public class ServletConfigDemo extends HttpServlet {
    private ServletConfig config;
    // Assign a value to config through the init method to obtain the ServletConfig object
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get value by name
        String encoding = config.getInitParameter("encoding");
        System.out.println("encoding:" + encoding);

        // Get all name s and traverse
        Enumeration<String> names = config.getInitParameterNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            String value = config.getInitParameter(name);
            System.out.println(name + "---" + value);
        }
        // Get servlet name
        String sname = config.getServletName();
        System.out.println("Servlet-name: " + sname);
        // Get ServletContext object
        ServletContext servletContext = config.getServletContext();
        System.out.println(servletContext);
    }

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

ServletContext

  • ServletContext is an application context object (application domain object). There is only one ServletContext object in each application
  • Function: it can configure and obtain the global initialization parameters of the application, and realize the data sharing between servlets
  • Life cycle: the application is created as soon as it is loaded, and the application is destroyed when it is stopped

Domain object

  • Domain object means that the object has a scope, that is, a scope. Domain objects can realize data sharing. The ability to share data is also different for domain objects with different scopes
  • In the Servlet specification, there are four domain objects. ServletContext is one of them. It is also the largest scope in web applications, also known as application domain. It can realize the data sharing between the whole application

collocation method

  • In the < web app > tag, configure it through the < context param > tag. There are two sub tags
    • < param name >: the key representing the global initialization parameter
    • < param value >: represents the value of the global initialization parameter
<context-param>
	<param-name>globalencoding</param-name>
	<param-value>UTF-8</param-value>
</context-param>
<context-param>
	<param-name>globaldesc</param-name>
	<param-value>This is ServletContext</param-value>
</context-param>

common method

Return valueMethod nameexplain
StringgetInitParameter(String name)Get parameters of global configuration by name
StringgetContextPath()Get the access virtual directory of the current application
StringgetRealPath(String path)Obtain the absolute disk path of application deployment according to the virtual directory

The HttpServlet class inherits from the GenericServlet class
There is a getServletContext method in the GenericServlet class, which can directly obtain the ServletContext object

Return valueMethod nameexplain
voidsetAttribute(String name, Object value)Store data to application domain objects
ObjectgetAttribute(String name)Get the data in the application domain object by name
voidremoveAttribute(String name)Remove data from application domain objects by name
package study.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

public class ServletContextDemo extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = req.getServletContext();
        Enumeration<String> names = servletContext.getInitParameterNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            String value = servletContext.getInitParameter(name);
            System.out.println(name + "====" + value);

        }
        resp.setContentType("text/html;charset=UTF-8");
        String contextPath = servletContext.getContextPath();
        String realPath = servletContext.getRealPath(contextPath);
        PrintWriter pw = resp.getWriter();
        pw.write("The virtual directory is:" + contextPath + "<br>");
        pw.write("The real directory is:" + realPath);

        servletContext.setAttribute("use","lisi");
    }

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

Annotation development

Servlet3.0 specification

  • We are using Tomcat 9. The requirement of Java EE specification is 8 The corresponding Servlet version should be 4 X version. However, in enterprise development, stability is far more important than the pursuit of new versions. Therefore, we will reduce the use of version and use Servlet version 3.1.
  • In fact, all our previous operations are based on servlet version 2.5 specification, that is, with the help of configuration files. Later, with the gradual evolution of software development, annotation based configuration became popular. Servlet version 3.0 also supports annotation development
  • Servlet version 3.0 not only retains the configuration mode of version 2.5, but also supports a new annotation configuration mode. It can completely eliminate the need for web XML configuration file can realize the configuration of servlet, and there are some other new features.

Automatic annotation development

Implementation steps

  1. Create a web project
  2. Define a class that inherits HttpServlet
  3. Override doGet and doPost methods
  4. Use the @ WebServlet annotation on the class and configure the Servlet
  5. Deploy and start the project
  6. Test by browser
@WebServlet("/servletDemo")
public class ServletDemo extends HttpServlet{
    
}

Create containers manually (understand)

  • In addition to the configuration mode of automatic annotation, Servlet 3.0 specification also supports the mode of manually creating Servlet containers. If used, its writing specification must be followed. In version 3.0, a new interface is added: ServletContainerInitializer, which needs to override the onStartup method

step

  1. Define a class that inherits HttpServlet

  2. Override doGet and doPost methods

  3. Define a class that implements the ServletContainerInitializer interface

  4. Create a META-INF package in the src directory

  5. Create a package of services under META-INF package

  6. Create a javax. XML file under the services package servlet. File for servletcontainerinitializer

  7. The content in the file is the full class name of the container implementation class

  8. Complete the Servlet registration in the onStartup method in the container implementation class

    public void onStartup(Set<Class<?>> set, ServletContext servletContext){
        // 1. Create the object of ServletDemo class
        ServletDemo servletDemo = new ServletDemo();
        // 2. Add a Servlet to the ServletContext object and get the dynamic configuration object of the Servlet
        ServletRegistration.Dynamic registration = servletContext.addServlet("ServletDemo", servletDemo);
        // 3. Configure Servlet
        registration.addMapping("/servletDemo");	// Map the path to access the resource
        registration.setLoadOnStartup(1);	// Set Servlet loading time
    }
    
  9. Deploy and start the project

  10. Test by browser

Student management system 1

  • Requirements: add student information to the local file in the Java server

step

  1. Create a web project
  2. Create an html file for saving student information
  3. Create a class that inherits HttpServlet
  4. Override doGet and doPost methods
  5. On the web Modify the default home page and configure the Servlet in the XML file
  6. In the doGet method, receive the form data, save it to a file, and respond to the browser results
  7. Deploy and start the project
  8. Test by browser

Get form data
req.getParameter(name value): you can obtain the corresponding form data through the name attribute of the form through the method in the HttpServletRequest object

Response data
PrintWriter pw = resp.getWriter(): get the output stream object through the method in the HttpServletResponse object
pw.println("Save Success"): respond the specified content to the browser

<!--studentAdd.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add student</title>
</head>
<body>
    <form action="/add" method="get">
        full name:<input type="text" name="username"> <br>
        Age:<input type="number" name="age"> <br>
        Achievements:<input type="number" name="score">   <br>
        <button type="submit">add to</button>
    </form>
</body>
</html>
<!--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">
    <!--Configure home page-->
    <welcome-file-list>
        <welcome-file>/studentAdd.html</welcome-file>
    </welcome-file-list>
    <!--Servlet statement-->
    <servlet>
        <servlet-name>StudentServlet</servlet-name>
        <servlet-class>studentServlet.add</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>StudentServlet</servlet-name>
        <url-pattern>/add</url-pattern>
    </servlet-mapping>
</web-app>
// add.java
package studentServlet;

import studentServlet.bean.Student;

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

public class add extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get the corresponding form content
        String username = req.getParameter("username");
        String age = req.getParameter("age");
        String score = req.getParameter("score");
        // Encapsulate student objects
        Student stu = new Student(username, Integer.parseInt(age), Integer.parseInt(score));
        // Save to local file
        BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\Java\\code\\StudentServlet\\stu.txt",true));
        bw.write(stu.getUsername() + "," + stu.getAge() + "," + stu.getScore());
        bw.newLine();
        bw.close();

        // Respond to browser
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.println("After adding successfully, you will jump to the home page in 3 seconds!!!");
        resp.setHeader("Refresh","3;url=/index.html");
        pw.close();
    }

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

Request object

Request: get resources. In BS architecture, the client browser sends a query to the server.

Request object: the object used to send the request in the project (ServletRequest and HttpServletRequest)

ServletRequest and HttpServletRequest are both interfaces, but Tomcat server will help us deal with the assignment of implementation classes. We don't need to care about these

Get various paths

Return valueMethod nameexplain
StringgetContextPath()Get virtual directory name
StringgetServletPath()Get Servlet mapping path
StringgetRemoteAddr()Get visitor ip address
StringgetQueryString()Get the requested message data
StringgetRequestURI()Get uniform resource identifier
StringBuffergetRequestURL()Get uniform resource locator
package study.servlet;

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

@WebServlet("/request")
public class RequestDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String contextPath = req.getContextPath();
        String servletPath = req.getServletPath();
        String remoteAddr = req.getRemoteAddr();
        String queryString = req.getQueryString();
        String requestURI = req.getRequestURI();
        StringBuffer requestURL = req.getRequestURL();

        PrintWriter pw = resp.getWriter();
        pw.println("contextPath= " + contextPath);
        pw.println("servletPath= " + servletPath);
        pw.println("remoteAddr= " + remoteAddr);
        pw.println("queryString= " + queryString);
        pw.println("requestURI= " + requestURI);
        pw.println("requestURL= " + requestURL);
    }

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

Get request header

Return valueMethod nameexplain
StringgetHeader(String name)Get a value based on the request header name
EnumerationgetHeaders(String name)Get multiple values according to the request header name
EnumerationgetHeaderNames()Get all request header names
package study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

@WebServlet("/request2")
public class RequestDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getHeader("host"));
        System.out.println(req.getHeader("user-agent"));
        Enumeration<String> headers = req.getHeaders("user-agent");
        while(headers.hasMoreElements()){
            String s = headers.nextElement();
            System.out.println(s);
        }
        System.out.println("===============");
        Enumeration<String> names = req.getHeaderNames();
        while(names.hasMoreElements()){
            System.out.println(names.nextElement());
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

Get request parameter information

Return valueMethod nameexplain
StringgetParameter(String name)Get data by name
String[]getParameterValues(String name)Get all data by name
EnumerationgetParameterNames()Get all names
Map<String,String[]>getParameterMap()Get key value pairs of all parameters
package study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebServlet("/request3")
public class RequestDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getParameter("username"));
        System.out.println("================");
        for (String hobby : req.getParameterValues("hobby")) {
            System.out.println(hobby);
        }
        System.out.println("===================");
        Enumeration<String> parameterNames = req.getParameterNames();
        while(parameterNames.hasMoreElements()){
            String name = parameterNames.nextElement();
            for (String value : req.getParameterValues(name)) {
                System.out.println(value);
            }
        }
        System.out.println("===================");
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (String key : parameterMap.keySet()) {
            String[] value = parameterMap.get(key);
            System.out.println(key + " === " + value);
        }
    }

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

Get request parameters and encapsulate objects

  1. Manual packaging mode
    The member variable name is consistent with the parameter name attribute value
  2. Reflection packaging mode
    Property descriptor: propertydescriptor (get the corresponding get and set methods in the object by name)
  3. Tool class encapsulation method
    Beautils tool class, populate method
    Before publishing, you also need to enter file project structure
package study.servlet;

import study.servlet.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/*
*   Encapsulation object ----- reflection mode
* */
public class RequestDemo5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get all data
        Map<String, String[]> map = req.getParameterMap();
        // Encapsulate student objects
        Student stu = new Student();
        // Traversal set
        for(String name : map.keySet()){
            String[] value = map.get(name);
            try {
                // Gets the property descriptor of the Student object
                PropertyDescriptor pd = new PropertyDescriptor(name, stu.getClass());
                // Get the corresponding set method
                Method writeMethod = pd.getWriteMethod();
                // Execution method
                writeMethod.invoke(stu,value);
            } catch (IntrospectionException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
package study.servlet;

import org.apache.commons.beanutils.BeanUtils;
import study.servlet.bean.Student;

/*
*   Encapsulate object ----- tool class method
	Import package required: BeanUtils
* */
public class RequestDemo6 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get all data
        Map<String, String[]> map = req.getParameterMap();
        // Encapsulate student objects
        Student stu = new Student();
        try {
            BeanUtils.populate(stu, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

Get request information from stream object

Return valueMethod nameexplain
BufferedReadergetReader()Get character input stream
ServletInputStreamgetInputStream()Get byte input stream

When using the IO stream to obtain request information, the get method is not supported, and only the post submission method is supported
The obtained stream objects are not new by themselves. There is no need to close to release resources. They will be processed and released by the request object

package study.servlet;

import org.apache.commons.beanutils.BeanUtils;
import study.servlet.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/*
*   Get data from stream object
* */
@WebServlet("/request7")
public class RequestDemo7 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Character stream (must be post request mode)
        BufferedReader br = req.getReader();
        String line;
        while((line = br.readLine()) != null) System.out.println(line);
        
        // Byte stream
        ServletInputStream is = req.getInputStream();
        byte[] arr = new byte[1024];
        int len;
        while((len = is.read(arr)) != -1){
            System.out.println(new String(arr, 0, len));
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

Chinese garbled code problem

  • GET mode
    There is no garbled code problem. It has been solved after Tomcat 8
  • POST mode
    The problem of garbled code can be solved by setCharacterEncoding() method (the coding format should be consistent with the page coding format)
package study.servlet;

/*
*   Chinese garbled code problem
* */
@WebServlet("/request8")
public class RequestDemo8 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        System.out.println(name);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

Request domain

  • Request domain: data can be shared within the scope of one request.
  • It is generally used to share data among multiple resources requesting forwarding
  • Request object operation shared data method
    Return valueMethod nameexplain
    voidsetAttribute(String name, Object value)Store data in the request domain object
    ObjectgetAttribute(String name)Get the data in the request domain object by name
    voidremoveAttribute(String name)Remove data from the request domain object by name

Request forwarding

  • Request forwarding: after A request from the client arrives, it is found that it needs to use other servlets to realize the function (browser request, A finds that it can't do it, and forwards it to B)
  • characteristic
    • The browser address bar remains unchanged
    • Data in the domain object is not lost
    • The response body of the Servlet responsible for forwarding will be lost before and after forwarding
    • The forwarding destination responds to the client
Return valueMethod nameexplain
RequestDispatchergetRequestDispatcher(String name)Get request scheduling object
voidforward(ServletRequest req, ServletResponse resp)Realize forwarding (call with request scheduling object)
package study.servlet.request;

/*
*   Request forwarding
* */
@WebServlet("/request9")
public class RequestDemo9 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Set up shared data
        req.setAttribute("name","Zhang San");
        // Get request scheduling object
        RequestDispatcher rd = req.getRequestDispatcher("/request10");
        // Request forwarding
        rd.forward(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
package study.servlet.request;

/*
*   Forwarding purpose
* */
@WebServlet("/request10")
public class RequestDemo10 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get shared data
        System.out.println(req.getAttribute("name"));
    }

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

Request contains

  • The request includes: you can combine the functions in other servlets to respond to the client together (for browser requests, A can only do half, and B can do the other half)
  • characteristic
    • The browser address bar remains unchanged
    • Data in the domain object is not lost
    • The contained Servlet response header will be lost
Return valueMethod nameexplain
RequestDispatchergetRequestDispatcher(String name)Get request scheduling object
voidinclude(ServletRequest req, ServletResponse resp)Implementation includes
package study.servlet.request;

/*
*   Request contains
* */
@WebServlet("/request11")
public class RequestDemo11 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Set up shared data
        req.setAttribute("name","Zhang San");
        // Get request scheduling object
        RequestDispatcher rd = req.getRequestDispatcher("/request10");
        // Request forwarding
        rd.include(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

Response object

  • Response: feedback results. In BS architecture, the server feeds back the results to the client browser
  • Response object: the object used to send the response in the project
    ServletResponse (Interface)
    HttpServletResponse (inherited from ServletResponse, an interface based on http protocol)

    Like the request object, we don't need to write the implementation class. It is created in the Tomcat server. When the doGet or doPost method is executed, the server will pass the corresponding implementation class object

Common status codes

Status codeexplain
200success
302redirect
304The requested resource has not changed, use cache
400Request error, common in request parameter error
404Requested resource not found
405The request method is not supported
500Server error

Byte stream response message

Return valueMethod nameexplain
ServletOutputStreamgetOutputStream()Get response byte output stream object
voidsetContentType("text/html;charset=UTF-8")Set the response content type to solve the problem of Chinese garbled code

Steps:

  1. Get byte output stream object
  2. Define a message (a string)
  3. Output via byte stream object

The obtained byte output stream object does not need to be close d and will be processed and released by the response object

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// Get byte output stream
	ServletOutputStream os = resp.getOutputStream();
    String s = "Byte output stream response message";
    os.write(s.getBytes());
}

There is no garbled code problem: the browser defaults to gbk code and idea defaults to UTF-8 code; However, when the getBytes method converts a string into a byte array, if the code specified by the parameter is not passed, it will be converted according to the default code of the current system platform. The default code of the Windows system is gbk, which is consistent with the browser, so there is no garbled code

// The unified coding format is UTF-8 and the problem of garbled code is solved
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// Set the corresponding content type and set the encoding format (inform the browser of the encoding format that should be adopted)
	resp.setContentType("text/html;charset=UTF-8");
	// Get byte output stream
	ServletOutputStream os = resp.getOutputStream();
	String s = "Byte output stream response message";
	os.write(s.getBytes("UTF-8"));
}

Character stream response message

Return valueMethod nameexplain
PrintWritergetWriter()Gets the response character output stream object
voidsetContentType("text/html;charset=UTF-8")Set the response content type to solve the problem of Chinese garbled code

The step is the same as the byte stream above. You also do not need to close to release resources

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// Set the corresponding content type and set the encoding format (inform the browser of the encoding format that should be adopted)
	resp.setContentType("text/html;charset=UTF-8");
	// Get character output stream object
	PrintWriter pw = resp.getWriter();
	pw.write("Character output stream response message");
}

Response picture

  1. Get the absolute path through the relative path of the file (getRealPath)
  2. Create a byte input stream object and associate the read picture path
  3. Get byte output stream object through response object
  4. Loop reading and writing pictures
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String realPath = getServletContext().getRealPath("/img/tx.png");
	// Create byte input stream object and associate pictures
	BufferedInputStream is = new BufferedInputStream(new FileInputStream(realPath));
	// Get byte output stream object, response picture
	ServletOutputStream os = resp.getOutputStream();
	// Cyclic reading and writing
	byte[] arr = new byte[1024];
	int len;
	while((len = is.read(arr)) != -1){
		os.write(arr, 0, len);
	}
	// Release resources
	is.close();
}

Set cache

  • Cache: for data that does not change frequently, we can set a reasonable cache time to avoid frequent requests from the browser to the server. To improve efficiency
Return valueMethod nameexplain
voidsetDateHeader(String name,long time)Set header add cache

Example: resp setDateHeader("Expires",System.currentTimeMillis() + 1*60*60*1000); Set one hour cache time
Expires means expired
The unit of time is milliseconds, and one second is equal to 1000 milliseconds

Timed refresh

  • Regular refresh: after the specified time, the page will jump automatically
Return valueMethod nameexplain
voidsetHeader(String name,String value)Set regular refresh of message header

Example: resp Setheader ("Refresh", "3; url = path to jump")
In seconds

request redirections

  • Request redirection: after a request from the client arrives, it is found that other servlets are needed to realize the function
  • Features: the address bar of the browser will change. Two requests can be made. Data cannot be shared in the request domain object, and can be redirected to other servers
  • Implementation principle of redirection
    1. Set the response status code to 302: resp setStatus(302);
    2. Set the resource path of the response (where the response goes is specified by the response header location): resp setHeader("location","/response/responseDemo")
  • Response object redirection method
    Return valueMethod nameexplain
    voidsendRedirect(String name)Set redirection

File download

  1. Create a byte input stream and associate the read file
  2. Set the supported type of response header: resp setHeader("Content-Type","application/octet-stream")
    Content type: header name, representing the supported type
    Application / octet stream: message header parameter, representing that the type of application is byte stream
  3. Set the response header to open the resource by downloading: resp Setheader ("content disposition", "attachment; filename = name of downloaded file")
    Content disposition: header name, representing the processing form
    attachment;filename=xxx: message header parameter, which represents processing in the form of attachment, and filename represents the name of the specified downloaded file
  4. Get byte output stream object through response object
  5. Cyclic reading and writing
  6. Release resources
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// Create a byte input stream and associate the read file
	String realPath = req.getServletContext().getRealPath("/img/tx.png");
	BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));
	// Set the supported types of response headers
	resp.setHeader("Content-Type", "application/octet-stream");
	// Set the response header to open the resource by downloading
	resp.setHeader("Content-Disposition","attachment;filename=file.png");
	// Get byte output stream object through response object
	ServletOutputStream os = resp.getOutputStream();
	int len;
	byte[] arr = new byte[1024];
	while((len = bis.read(arr)) != -1){
		os.write(arr, 0, len);
	}
	// Release resources
	bis.close();
}

Student management system 2

  • Resource preparation
    1. Create a web project
    2. Create an index in the web directory HTML with two hyperlink tags (add student, view student)
    3. Create an addstudent. Net in the web directory The function of adding HTML pages
    4. Create a Student class under src to encapsulate Student information
// list.java
package studentServlet;

import studentServlet.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
@WebServlet("/list")
public class list extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader br = new BufferedReader(new FileReader("E:\\Java\\code\\StudentServlet\\stu.txt"));
        ArrayList<Student> list = new ArrayList<>();
        String str;
        while((str = br.readLine()) != null){
            String[] split = str.split(",");
            Student stu = new Student(split[0], Integer.parseInt(split[1]), Integer.parseInt(split[2]));
            list.add(stu);
        }
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        for(Student student : list){
            pw.write(student.getUsername() + "," + student.getAge() + "," + student.getScore());
            pw.write("<br>");
        }
        br.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student information management system</title>
</head>
<body>
    <h1>Student information management system</h1>
    <hr>
    <a href="/studentAdd.html">Add student information</a>
    <a href="/list">View student information</a>
</body>
</html>

Cookie

conversation

  • Session: multiple requests and responses between browser and server
  • In order to realize some functions, multiple requests and responses may be generated between the browser and the server, from the browser accessing the server to the end of accessing the server (closing the browser and expiration time). The multiple requests and responses generated during this period are called a session between the browser and the server
  • Some data generated during the session can be saved through session Technology (Cookie and Session).

summary

  • Cookie: client session management technology
    Save the data to be shared to the client
    Each time, the session information is brought to the server, so as to realize the data sharing of multiple requests
  • Function: it can save the relevant content of the website visited by the client, so as to ensure that it is obtained from the local cache first during each visit, so as to improve efficiency
  • characteristic:
    • Is an ordinary Java class
    • Two required attributes: name and value
    • Send: httpservletresponse Addcookie (cookie object)
    • Each website can have up to 20 cookies, the total number of cookies stored in the browser is no more than 300, and the size of each Cookie is limited to 4kb
    • Get all Cookie objects: HttpServletRequest getCookie()

Cookie properties

Attribute nameeffectIs it important
nameThe name of the CookieRequired attribute
valueValue of Cookie (Chinese is not supported)Required attribute
pathPath to Cookieimportant
domainThe domain name of the Cookieimportant
maxAgeCookie lifetime (s)important
versionThe version number of the Cookieunimportance
commentDescription of the Cookieunimportance

method

Method nameeffect
Cookie(String name, String value)Creating objects using construction methods
set and get methods corresponding to propertyAssign and get values (name is decorated with final, no set method)
  • Add a cookie to the client: void httpservletresponse addCookie(Cookie cookie)
  • Get all cookies: Cookie [] HttpServletRequest getCookies()

practice

  • Requirement Description: record the last access time through Cookie and display it on the browser
  • Ultimate goal: master the basic use of cookies, from creating to adding clients, and then to obtaining cookies from servers
  • Implementation steps
    1. Write a prompt message through the response object
    2. Create a Cookie object and specify name and value
    3. Set the maximum Cookie lifetime
    4. Adds a Cookie object to the client through a response object
    5. Get Cookie object through request object
    6. Write out the access time in the Cookie object
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// Write a prompt message through the response object
	resp.setContentType("text/html;charset=UTF-8");
	PrintWriter pw = resp.getWriter();
	pw.write("Your last visit was:");
	pw.write("<br>");
	// Create a Cookie object and specify name and value
	Cookie cookie = new Cookie("time", System.currentTimeMillis()+"");
	// Set the maximum Cookie lifetime
	cookie.setMaxAge(3600);
	// Adds a Cookie object to the client through a response object
	resp.addCookie(cookie);
	// Get Cookie object through request object
	Cookie[] cookies = req.getCookies();
	// Write out the access time in the Cookie object
	for(Cookie ck : cookies){
		if("time".equals(ck.getName())){
			String value = ck.getValue();
			// Format time
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String lastTime = sdf.format(new Date(Long.parseLong(value)));
			pw.write(lastTime);
		}
	}
}

matters needing attention

  • Quantity limit
    Each website can only use 20 cookies at most, and the size cannot exceed 4kb. The total number of cookies on all websites shall not exceed 300
  • Name restrictions
    The name of the Cookie can only contain alphanumeric characters in the ASCII code table. Cannot contain commas, semicolons, spaces, or start with $.
    The value of the Cookie does not support Chinese
  • Lifetime limit: the setMaxAge() method receives numbers
    Negative integer: the current session is valid and cleared when the browser is closed (default)
    0: clear now
    Positive integer: sets the survival time in seconds
  • Access path restrictions
    Resource path prefix from the first access
    As long as you start with this prefix (including child paths), you can get it. Otherwise, you can't get it
    Set path: setPath() method sets the specified path

Session

  • HttpSession: server-side session management technology
    The essence is to adopt client session management technology

    Only a special ID is saved on the client side, and the shared data is saved to the memory object on the server side.
    Each time a request is made, a special ID will be brought to the server, and the corresponding memory space will be found according to this ID, so as to realize data sharing
    Session domain object is one of the four domain objects in Servlet specification

  • Function: data sharing can be realized
    Domain objectfunctioneffect
    ServletContextApplication domainRealize data sharing among the whole application
    ServletRequestRequest domainData sharing between current requests or request forwarding
    HttpSessionSession domainData sharing between current session scopes

common method

Return valueMethod nameexplain
voidsetAttribute(String name, Object value)Set up shared data
ObjectgetAttribute(String name)Get shared data
voidremoveAttribute(String name)Remove shared data
StringgetId()Get unique identification name
voidInvalidate()Make the session fail immediately

Object acquisition

  • HttpSession is an interface, and the corresponding implementation class object is obtained through the HttpServletRequest object
    Return valueMethod nameexplain
    HttpSessiongetSession()Get HttpSession object
    HttpSessiongetSession(boolean create)Gets the HttpSession object, but does not get whether to create it automatically (true by default)

practice

  • Requirement Description: set the shared data user name through the first Servlet and obtain it in the second Servlet
  • Ultimate goal: master the basic use of HttpSession and how to obtain and use it
  • Implementation steps
    1. Get the requested user name in the first Servlet
    2. Get HttpSession object
    3. Set user name to shared data
    4. Get the HttpSession object in the second Servlet
    5. Get shared data user name
    6. Respond the obtained user name to the client browser
// Session01
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// Get the requested user name in the first Servlet
	String username = req.getParameter("username");
	// Get HttpSession object
	HttpSession session = req.getSession();
	// Set user name to shared data
	session.setAttribute("username",username);
}
// session02
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// Get the HttpSession object in the second Servlet
	HttpSession session = req.getSession();
	// Get shared data user name
	Object username = session.getAttribute("username");
	// Respond the obtained user name to the client browser
	PrintWriter pw = resp.getWriter();
	pw.write(username+"");
}

matters needing attention

  • View of unique identification: with the help of browser developer tools
  • Browser disable cookies
    Method 1: inform users of the solutions adopted by most websites through prompt information [recommended]
    Method 2: through resp The enconerurl method implements url rewriting (splicing jsessionid in the address bar) [understand]
  • Passivation and activation
    • Passivation: serialization. Serialize the HttpSession that has not been used for a long time but has not expired, and write it to disk
    • Activation: the opposite state
  • Passivation time
    The first case: when the number of accesses is large, the server will sort according to getLastAccessTime and serialize httpsessions that have not been used for a long time but have not reached the expiration time
    The second case: when the server is restarted, it should also be serialized in order to maintain the data in the client HttpSession

The serialization of HttpSession is automatically completed by the server. We don't need to care

JSP

  • JSP(Java Server Pages): is a dynamic web page technical standard
  • JSP deployed on the server can process the request sent by the client, dynamically generate Web pages of HTML, XML or other format documents according to the request content, and then respond to the client.
  • Jsp is based on Java language, and its essence is Servlet
categoryUsage scenario
HTMLStatic resources cannot be developed and dynamic resources cannot be added
CSSBeautify page
JavaScriptAdd some dynamic effects to the web page
ServletWrite Java code to realize background function processing
JSPIt includes display page technology and Java code function

quick get start

  1. Create a web project
  2. Create an index in the web directory JSP file
  3. Write a sentence in the file as follows: This is my first jsp
  4. Deploy and start the project
  5. Test by browser
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    first jsp
</body>
</html>

Execution process

  1. The client browser sends a request to the Tomcat server
  2. The Tomcat server resolves the requested address
  3. Find specific applications
  4. Find the corresponding jsp file
  5. Translate jsp files into java file
  6. Compiling Java files
  7. Response to client

Document content introduction

  • Generated Java file directory
    Inherits from HttpJspBase class, while HttpJspBase inherits from HttpServlet(JSP is essentially a Servlet)
    The essence of jsp display page is to get the output stream object and write it out through write

grammar

  • JSP comment: <% -- content of comment --% >
  • Java code block: <% java code% >
  • Expression: <% = JSP expression: <% >
  • JSP declaration: <%! Declare variable or method% >

System.out.println(): normal output statement, which is output on the console
out.println(): JspWriter object, which outputs the content on the browser page without automatic line wrapping
<% = "content to output"% > is equivalent to out Println ("what to output")
In the statement, if you add!, Represents the declared member variable; If not!, Represents that the declared is a local variable; If it is a declaration method, it must be added!

instructions

  • Page instruction: <% @ page attribute name = attribute value attribute name = attribute value...% >
    Attribute nameeffect
    contentTypeTypes and encoding formats supported by the response body
    languageThe default language is Java
    errorPageJump to the page after the current page has an exception
    isErrorPageWhether to catch the exception. If true, the exception object can be used in the page. The default is false
    importimport = "java.util.ArrayList"
    sessionWhether to create an HttpSession object. The default is true
    bufferSet the size of JspWriter output jsp content cache, which is 8kb by default
    pageEncodingThe encoding format used when translating jsp
    isEIgnoredWhether to ignore EL expression. The default is false
  • include instruction: other pages can be included
    <% @ include file = included pages% >
  • taglib instruction: external tag library can be introduced
    <% @ taglib URI = address of tag library prefix = prefix name% >

matters needing attention

  • Nine implicit objects (you can use them directly without creating them)
    Implicit object nameRepresents the actual object
    requestjavax.servlet.http.HttpServletRequest
    responsejavax.servlet.http.HttpServletResponse
    sessionjavax.servlet.http.HttpSession
    applicationjavax.servlet.ServletContext
    pagejava.lang.Object
    configjavax.servlet.ServletConfig
    exceptionjava.lang.Throwable
    outjavax.servlet.jsp.JspWriter
    pageContextjavax.servlet.jsp.PageContext
  • PageContext object
    • It is unique to JSP and not in Servlet
    • Page domain object is one of the four domain objects. You can also manipulate the properties in the other three domain objects
    • You can get eight other implicit objects
    • The life cycle exists with the creation of JSP and disappears with the end of JSP. Each JSP page has a PageContext object

Four domain objects

Domain object nameRangelevelremarks
PageContextpage rangeMinimum, can only be used on the current pageBecause the scope is too small, it is rarely used in development
ServletRequestRequest scopeFor one request or current request forwardingAfter the request is forwarded, the request domain is lost when it is forwarded again
HttpSessionSession scopeUsed when data sharing is requested multiple timesMultiple requests to share data, but different clients cannot share
ServletContextScope of applicationMaximum, the whole application can be usedUse as little as possible. If the data is modified, it needs to be synchronized

jsp

  • M(Model): model. Used to encapsulate data, encapsulating the data model
  • V(View): view. It is used to display data. JSP pages are used for dynamic resources and HTML pages are used for static resources
  • C(Controller): controller. Used to process requests and responses, such as servlets

Student management system 3

Login function

  1. Create a web directory
  2. Create an index in the web directory jsp
  3. Get the user name in the session domain on the page, display the hyperlink of adding and viewing function when you get it, and display the hyperlink of login function when you don't get it
  4. Create a login in the web directory jsp. Implement login page
  5. Create LoginServlet and get user name and password
  6. If the user name is empty, redirect to the login page
  7. If it is not empty, add the user name to the session domain and redirect to the home page
<%-- login.jsp --%>
<%--
  Created by IntelliJ IDEA.
  User: lihao
  Date: 2022/2/24
  Time: 20:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign in</title>
</head>
<body>
<h1>Student information management system--Sign in</h1>
<hr>
<form action="/login" method="post">
    user name:<input type="text" name="username">
    password:<input type="password" name="password">
    <button type="submit">Sign in</button>
</form>
</body>
</html>
// login.java
package studentServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setContentType("text/html;charset=UTF-8");
        if(null == username || "".equals(username)){
            resp.getWriter().write("Account number cannot be blank, please re-enter (2) s Return after...)");
            resp.setHeader("Refresh","2;URL=/login.jsp");
        }else{
            if("admin".equals(username) && "abc123".equals(password)){
                session.setAttribute("username",username);
                resp.sendRedirect("/index.jsp");
            }else{
                resp.getWriter().write("Incorrect password (2) s Return after...)");
                resp.setHeader("Refresh","2;URL=/login.jsp");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
<%-- index.jsp --%>
<%--
  Created by IntelliJ IDEA.
  User: lihao
  Date: 2022/2/24
  Time: 19:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Student information management system</title>
</head>
<body>
    <h1>Student information management system</h1>
    <hr>
    <% if(session.getAttribute("username") == null){ %>
    <a href="/login.jsp">Please login</a>
    <% } else { %>
    <a href="/add.jsp">Add student information</a>
    <a href="/list">View student information</a>
    <% } %>
</body>
</html>
<%-- list.jsp --%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="studentServlet.bean.Student" %>
<%--
  Created by IntelliJ IDEA.
  User: lihao
  Date: 2022/2/24
  Time: 20:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>View students</title>
</head>
<body>
    <table width="600px" border="1px" align="center">
        <tr>
            <th>full name</th>
            <th>Age</th>
            <th>achievement</th>
        </tr>
        <%
            ArrayList<Student> students = (ArrayList<Student>) session.getAttribute("students");
            for(Student stu : students){
        %>
            <tr>
                <td><%=stu.getUsername()%></td>
                <td><%=stu.getAge()%></td>
                <td><%=stu.getScore()%></td>
            </tr>
        <% } %>
    </table>
</body>
</html>
// list.java
package studentServlet;

import studentServlet.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
@WebServlet("/list")
public class list extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader br = new BufferedReader(new FileReader("E:\\Java\\code\\StudentServlet\\stu.txt"));
        ArrayList<Student> list = new ArrayList<>();
        String str;
        while((str = br.readLine()) != null){
            String[] split = str.split(",");
            Student stu = new Student(split[0], Integer.parseInt(split[1]), Integer.parseInt(split[2]));
            list.add(stu);
        }
        req.getSession().setAttribute("students",list);
        resp.sendRedirect("/list.jsp");
    }

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

EL expression

  • EL(Expression Language): expression language
  • The content added in JSP 2.0 specification is also a part of Servlet specification
  • Function: get data in the JSP page and separate our JSP from Java code blocks and JSP expressions
  • Syntax: ${expression content}

quick get start

  1. Create a web project
  2. Create jsp file in web Directory
  3. Adding data to a domain object in a file
  4. Three methods are used to obtain the data in the domain object (Java code block, JSP expression, EL expression)
  5. Deploy and start the project
  6. Test by browser
<%--
  Created by IntelliJ IDEA.
  User: lihao
  Date: 2022/2/25
  Time: 10:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL Getting started with expressions</title>
</head>
<body>
    <% request.setAttribute("username","zhangsan"); %>

    <%--java Code block--%>
    <% out.println(request.getAttribute("username")); %><br>
    <%-- jsp expression --%>
    <%=request.getAttribute("username")%><br>
    <%--EL expression--%>
    ${username}
</body>
</html>

get data

  1. Get data of basic data type
    ${data name}
  2. Get data of custom object type
    ${object name. Property name}
    Here, the principle of obtaining the member variables of the object is to obtain them by calling the get method, so there is no need to worry about private
  3. Get data of array type
    ${array name [index]}
  4. Get data of List collection type
    ${set [index]}
  5. Get data of Map collection type
    ${set. Key value}: get the value corresponding to the key
<%@ page import="study.servlet.bean.Student" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.HashMap" %><%--
  Created by IntelliJ IDEA.
  User: lihao
  Date: 2022/2/25
  Time: 10:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL Get data from expression</title>
</head>
<body>
    <%
        Student stu = new Student("Zhang San",23);
        int[] arr = {1,2,3,4,5};
        ArrayList<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        HashMap<String,String> map = new HashMap<>();
        map.put("user","zhangsan");
        map.put("age","28");
        pageContext.setAttribute("stu",stu);
        pageContext.setAttribute("arr",arr);
        pageContext.setAttribute("list",list);
        pageContext.setAttribute("map",map);
    %>
    <%--EL Get data from expression--%>
    ${stu.name}<br>     <%--Get data of custom object type--%>
    ${arr[2]}<br>       <%--Get data of array type--%>
    ${list[1]}<br>      <%--obtain List Data of collection type--%>
    ${map.user}         <%--obtain Map Data of collection type--%>
</body>
</html>

matters needing attention

  • EL expression has no null pointer exception
  • EL expression has no index out of bounds exception
  • EL expression does not have string splicing

Use details

  • The EL expression can obtain the data of the four domain objects and find them in the domain objects from small to large according to their names
  • You can also get eight other implicit objects in the JSP and call the methods in the object

operator

  • Relational operator
    operatoreffectExamplesresult
    ==Or eqbe equal to${5 = = 5} or ${5 eq 5}true
    != Or neNot equal to${5! = 5} or ${5 ne 5}false
    < or ltless than${3 < 5} or ${3 lt 5}true
    >Or gtgreater than${3 > 5} or ${3 gt 5}false
    < = or leLess than or equal to${3 < = 5} or ${3 le 5}true
    >=Or geGreater than or equal to${3 > = 5} or ${3 ge 5}false
  • Logical operator
    operatoreffectExamplesresult
    &&Or andalso${A & & B} or ${A and B}true / false
    ||Or orperhaps${a | B} or ${A or B}true / false
    ! Or notReverse${! A} or ${not A}true / false
  • Other Operators
    operatoreffect
    empty1. Judge whether the object is null
    2. Judge whether the string is empty
    3. Judge whether the container element is 0
    Conditions? Expression 1: expression 2Ternary operator

Implicit object

Implicit object nameCorresponding JSP implicit objectexplain
pageContextpageContextThe function is exactly the same
applicationScopenothingOperation application domain object data
sessionScopenothingOperation session domain object data
requestScopenothingOperation request domain object data
pageScopenothingOperation page domain object data
headernothingGet request header data
headerValuesnothingGet request header data (multiple values)
paramnothingGet request parameter data
paramValuesnothingGet request parameter data (multiple values)
initParamnothingGet global configuration parameter data
cookienothingGet Cookie object
<%--
  Created by IntelliJ IDEA.
  User: lihao
  Date: 2022/2/25
  Time: 10:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Implicit object</title>
</head>
<body>
    <%--pageContext Object, you can get the other three domain objects and JSP Eight implicit objects in--%>
    ${pageContext.request.requestURL}<br>

    <%--applicationScope sessionScope requestScope pageScope Manipulate data in four domain objects--%>
    ${pageContext.setAttribute("username","zhangsan")}
    ${pageScope.username}<br>

    <%--header headerValues Get request header data--%>
    ${header["connection"]}
    ${headerValues["connection"][0]}
    ${header.connection}<br>

    <%--param paramValues Get request parameter data--%>
    ${param.username}
    ${paramValues.hobby[0]}<br>

    <%--initParam Get global configuration parameters--%>
    ${initParam.globaldesc}<br>

    <%--cookie obtain cookie information--%>
    ${cookie}   <%--direct writing cookie Got a map aggregate--%>
    <br>
    ${cookie.JSESSIONID.value}
</body>
</html>

JSTL

  • JSTL (Java Server Pages Standard Tag Library): JSP standard tag library
  • It mainly provides developers with a standard and general label library
  • Developers can use these tags to replace the Java code on JSP pages, so as to improve the readability of the program and reduce the difficulty of program maintenance
formeffectexplain
coreCore tag libraryGeneral logic processing
fmtinternationalizationDifferent regions display different languages
functionsEL functionMethods that EL expressions can use
sqlOperation databaseunderstand
xmlOperation XMLunderstand

Core label

Label nameFunctional classificationattributeeffect
< tag name: if >Process controlCore tag libraryFor condition judgment
< tag name: choose >
< tag name: when >
< tag name: otherwise >
Process controlCore tag libraryFor multi conditional judgment
< tag name: foreach >Iterative traversalCore tag libraryFor loop traversal

Use steps

  1. Create a web project
  2. Create a WEB-INF directory under the web directory
  3. Create a libs directory under the WEB-INF directory and import the jar package of JSTL
  4. Create a JSP file and import the JSTL tag library through taglib
  5. Use tags for process control and iterative traversal
  6. Deploy and start the project
  7. View via browser
<%@ page import="java.util.ArrayList" %><%--
  Created by IntelliJ IDEA.
  User: lihao
  Date: 2022/2/25
  Time: 10:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%--Import core library and mark and sign--%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<html>
<head>
    <title>JSTL[JSP [standard label library]</title>
</head>
<body>
    ${pageContext.setAttribute("score","A")}

    <%--Judge the results--%>
    <c:if test="${score eq 'A'}">
        excellent
    </c:if>
    <hr>

    <%--Multi condition judgment--%>
    <c:choose>
        <c:when test="${score eq 'A'}">excellent</c:when>
        <c:when test="${score eq 'B'}">good</c:when>
        <c:when test="${score eq 'C'}">pass</c:when>
        <c:when test="${score eq 'D'}">Poor</c:when>
        <c:otherwise>Illegal achievement</c:otherwise>
    </c:choose>
    <hr>

    <%--Loop traversal--%>
    <%
        ArrayList<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        list.add("ddd");
        pageContext.setAttribute("list",list);
    %>
    <c:forEach items="${list}" var="str">
        ${str}<br>
    </c:forEach>
</body>
</html>

Filter

  • When accessing server resources in the program, when a request arrives, the server first determines whether there is a filter associated with the requested resources. If so, the filter can intercept the request and complete some specific functions, and then the filter decides whether to give it to the requested resources. If there is no associated filter, the resource will be requested directly as before. The response is similar
  • Filters are generally used for general operations, such as login authentication, unified coding processing, sensitive character filtering, etc

summary

  • Is an interface. If you want to realize the function of filter, you must implement this interface
  • Core method
    Return valueMethod nameeffect
    voidinit(FilterConfig config)Initialization method
    voiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)Filtering request and response resources
    voiddestroy()Destruction method
  • collocation method
    Method 1: configuration file (web.xml)
    Method 2: annotation method

FilterChain

  • FilterChain is an interface that represents a filter chain object. The implementation class object is provided by the Servlet container. Just use it directly
  • Multiple filters can be defined to form a filter chain
  • Core method
    Return valueMethod nameexplain
    voiddoFilter(ServletRequest request, ServletResponse response)Release method

If there are multiple filters, call the next filter in the first filter, and so on. Until the final access resource is reached.
If there is only one filter, when released, it will directly reach the final access resource

Filter use

  • Requirement Description: solve the problem of Chinese garbled code written by multiple resources through Filter filter
  • Implementation steps
    1. Create a web project
    2. Create two Servlet function classes and write Chinese data to the client
    3. Create a Filter implementation class and override the doFilter core method
    4. Solve Chinese garbled code within the method and release it
    5. Deploy and start the project
    6. Test by browser
package study.servlet.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/filter01")
public class filter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter Yes");
        // Deal with garbled code
        servletResponse.setContentType("text/html;charset=UTF-8");
        // Release
        filterChain.doFilter(servletRequest,servletResponse);
    }
    @Override
    public void destroy() {}
}

Use details

  • collocation method
    Annotation method: @ webfilter (intercept path)
    Profile mode
    <!--statement-->
    <filter>
    	<filter-name>demo</filter-name>
        <filter-class>Full class name</filter-class>
    </filter>
    <!--mapping-->
    <filter-mapping>
    	<filter-name>demo</filter-name>
        <url-pattern>/Intercept path</url-pattern>
    </filter-mapping>
    
  • Order of use of multiple filters
    If there are multiple filters, it depends on the order in which the filters are mapped

life cycle

  • establish
    When the application loads, instantiate the object and execute the init initialization method
  • service
    Object, execute the doFilter method
  • Destroy
    The object is destroyed when the application is uninstalled or the server is stopped. Execute destroy method

FilterConfig

FilterConfig is an interface. Represents the configuration object of the filter, and some initialization parameters can be loaded

Core method

Return valueMethod nameeffect
StringgetFilterName()Get filter object name
StringgetInitParameter(String name)Get value by name
Enumeration<String>getInitParameterNames()Get the key of all parameters
ServletContextgetServletContext()Get application context object
<filter>
	<filter-name>demo</filter-name>
	<filter-class>Full class name</filter-class>
      
	<init-param>
		<param-name>username</param-name>
		<param-value>zhangsan</param-value>
	</init-param>
</filter>

Five interception behaviors

By default, the Filter intercepts requests, but in actual development, we also have request forwarding and request inclusion, as well as the global error page triggered by the server. By default, the Filter does not participate in filtering. If you want to use it, you need to configure it

Interception mode

<!--statement-->
<filter>
	<filter-name>demo</filter-name>
	<filter-class>Full class name</filter-class>
</filter>

<!--mapping-->
<filter-mapping>
	<filter-name>demo</filter-name>
	<url-pattern>/Intercept path</url-pattern>
      
	<dispatcher>REQUEST</dispatcher>
	<dispatcher>FORWARD</dispatcher>
	<dispatcher>INCLUDE</dispatcher>
	<dispatcher>ERROR</dispatcher>
	<dispatcher>ASYNC</dispatcher>
</filter-mapping>

REQUEST: by default, the resources directly requested by the browser will be intercepted by the filter

FORWARD: FORWARD access to resources will be blocked by the filter

INCLUDE: contains access resources

ERROR: global ERROR jump resource

ASYNC: asynchronous access to resources

Global error page configuration

<error-page>
    <!--Configure according to exception type-->
    <exception-type>java.lang.exception</exception-type>
    <location>/error.jsp</location>
</error-page>

<error-page>
    <!--Configure according to the status code-->
	<error-code>404</error-code>
    <location>/error.jsp</location>
</error-page>

Listener

  • Observer design pattern. All listeners are based on observer design pattern
  • Three components
    1. Event source: the object that triggers the event
    2. Event: the triggered action encapsulates the event source
    3. Listener: when the event source triggers an event, the function can be completed
  • In the program, we can monitor the creation and destruction of objects, the changes of attributes in domain objects, and session related contents
  • There are 8 listeners in the Servlet specification. The listeners are provided in the form of interfaces, and the specific functions need to be completed by ourselves

monitor

Listener for creating and destroying listening objects

ServletContextListener: used to listen for the creation and destruction of ServletContext objects

Core method

Return valueMethod nameeffect
voidcontextInitialized(ServletContextEvent sce)This method is executed when the object is created
voidcontextDestroyed(ServletContextEvent sce)Execute this method when the object is destroyed

Parameter: ServletContextEvent represents the event object
The event object encapsulates the event source, that is, ServletContext
The real event refers to the operation of creating or destroying the ServletContext object

HttpSessionListener: used to listen for the creation and destruction of HttpSession objects

Core method

Return valueMethod nameeffect
voidsessionCreated(HttpSessionEvent se)This method is executed when the object is created
voidsessionDestroyed(HttpSessionEvent se)Execute this method when the object is destroyed

Parameter: HttpSessionEvent represents the event object
The event object encapsulates the event source, that is, HttpSession
The real event refers to the operation of creating or destroying the HttpSession object

ServletRequestListener: used to listen for the creation and destruction of ServletRequest objects

Core method

Return valueMethod nameeffect
voidrequestInitialized(ServletRequestEvent sre)This method is executed when the object is created
voidrequestDestroyed(ServletRequestEvent sre)Execute this method when the object is destroyed

Parameter: ServletRequestEvent represents the event object
The event object encapsulates the event source, that is, ServletRequest
The real event refers to the operation of creating or destroying the ServletRequest object

A listener that listens for changes in domain object properties

ServletContextAttributeListener: used to listen for attribute changes in the ServletContext application domain

Core method

Return valueMethod nameeffect
voidattributeAdded(ServletContextAttributeEvent scae)Execute this method when adding an attribute to a domain
voidattributeRemoved(ServletContextAttributeEvent scae)This method is executed when an attribute is removed from the domain
voidattributeReplaced(ServletContextAttributeEvent scae)This method is executed when replacing an attribute in a domain

Parameter: ServletContextAttributeEvent represents the event object
The event object encapsulates the event source, that is, ServletContext
Real events refer to the operations of adding, removing and replacing attributes in the application domain

HttpSessionAttributeListener: used to listen for attribute changes in the HttpSession session domain

Core method

Return valueMethod nameeffect
voidattributeAdded(HttpSessionBindingEvent se)Execute this method when adding an attribute to a domain
voidattributeRemoved(HttpSessionBindingEvent se)This method is executed when an attribute is removed from the domain
voidattributeReplaced(HttpSessionBindingEvent se)This method is executed when replacing an attribute in a domain

Parameter: HttpSessionBindingEvent represents the event object
The event object encapsulates the event source, that is, HttpSession
Real events refer to the operations of adding, removing and replacing attributes in the session domain

ServletRequestAttributeListener: used to listen for attribute changes in the ServletRequest request domain

Core method

Return valueMethod nameeffect
voidattributeAdded(ServletRequestAttributeEvent srae)Execute this method when adding an attribute to a domain
voidattributeRemoved(ServletRequestAttributeEvent srae)This method is executed when an attribute is removed from the domain
voidattributeReplaced(ServletRequestAttributeEvent srae)This method is executed when replacing an attribute in a domain

Parameter: ServletRequestAttributeEvent represents the event object
The event object encapsulates the event source, that is, ServletRequest
Real events refer to the operations of adding, removing and replacing attributes in the request domain

Listening to session related perceptual listeners

Perceptual listener: it can be used directly after it is defined, and there is no need to configure it through annotation or xml file

HttpSessionBindingListener: listener used to sense the binding between the object and the session domain

Core method

Return valueMethod nameeffect
voidvalueBound(HttpSessionBindingEvent event)This method is executed when data is added to the session domain (binding)
voidvalueUnbound(HttpSessionBindingEvent event)This method is executed when data is removed (unbound) from the session domain

Parameter: HttpSessionBindingEvent represents the event object
The event object encapsulates the event source, that is, HttpSession
The real event refers to the operation of adding and removing data in the session domain

HttpSessionActivationListener: listener used to sense passivation and activation of session domain objects

Core method

Return valueMethod nameeffect
voidsessionWillPassivate(HttpSessionEvent se)This method is executed when data in the session domain is passivated
voidsessionDidActivate(HttpSessionEvent se)When the method executes in the session

Parameter: HttpSessionEvent represents the event object
The event object encapsulates the event source, that is, HttpSession
Real events refer to the operations of data passivation and activation in the session domain

Use of listener

  • Of the listening object
    ServletContextListener
    HttpSessionListener
    ServletRequestListener
package study.servlet.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebServlet;

@WebServlet("/listener01")
@WebListener
public class listener01 implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("Listening to object creation");
        ServletContext servletContext = servletContextEvent.getServletContext();
        // Add attribute
        servletContext.setAttribute("username","Zhang San");
        // Replace attribute
        servletContext.setAttribute("username","Li Si");
        // Remove Attribute 
        servletContext.removeAttribute("username");
        
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("Object destruction detected");
    }
}
  • Listening for attribute changes
    ServletContextAttributeListener
    HttpSessionAttributeListener
    ServletRequestAttributeListener
package study.servlet.listener;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/listener02")

public class listener02 implements ServletContextAttributeListener {
    @Override
    public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("Listening to the addition of attribute");
        ServletContext servletContext = servletContextAttributeEvent.getServletContext();
        Object username = servletContext.getAttribute("username");
        System.out.println(username);
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("Listening to the removal of property");
        ServletContext servletContext = servletContextAttributeEvent.getServletContext();
        Object username = servletContext.getAttribute("username");
        System.out.println(username);
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("Property replacement detected");
        ServletContext servletContext = servletContextAttributeEvent.getServletContext();
        Object username = servletContext.getAttribute("username");
        System.out.println(username);
    }
}
  • Session related perceptual
    HttpSessionBindingListener
    HttpSessionActivationListener

Configure listener

  • Annotation method: @ WebListener
  • xml document mode
    <listener>
    	<listener-class>Full path of listener object implementation class</listener-class>
    </listener>
    

Optimization of student management system

Solve garbled code

Use filters to achieve uniform coding of all resources

  1. Convert request and response objects into HTTP related HttpServletRequest and HttpServletResponse
  2. Set encoding format
  3. Release
package studentSystem.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class EncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // Convert request and response objects into HTTP related HttpServletRequest and HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // Set encoding format
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // Release
        filterChain.doFilter(request, response);
    }
}

Check login

Use filters to resolve login checks

  1. Convert request and response objects into HTTP related HttpServletRequest and HttpServletResponse
  2. Gets the data in the session domain object
  3. Judge user name
  4. Redirect (or periodically refresh) to the login page or release

Annotation specifies multiple interception paths when configuring filters
@WebFilter(value = {"/ intercept path 1", "intercept path 2",...})

package studentSystem.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(value = {"/add.jsp", "/list.jsp"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // Convert request and response objects into HTTP related HttpServletRequest and HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // Gets the data in the session domain object
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");
        Object password = session.getAttribute("password");
        // Judge user name
        if("admin".equals(username) && "abc123".equals(password)){
            filterChain.doFilter(request, response);
        }else{
            // Output prompt information and set regular refresh to the login page
            response.getWriter().write("You haven't signed in yet. Please sign in and try again.(2s Then jump to the login page for you)");
            response.setHeader("Refresh","2:URL=/login.jsp");
        }
    }
}

Optimize JSP pages

Replace the previous Java code block and JSP expression with EL expression and JSTL

Full code: https://github.com/HelloCode66/StudentSystem

MYSQL

JDBC

Mybatis

JavaScript

jQuery

AJAX

Vue + Element

Redis

Maven Foundation

Web project practice - dark horse page

Topics: Java Linux MySQL JavaEE Back-end