Most of the notes are taken when station B meets the javaWeb said by crazy God. By the way, the pictures and texts are combined and recorded for easy review
Video address: https://www.bilibili.com/video/BV12J411M7Sj Remember Sanlian
Article catalogue
-
- 1. Basic concepts
- 2. web server
- 3,Tomcat
- 4,Http
- 5,Maven
- 6,Servlet
- 7,Cookie,Session
- 8,JSP
- 9,JavaBean
- 10. MVC three-tier architecture
- 11. Filter (key)
- 12. Listener
- 13. Common applications of filters and listeners
- 14,JDBC
- 15. Smbms (supermarket management project)
1. Basic concepts
1.1 Preface
web development:
-
Web, the meaning of web page, www.baidu.com com·
-
Static web
- html,css
- The data provided to everyone will never change!
-
Dynamic web
- Taobao, almost all websites;
- The data provided to everyone will always change, and everyone will see different information at different times and places!
- Technology stack: Servlet/JSP, ASP, PHP
1.2. Web application web application:
Programs that can provide browser access;
- a.html,b.html.…. Multiple web resources, which can be accessed by the outside world and provide services to the outside world;
- Any page or resource you can access exists on a computer in a corner of the world.
- URL
- This unified web resource will be placed in the same folder, Web Application > Tomcat: server
- A web application consists of many parts (static web, dynamic web)
- html,css,js
- jsp,servlet
- Java program
- jar package
- Configuration files (Properties)
If you want to provide access to the outside world after the Web application is written; A service fee is required for unified management
1.3. Static web
-
*.htm, *. html these are the background of webmasters. If these Dongsi exist on the server all the time, we can read them directly and need the network;
-
Disadvantages of static web
- The Web page cannot be updated dynamically. All users see the same page
- Rotation chart, click special effect: pseudo dynamic
- JavaScript [in actual development, it is used most]
- VBScript
- It cannot interact with the database (data cannot be persisted and users cannot interact)
- The Web page cannot be updated dynamically. All users see the same page
1.4 dynamic web
The page will be displayed dynamically, "the display effect of web page varies from person to person"
Disadvantages:
- There is an error in the dynamic web resources added to the server. We need to rewrite our background program and publish it again;
- Advantages of shutdown maintenance:
- Web pages can be updated dynamically, and all users don't see the same page
- It can interact with the database (data persistence: registration, product information, user information...)
2. web server
2.1 technical explanation
ASP:
- Microsoft: ASP is the first popular in China;
- ·Embedded VB script in HTML, ASP+COM;
- ·In ASP development, there are several lines of business code in a page, and the page is extremely disordered
- ·High maintenance cost!
- C#
- IIS
php:
- PHP has fast development speed, powerful functions, cross platform, and simple code (70%, WP)
- ·Unable to carry large traffic (limitations)
jSP/Servlet:
B/S; Browse and server C/S: client and server
- B/S architecture mainly promoted by sun company
- Based on Java language (all large companies or some open source components are written in Java)
- It can bear the impact of the three high issues;
- Syntax like ASP, ASP - > JSP, strengthen market intensity;
2.2. web server
Server is a passive operation, which is used to process some requests of users and give users some response information;
lIS
Microsoft's; ASP., Built in Windows
Tomcat
Programming for Baidu:
Tomcat is a core project in the jakarta project of the Apache Software Foundation (Apache). The latest Servlet and JSP specification can always be reflected in Tomcat, because Tomcat technology is advanced, stable and free, which is deeply loved by the fans and has been recognized by some software developers. It has become a popular Web application server.
Tomcat server is a free open source web application server. It is a lightweight application server. It is widely used in small and medium-sized systems and when there are not many concurrent access users. It is the first choice for developing and debugging JSP programs. For a beginner of Java Web, it is the best choice
Tomcat actually runs JSP pages and serlets. Tornct latest version 9.0
After working for 3-5 years, you can try to write Tomcat server;
Download tomcat:
- Install or unzip
- Understand the configuration file and directory structure
- The function of this thing
3,Tomcat
3.1 installing Tomcat
Official website: http://tomcat.apache.org/
3.2. Tomcat startup and configuration
Folder function:
Access test: http://localhost:8080/
Possible problems:
- Java environment variables are not configured
- Flash back problem: compatibility needs to be configured
- Garbled code problem: set in the configuration file
You can modify conf / logging Java. In properties util. logging. ConsoleHandler. Encoding = GBK solves the problem of garbled code
3.3 configuration
The port number of startup can be configured
-
The default port number of tomcat is 8080
-
mysql:3306
-
http:80
-
https: 443
You can configure the name of the host
-
The default host name is localhost - > 127.0.0.1
-
The default location of website application is webapps
Difficult interview questions:
Please talk about how the website is accessed!
- Enter a domain name; enter
- Check whether there is this domain name mapping under the C:WindowsSystem32driversetchosts configuration file of this machine;
-
Yes: directly return the corresponding ip address. In this address, there are web programs we need to access, which can be accessed directly
127.0.0.1 www.qinjiang.com
-
No: go to the DNS server and return if found. If not, return if not found;
-
4. You can configure the following environment variables (optional)
3.4. Publish a web site
If not, imitate first
- Put the website written by yourself under the specified web application folder (webapps) in the server (Tomcat), and you can access it
The structure that a website should have
--webapps : Tomcat Server web catalogue -ROOT -kuangstudy : Directory name of the web site - WEB-INF -classes : java program -lib: web Application dependent jar package -web.xml : Site profile - index.html Default home page - static -css -style.css -js -img -.....
HTTP protocol: Interview
Maven: build tool
- Maven installation package
Getting started with Servlet
- HelloWorld!
- Servlet configuration and principle
4,Http
4.1. What is HTTP
(Hypertext Transfer Protocol) is a simple request response protocol, which usually runs on TCP.
- Text: html, string
- Hypertext: picture, music, video, location, map
- Port: 80
Https: Secure
4.2 two times
- http1.0
- HTTP/1.0: after the client can connect with the web server, it can only obtain one web resource and disconnect
- http2.0
- HTTP/1.1: after the client can connect with the web server, it can obtain multiple web resources.
4.3 Http request
- Client – Request – server
Baidu:
Request URL:https://www.baidu.com / request address Request Method:GET get method/post method Status Code:200 OK Status code: 200 Remote((remote) Address:14.215.177.39:443 Accept:text/html Accept-Encoding:gzip, deflate, br Accept-Language:zh-CN,zh;q=0.9 language Cache-Control:max-age=0 Connection:keep-alive
1. Request line
- Request method in request line: GET
- Request method: get, post, head, delete, put, trace
- get: the request can carry fewer parameters, and the size is limited. The data content will be displayed in the URL address bar of the browser, which is unsafe but efficient
- post: there is no limit on the parameters that the request can carry, and there is no limit on the size. The data content will not be displayed in the URL address bar of the browser. It is safe but not efficient.
2. Message header
Accept: Tell the browser what data types it supports Accept-Encoding: Which encoding format is supported GBK UTF-8 GB2312 ISO8859-1 Accept-Language: Tell the browser its locale Cache-Control: Cache control Connection: Tell the browser whether to disconnect or remain connected when the request is completed HOST: host..../.
4.4 Http response
- Server – response client
Baidu:
Cache-Control:private Cache control Connection:Keep-Alive connect Content-Encoding:gzip code Content-Type:text/html type
1. Responder
Accept: Tell the browser what data types it supports Accept-Encoding: Which encoding format is supported GBK UTF-8 GB2312 ISO8859-1 Accept-Language: Tell the browser its locale Cache-Control: Cache control Connection: Tell the browser whether to disconnect or remain connected when the request is completed HOST: host..../. Refresh: Tell the client how often to refresh; Location: Repositioning web pages;
2. Response status code
200: request response succeeded 200
3xx: request redirection · redirection: you go back to the new location I gave you;
4xx: resource not found 404 · resource does not exist;
5xx: server code error 500 502: gateway error
Common interview questions:
When you enter the address in the address bar of your browser and press enter, what has happened when the page can be displayed back?
5,Maven
Why should I learn this technology?
- In Java Web development, we need to use a large number of jar packages, which we import manually;
- How can I make something automatically import and configure this jar package for me.
Thus, Maven was born!
5.1 Maven project architecture management tool
We are currently used to facilitate the import of jar packages!
Maven's core idea: Convention is greater than configuration
- There are constraints. Don't break them.
Maven will specify how you should write our Java code, which must be in accordance with this specification;
5.2 download and install Maven
Official website: https://maven.apache.org/
After downloading, unzip it;
Little crazy God friendship suggestion: all the environments on the computer are placed in one folder for easy management;
5.3 configuring environment variables
Configure the following configuration in our system environment variable:
- M2_ bin directory under home Maven directory
- MAVEN_ Directory of home maven
- Configure% Maven in the path of the system_ HOME%in
Test whether Maven is installed successfully and ensure that the configuration must be completed!
5.4 Alibaba cloud image
-
Mirroring: mirrors
-
Function: speed up our download
-
Alibaba cloud image is recommended in China
nexus-aliyun *,!jeecg,!jeecg-snapshots Nexus aliyun http://maven.aliyun.com/nexus/content/groups/public
D:Enmvironmentapache-maven-3.6.2confettings.xml
(madness teacher configures the file location of source and warehouse)
5.5 local warehouse
Local warehouse, remote warehouse; Set up a local repository: localRepository
<localRepository>D:Environmentapache-maven-3.6.2maven-repo</localRepository>
5.6 ~ 5.13 notes - download address
(reject dial) download address: https://lanzoui.com/ibuibxi
Later 5.6 ~ 5.13 + case demonstration (Figure)
The rest of the notes in the following part 5 suggest to cooperate with the spirit of madness
"javaweb-06: Maven operation in IDEA", "javaweb-07: solving some problems we encounter"
Look back (carefully)
6,Servlet
6.1 introduction to Servlet
- Servlet is a technology for sun company to develop dynamic web
- Sun provides an interface called Servlet in these APIs. If you want to develop a Servlet program, you only need to complete two small steps:
- Write a class to implement the Serlet interface
- Deploy the java class into the web development server.
The Java program that implements the Servlet interface is called Servlet
6.2,HelloServlet
Servlet interface Sun has two default implementation classes: HttpServlet and genericservlet
6.2,HelloServlet
-
Build an ordinary Maven project and the sc directory of the equivalent surface. In the future, we will build Moudel in this project; This empty project is called Maven main project;
-
Understanding of Maven father son project;
There will be in the parent project<modules> <module>servlet-01</module> </modules>
Sub projects will have
<parent> <artifactId>javaweb-02-servlet</artifactId> <groupId>com.kuang</groupId> <version>1.0-SNAPSHOT</version> </parent>
java subprojects in the parent project can be used directly
son extends father
-
Maven environment optimization
- Modify web XML is the latest
- Complete the structure of maven
.
-
Write a Servlet program
-
Write a common class
-
Implement the Servlet interface. Here we directly inherit HttpServlet
public class HelloServlet extends HttpServlet {
//Because get or post are only different ways of request implementation, they can call each other, and the business logic is the same; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //ServletOutputStream outputStream = resp.getOutputStream(); PrintWriter writer = resp.getWriter(); //Response flow writer.print("Hello,Serlvet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }
}
-
-
Write the mapping of Servlet
Why mapping is needed: we write a JAVA program, but we need to access it through the browser, and the browser needs to connect to the web server, so we need to
To register the Servlet we wrote in the web service, we also need to give it a path that the browser can access;<!--register Servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.kuang.servlet.HelloServlet</servlet-class> </servlet> <!--Servlet Request path for--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
-
Configure Tomcat
Note: just configure the project publishing path
-
Start the test, OK!
6.3 principle of Servlet
Servlet is called by the web server. After receiving the browser request, the web server will:
6.4. Mapping problem
-
A Servlet can specify a mapping path
.<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
-
A servlet can specify multiple mapping paths
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello3</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello4</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello5</url-pattern> </servlet-mapping>
-
A servlet can specify a generic mapping path
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping>
-
Default request path
<!--Default request path--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
-
Specify some suffixes or prefixes, etc
hello *.qinjiang -
Priority issues
error com.kuang.servlet.ErrorServlet error /*
Specifies the inherent mapping path with the highest priority. If it cannot be found, it will go to the default processing request;
6.5,ServletContext
When the web container starts, it will create a corresponding ServletContext object for each web application, which represents the current web application;
1. Shared data
The data I saved in this servlet can be obtained in another servlet;
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //this.getInitParameter() initialization parameter //this. Getservletconfig() servlet configuration //this. Getservletcontext() servlet context ServletContext context = this.getServletContext(); String username = "Qin Jiang"; //data context.setAttribute("username",username); //A data is saved in the ServletContext with the name username. Value username } } public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String username = (String) context.getAttribute("username"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); resp.getWriter().print("name"+username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.kuang.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>getc</servlet-name> <servlet-class>com.kuang.servlet.GetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>getc</servlet-name> <url-pattern>/getc</url-pattern> </servlet-mapping>
Test access results;
2. Get initialization parameters
<!--Configure some web Application initialization parameters--> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybatis</param-value> </context-param> protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String url = context.getInitParameter("url"); resp.getWriter().print(url); }
3. Request forwarding
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); System.out.println("Entered ServletDemo04"); //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); // Forwarded request path //requestDispatcher.forward(req,resp); // Call forward to forward the request; context.getRequestDispatcher("/gp").forward(req,resp); }
4. Read resource file
Properties
- Create new properties in java directory
- Create new properties in the resources directory
Discovery: they are all packaged in the same path: classes. We commonly call this path classpath:
Idea: need a file stream
username=root12312 password=zxczxczxc
public class ServletDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties"); Properties prop = new Properties(); prop.load(is); String user = prop.getProperty("username"); String pwd = prop.getProperty("password"); resp.getWriter().print(user+":"+pwd); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
Access the test, ok;
6.6,HttpServletResponse
web The server received a message from the client http Request. For this request, create a representative of the request HttpServletRequest Object that represents a response HttpServletResponse;
-
If you want to get the parameters requested by the client: find HttpServletRequest
-
If you want to respond to the client with some information: find HttpServletResponse
1. Simple classification
Method responsible for sending data to browser
servletOutputstream getOutputstream() throws IOException; Printwriter getwriter() throws IOException;
The method responsible for sending the response header to the browser
void setCharacterEncoding(String var1); void setContentLength(int var1); void setContentLengthLong(long var1); void setContentType(String var1); void setDateHeader(String varl,long var2) void addDateHeader(String var1,long var2) void setHeader(String var1,String var2); void addHeader(String var1,String var2); void setIntHeader(String var1,int var2); void addIntHeader(String varl,int var2);
Response status code
2. Download File
-
Output a message to the browser (keep talking, don't say it)
-
Download File
- To get the path of the downloaded file
- What is the name of the downloaded file?
- Set up a way to make the browser support downloading what we need
- Gets the input stream of the downloaded file
- Create buffer
- Get OutputStream object
- Writes the FileOutputStream stream to the bufer buffer
- Use OutputStream to output the data in the buffer to the client!
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. To get the path of the downloaded file
String realPath = "F: \ class management \ Xikai [19525] \ 2. Code \ JavaWeb\javaweb-02-servlet\response\target\classes \ Qinjiang. png";
System.out.println("download file path:" + realPath);
// 2. What is the name of the downloaded file?
String fileName = realPath.substring(realPath.lastIndexOf("") + 1);
// 3. Set up a way to make the browser support (content disposition) to download what we need. The Chinese file name is urlencoder Otherwise, the code may be scrambled
resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
// 4. Gets the input stream of the downloaded file
FileInputStream in = new FileInputStream(realPath);
// 5. Create buffer
int len = 0;
byte[] buffer = new byte[1024];
// 6. Get OutputStream object
ServletOutputStream out = resp.getOutputStream();
// 7. Write the FileOutputStream stream to the buffer buffer, and use OutputStream to output the data in the buffer to the client!
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
}in.close(); out.close();
}
3. Verification code function
How did the verification come from
-
Front end implementation
-
The back-end implementation needs to use the Java picture class to produce a picture
package com.kuang.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;public class ImageServlet extends HttpServlet {
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //How to make the browser refresh automatically every 3 seconds; resp.setHeader("refresh","3"); //Create a picture in memory BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); //Get pictures Graphics2D g = (Graphics2D) image.getGraphics(); //pen //Set the background color of the picture g.setColor(Color.white); g.fillRect(0,0,80,20); //Write data to pictures g.setColor(Color.BLUE); g.setFont(new Font(null,Font.BOLD,20)); g.drawString(makeNum(),0,20); //Tell the browser that the request is opened in the form of a picture resp.setContentType("image/jpeg"); //There is a cache on the website. Do not let the browser cache resp.setDateHeader("expires",-1); resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Pragma","no-cache"); //Write the picture to the browser ImageIO.write(image,"jpg", resp.getOutputStream()); } //Generate random number private String makeNum(){ Random random = new Random(); String num = random.nextInt(9999999) + ""; StringBuffer sb = new StringBuffer(); for (int i = 0; i < 7-num.length() ; i++) { sb.append("0"); } num = sb.toString() + num; return num; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }
}
ImageServlet com.kuang.servlet.ImageServlet Imageservlet /img
Common scenarios:
-
User login
void sendRedirect(String var1) throws IOException;
Test:
@override protected void doGet(HttpservletRequest req, HttpservletResponse resp) throws ServletException, IOException { resp. sendRedirect("/r/img");//redirect /* resp. setHeader("Location","/r/img"); resp. setstatus (302); * }
index.jsp
<html> <body> <h2>Hel1o World!</h2> <%--Here is the path of intersection,Need to find the path to the project--%> <%--${pageContext. request, contextPath}Represents the current project--%> <form action="${pageContext. request.contextPath}/login" method="get"> user name: <input type="text" name="username"> <br> password: <input type="password" name="password"> <br> <input type="submit"> </form> </body> </html>
RequestTest.java
public class RequestTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Processing method String username = req.getParameter( s: "username"); String password rea.getParameter( s: "password"); System.out.println(username+":"+password); resp.sendRedirect(s: "/r/success.jsp"); }
Redirect page success jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>success</h1> </body> </html>
web.xml configuration
<servlet> <servlet-name>requset</servlet-name> <servlet-class>com. kuang. servlet. RequestTest</servlet-class> </servlet> <servlet-mapping> <servlet-name>requset</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping>
Import dependent jar packages
<dependencies> <!-- https://mvnrepository. com/artifact/javax. servLet/javax. servlet-opi --> <dependency> <groupld>javax.servlet</grouptd> <artifactId>javax. servlet-api</artifactId> <version>4.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax. servLet.jsp/javax. servLet.jsp-opi --> <dependency> <groupId>javax.servlet.jsp</groupld> <artifactId>javax. servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> </dependencies> </project>
6.7,HttpServletRequest
HttpServletRequest represents the request of the client. The user accesses the server through the HTTP protocol. All the information in the HTTP request will be encapsulated in HttpServletRequest. Through this HttpServletRequest method, all the information of the client can be obtained;
Obtain parameters and request forwarding
Create your own class and inherit the HttpServlet class
@Override protected void doGet(HttpservletRequest req. HttpservletResponse resp) throws ServletException, IOException { req. setcharacterEncoding("utf-8"); resp.setcharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobbys = req.getParameterValues("hobbys"); System.out.println("=========="); //Background receiving Chinese garbled code System. out.println(username); System. out.println(password); System. out.println(Arrays.tostring(hobbys)); System. out.println("============"); system. out.println(req.getContextPath()); //Forward by request /// here represents the current web application req.getRequestDispatcher("/success.jsp").forward(req,resp); }
7,Cookie,Session
7.1 conversation
Session: users open a browser, click many hyperlinks, access multiple web resources, and close the browser. This process can be called session;
Stateful conversation: when a classmate comes to the classroom next time, we will know that the classmate has been here, which is called stateful conversation;
How can you prove that you are a student of Xikai?
You drive west
- I'll give you the invoice
- School registration Xikai sign you've been here
A website, how to prove that you have been here?
Client server
- The server sends a letter to the client, and the client can bring the letter to the server next time; cookie
- The server registers that you have been here. Next time you come, I will match you; seesion
7.2. Two techniques for saving sessions
cookie
- Client Technology (response, request)
session
- Server technology, which can save the user's Session information? We can put information or data in the Session!
Common: after you log in to the website, you don't need to log in again next time. You can go up directly for the second visit!
7.3,Cookie
-
Get cookie information from the request
-
The server responds to the client cookie
Cookie[] cookies = req.getCookies(); // Get cookies
cookie.getName(); // Get the key in the cookie
cookie.getValue(); // Get vlaue in cookie
new Cookie(“lastLoginTime”, System.currentTimeMillis()+""); // Create a new cookie
cookie.setMaxAge(246060); // Set the validity period of the cookie
resp.addCookie(cookie); // Respond to a cookie to the client
cookie: usually saved in the local user directory appdata;
Whether there is an upper limit for a website cookie! Talk about the details
- A Cookie can only save one information;
- A web site can send multiple cookies to the browser and store up to 20 cookies;
- The Cookie size is limited to 4kb;
- 300 cookie s browser limit
Delete cookies;
- If the validity period is not set, close the browser and it will automatically become invalid;
- Set the validity time to 0;
Encoding and decoding:
URLEncoder.encode("Qin Jiang","utf-8") URLDecoder.decode(cookie.getValue(),"UTF-8")
7.4. Session (key)
What is a Session:
- The server will create a Seesion object for each user (browser);
- A Session monopolizes a browser. As long as the browser is not closed, the Session exists;
- After the user logs in, the whole website can be accessed! – > Save user information; Save shopping cart information
...
...
...
The difference between Session and cookie:
- Cookie is to write the user's data to the user's browser, and the browser saves it (multiple can be saved)
- Session writes the user's data to the user's exclusive session and saves it on the server side (saving important information and reducing the waste of server resources)
- The Session object is created by the service;
Usage scenario:
- Save the information of a login user;
- Shopping cart information;
- The data that is often used in the whole website is saved in Session;
Using Session:
package com.kuang.servlet; import com.kuang.pojo.Person; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException; public class SessionDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Solve the problem of garbled code req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); //Get Session HttpSession session = req.getSession(); //Save something in the Session session.setAttribute("name",new Person("Qin Jiang",1)); //Get the ID of the Session String sessionId = session.getId(); //Judge whether the Session is newly created if (session.isNew()){ resp.getWriter().write("session Created successfully,ID:"+sessionId); }else { resp.getWriter().write("session As well as existing in the server,ID:"+sessionId); } //What was done when the Session was created; // Cookie cookie = new Cookie("JSESSIONID",sessionId); // resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } //Get Session HttpSession session = req.getSession(); Person person = (Person) session.getAttribute("name"); System.out.println(person.toString()); HttpSession session = req.getSession(); session.removeAttribute("name"); //Log off Session manually session.invalidate();
Session auto Expiration: Web XML configuration
<!--set up Session Default expiration time--> <session-config> <!--15 Minutes later Session Automatic failure, in minutes--> <session-timeout>15</session-timeout> </session-config>
8,JSP
8.1. What is JSP
Java Server Pages: Java server-side pages, like servlets, are used for dynamic Web technology!
Biggest features:
- Writing JSP is like writing HTML
- difference:
- HTML only provides users with static data
- JAVA code can be embedded in JSP pages to provide users with dynamic data;
8.2 JSP principle
Idea: how to execute JSP in the end!
-
There are no problems at the code level
-
Server internal work
There is a work directory in tomcat;
If Tomcat is used in the IDEA, a work directory will be produced in Tomcat of the IDEA
Address of my computer:
C:UsersAdministrator.IntelliJIdea2018.1system omcatUnnamed_javaweb-session-cookieworkCatalinalocalhostROOTorgapachejsp
Found that the page has been transformed into a Java program!
The browser sends a request to the server. No matter what resources are accessed, they are actually accessing the Servlet!
JSP will eventually be converted into a Java class!
JSP is essentially a Servlet
//initialization public void _jspInit() { } //Destroy public void _jspDestroy() { } //JSPService public void _jspService(.HttpServletRequest request,HttpServletResponse response)
-
Judgment request
-
Some built-in objects
final javax.servlet.jsp.PageContext pageContext; //Page context javax.servlet.http.HttpSession session = null; //session final javax.servlet.ServletContext application; //applicationContext final javax.servlet.ServletConfig config; //config javax.servlet.jsp.JspWriter out = null; //out final java.lang.Object page = this; //page: current HttpServletRequest request //request HttpServletResponse response //response
-
Code added before output page
response.setContentType("text/html"); //Set the page type of the response pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out;
-
The above objects can be used directly in JSP pages!
In JSP pages;
As long as it is JAVA code, it will be output intact;
If it is HTML code, it will be converted to:
out.write("<html> ");
Such a format, output to the front end!
8.3. JSP basic syntax
Any language has its own syntax, which is found in Java,. As an application of Java technology, JSP has its own expanded syntax (understand, know!), All Java grammars are supported!
JSP expression
<%--JSP expression Function: used to output the output of the program to the client <%= Variable or expression%> --%> <%= new java.util.Date()%>
jsp script fragment
<%--jsp Script fragment--%> <% int sum = 0; for (int i = 1; i <=100 ; i++) { sum+=i; } out.println("<h1>Sum="+sum+"</h1>"); %>
Re implementation of script fragments
<% int x = 10; out.println(x); %> <p>This is a JSP file</p> <% int y = 2; out.println(y); %> <hr> <%--Embedding in code HTML element--%> <% for (int i = 0; i < 5; i++) { %> <h1>Hello,World <%=i%> </h1> <% } %>
JSP declaration
<%! static { System.out.println("Loading Servlet!"); } private int globalVar = 0; public void kuang(){ System.out.println("Entered the method Kuang!"); } %>
JSP declaration: it will be compiled into the Java class generated by JSP! Others will be generated to_ jspService method!
In JSP, embed Java code!
<%%> <%=%> <%!%> <%--notes--%>
JSP comments will not be displayed on the client, and HTML will!
8.4. JSP instruction
<%@page args.... %> <%@include file=""%> <%--@include The two pages will be combined into one--%> <%@include file="common/header.jsp"%> <h1>Web page subject</h1> <%@include file="common/footer.jsp"%> <hr> <%--jSP label jsp:include: The essence of splicing pages is three --%> <jsp:include page="/common/header.jsp"/> <h1>Web page subject</h1> <jsp:include page="/common/footer.jsp"/>
8.5 and 9 built-in objects
-
PageContext store things
-
Request to store things
-
Response
-
Session storage
-
Application [servvetcontext] save things
-
config [SerlvetConfig]
-
out
-
page, don't understand
-
exception
pageContext.setAttribute("name1", "Qinjiang No. 1")// The saved data is only valid in one page
request.setAttribute("name2", "Qinjiang 2")// The saved data is only valid in one request, and the request forwarding will carry this data
session.setAttribute("name3", "Qinjiang 3")// The saved data is valid only in one session, from opening the browser to closing the browser
application.setAttribute("name4", "Qinjiang 4")// The saved data is only valid in the server, from opening the server to closing the server
Request: the client sends a request to the server. The generated data is useless after the user reads it. For example, news is useless after the user reads it!
session: the client sends a request to the server, and the generated data is still useful when the user runs out, such as a shopping cart;
application: the client sends a request to the server, and the generated data is used up by one user, and other users may also use it, such as chat data;
8.6. JSP tag, JSTL tag, EL expression
<!-- JSTL Dependency of expression --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <!-- standard Tag library --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>
EL expression: ${}
- get data
- Perform operations
- Get common objects of web Development
JSP tag
<%--jsp:include--%> <%-- http://localhost:8080/jsptag.jsp?name=kuangshen&age=12 --%> <jsp:forward page="/jsptag2.jsp"> <jsp:param name="name" value="kuangshen"></jsp:param> <jsp:param name="age" value="12"></jsp:param> </jsp:forward>
JSTL expression
The use of JSTL tag library is to make up for the deficiency of HTML tags; It can customize many tags for us to use. The function of tags is the same as that of Java code!
Format label
SQL tag
XML tag
Core label (master part)
Steps for using JSTL tag library
- Introduce the corresponding taglib
- Use one of the methods
- It is also necessary to introduce JSTL package in Tomcat, otherwise an error will be reported: JSTL parsing error
c: if
<head> <title>Title</title> </head> <body> <h4>if test</h4> <hr> <form action="coreif.jsp" method="get"> <%-- EL Expression to get the data in the form ${param.Parameter name} --%> <input type="text" name="username" value="${param.username}"> <input type="submit" value="Sign in"> </form> <%--Judge that if the submitted user name is administrator, the login is successful--%> <c:if test="${param.username=='admin'}" var="isAdmin"> <c:out value="Welcome to the administrator!"/> </c:if> <%--Self closing label--%> <c:out value="${isAdmin}"/> </body>
c:choose c:when
<body> <%--Define a variable score,The value is 85--%> <c:set var="score" value="55"/> <c:choose> <c:when test="${score>=90}"> Your grades are excellent </c:when> <c:when test="${score>=80}"> Your grades are average </c:when> <c:when test="${score>=70}"> Your grades are good </c:when> <c:when test="${score<=60}"> Your grade is a failure </c:when> </c:choose> </body>
c:forEach
<% ArrayList<String> people = new ArrayList<>(); people.add(0,"Zhang San"); people.add(1,"Li Si"); people.add(2,"Wang Wu"); people.add(3,"Zhao Liu"); people.add(4,"Tian Liu"); request.setAttribute("list",people); %> <%-- var , Variables traversed each time items, Object to traverse begin, Where to start end, Where to go? step, step --%> <c:forEach var="people" items="${list}"> <c:out value="${people}"/> <br> </c:forEach> <hr> <c:forEach var="people" items="${list}" begin="1" end="3" step="1" > <c:out value="${people}"/> <br> </c:forEach>
9,JavaBean
Entity class
JavaBean s have specific ways of writing:
- There must be a parameterless construct
- Property must be privatized
- There must be a corresponding get/set method;
It is generally used to map ORM with database fields;
ORM: Object Relational Mapping
- Table - > class
- Fields – > Properties
- Line record - > object
people table
id
name
age
address
1
Qinjiang 1
3
Xi'an
2
Qinjiang 2
18
Xi'an
3
Qinjiang 3
100
Xi'an
class People{ private int id; private String name; private int id; private String address; } class A{ new People(1,"Qinjiang 1",3,"Xi'an"); new People(2,"Qinjiang 2",3,"Xi'an"); new People(3,"Qinjiang 3",3,"Xi'an"); }
- filter
- File upload
- Mail sending
- jdbc review: how to use jdbc, jdbc crud, jdbc transaction
10. MVC three-tier architecture
- What is MVC: Model view Controller
10.1 previous architecture
Users directly access the control layer, and the control layer can directly operate the database;
servlet--CRUD-->database Disadvantages: the program is very bloated, which is not conducive to maintenance servlet In the code of: processing request, response, view jump, processing JDBC,Processing business code and processing logic code Architecture: nothing can't be solved by adding one layer! Program call ↑ JDBC ((implement the interface) ↑ Mysql Oracle SqlServer ....((different manufacturers)
10.2 MVC three-tier architecture
Model
- Business processing: business logic (Service)
- Data persistence layer: CRUD (Dao - data persistence object)
View
- Display data
- Provide link to initiate Servlet request (a, form, img...)
Controller (Servlet)
-
Receive user's request: (req: request parameters, Session information...)
-
Give it to the business layer to process the corresponding code
-
Control view jump
Sign in--->Receive user login request--->Handle the user's request (get the user login parameters, username,password)---->Give it to the business layer to handle the login business (judge whether the user name and password are correct: Transaction)--->Dao Check whether the user name and password are correct-->database
11. Filter (key)
For example, Shiro security framework technology is implemented with Filter
Filter: filter, used to filter the data of the website;
- Deal with Chinese garbled code
- Login authentication
(for example, I * * * myself 0-0 when I use it to filter the words of swearing on the Internet)
Filter development steps:
-
Guide Package
-
Write filter
- Guide the package correctly (note)
Implement the Filter interface and rewrite the corresponding method
public class CharacterEncodingFilter implements Filter { //Initialization: when the web server starts, it will be initialized, waiting for the filter object to appear at any time! public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharacterEncodingFilter initialization"); } //Chain: Chain /* 1. All codes in the filter will be executed when filtering specific requests 2. You have to keep the filter going chain.doFilter(request,response); */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); System.out.println("CharacterEncodingFilter Before execution...."); chain.doFilter(request,response); //Let our request continue. If we don't write, the program will be intercepted and stopped here! System.out.println("CharacterEncodingFilter After execution...."); } //Destroy: when the web server is shut down, the filter will be destroyed public void destroy() { System.out.println("CharacterEncodingFilter Destroy"); } }
-
On the web Configure Filter in XML
CharacterEncodingFilter com.kuang.filter.CharacterEncodingFilter CharacterEncodingFilter /servlet/*
12. Listener
Implement a listener interface; (there are n kinds of listeners)
-
Write a listener
Implement the listener interface
Dependent jar package
//Count the number of people online: session public class OnlineCountListener implements HttpSessionListener { //Create session monitor: watch your every move //This event will be triggered once the Session is created! public void sessionCreated(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); System.out.println(se.getSession().getId()); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount = new Integer(1); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } ctx.setAttribute("OnlineCount",onlineCount); } //Destroy session listening //This event will be triggered once the Session is destroyed! public void sessionDestroyed(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount = new Integer(0); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count-1); } ctx.setAttribute("OnlineCount",onlineCount); } /* Session Destruction: 1. Manually destroy getsession() invalidate(); 2. Automatic destruction */ }
-
web. Register listeners in XML
<!--Register listener--> <listener> <listener-class>com.kuang.listener.OnlineCountListener</listener-class> </listener>
-
It depends on whether it is used!
13. Common applications of filters and listeners
Listener: often used in GUI programming;
public class TestPanel { public static void main(String[] args) { Frame frame = new Frame("Happy Mid-autumn Day "); //Create a new form Panel panel = new Panel(null); //panel frame.setLayout(null); //Set the layout of the form frame.setBounds(300,300,500,500); frame.setBackground(new Color(0,0,255)); //Set background color panel.setBounds(50,50,300,300); panel.setBackground(new Color(0,255,0)); //Set background color frame.add(panel); frame.setVisible(true); //Monitor event frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); } }); } }
Users can enter the home page only after logging in! Users cannot enter the home page after logging off!
-
After the user logs in, put the user's data into Sison
-
When entering the home page, judge whether the user has logged in; Requirements: implemented in the filter!
HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; if (request.getSession().getAttribute(Constant.USER_SESSION)==null){ response.sendRedirect("/error.jsp"); } chain.doFilter(request,response);
14,JDBC
What is JDBC: Java connection database!
jar package support is required:
- java.sql
- javax.sql
- MySQL connector Java... Connection driver (must be imported)
Construction of experimental environment
CREATE TABLE users( id INT PRIMARY KEY, `name` VARCHAR(40), `password` VARCHAR(40), email VARCHAR(60), birthday DATE ); INSERT INTO users(id,`name`,`password`,email,birthday) VALUES(1,'Zhang San','123456','zs@qq.com','2000-01-01'); INSERT INTO users(id,`name`,`password`,email,birthday) VALUES(2,'Li Si','123456','ls@qq.com','2000-01-01'); INSERT INTO users(id,`name`,`password`,email,birthday) VALUES(3,'Wang Wu','123456','ww@qq.com','2000-01-01'); SELECT * FROM users;
Import database dependencies
<!--mysql Drive of--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
Connect to database in IDEA:
JDBC fixing steps:
-
Load driver
-
Connect to the database and represent the database
-
Object statement to send SQL to database: CRUD
-
Write SQL (different SQL according to business)
-
Execute SQL
-
Close the connection (open first and then close)
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//Configuration information
//Useunicode = true & characterencoding = UTF-8 solve Chinese garbled code
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";//1. Load drive Class.forName("com.mysql.jdbc.Driver"); //2. Connect to the database and represent the database Connection connection = DriverManager.getConnection(url, username, password); //3. Send SQL object statement to the database, Preparedstatement: CRUD Statement statement = connection.createStatement(); //4. Write SQL String sql = "select * from users"; //5. Execute SQL query and return a ResultSet: result set ResultSet rs = statement.executeQuery(sql); while (rs.next()){ System.out.println("id="+rs.getObject("id")); System.out.println("name="+rs.getObject("name")); System.out.println("password="+rs.getObject("password")); System.out.println("email="+rs.getObject("email")); System.out.println("birthday="+rs.getObject("birthday")); } //6. Close the connection and release resources (be sure to do it) first on and then off rs.close(); statement.close(); connection.close(); }
}
Precompiled SQL
public class TestJDBC2 { public static void main(String[] args) throws Exception { //configuration information //Useunicode = true & characterencoding = UTF-8 solve Chinese garbled code String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8"; String username = "root"; String password = "123456"; //1. Load drive Class.forName("com.mysql.jdbc.Driver"); //2. Connect to the database and represent the database Connection connection = DriverManager.getConnection(url, username, password); //3. Write SQL String sql = "insert into users(id, name, password, email, birthday) values (?,?,?,?,?);"; //4. Precompile PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1,2);//For the first placeholder? The value of is assigned to 1; preparedStatement.setString(2,"Madness theory Java");//For the second placeholder? The value of is assigned as crazy God said Java; preparedStatement.setString(3,"123456");//For the third placeholder? The value of is assigned as 123456; preparedStatement.setString(4,"24736743@qq.com");//For the fourth placeholder? The value of is assigned to 1; preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//For the fifth placeholder? The value of is assigned as new date (new Java. Util. Date() getTime()); //5. Execute SQL int i = preparedStatement.executeUpdate(); if (i>0){ System.out.println("Insert successful@"); } //6. Close the connection and release resources (be sure to do it) first on and then off preparedStatement.close(); connection.close(); } }
affair
Either all succeed or all fail!
ACID principle: ensure data security.
Open transaction Transaction commit commit() Transaction rollback rollback() Close transaction transfer accounts: A:1000 B:1000 A(900) --100--> B(1100)
Junit unit test
rely on
<!--unit testing --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>
Simple use
@The Test annotation is only effective in methods. As long as the annotated method is added, it can be run directly!
@Test public void test(){ System.out.println("Hello"); }
Failure is red:
Build an environment
CREATE TABLE account( id INT PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(40), money FLOAT ); INSERT INTO account(`name`,money) VALUES('A',1000); INSERT INTO account(`name`,money) VALUES('B',1000); INSERT INTO account(`name`,money) VALUES('C',1000); @Test public void test() { //configuration information //Useunicode = true & characterencoding = UTF-8 solve Chinese garbled code String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8"; String username = "root"; String password = "123456"; Connection connection = null; //1. Load drive try { Class.forName("com.mysql.jdbc.Driver"); //2. Connect to the database and represent the database connection = DriverManager.getConnection(url, username, password); //3. Notify the database to start the transaction and false to start it connection.setAutoCommit(false); String sql = "update account set money = money-100 where name = 'A'"; connection.prepareStatement(sql).executeUpdate(); //Manufacturing error //int i = 1/0; String sql2 = "update account set money = money+100 where name = 'B'"; connection.prepareStatement(sql2).executeUpdate(); connection.commit();//If the above two SQL statements are executed successfully, commit the transaction! System.out.println("success"); } catch (Exception e) { try { //If an exception occurs, notify the database to roll back the transaction connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); }finally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
15. Smbms (supermarket management project)
30 ~ 37 sets of SMBMS project experiment
Station B crazy God Theory - Eclipse - SMBMS project experiment
https://blog.csdn.net/bell_love/article/details/106157413
. . .