1. Getting to know Servlet first
1.1 Introduction
Servlet is a technology that uses Java language to develop dynamic websites. A Servlet is a program running on a Web server or an application server, and it serves as an intermediate layer between a request from a Web browser or other HTTP client and a database or application on the HTTP server. Servlets can collect user input from web forms, render records from databases or other sources, and create web pages dynamically
1.2 steps
Sun provides an interface in these APIs called: Servlet, if you want to develop a Servlet program, you only need to complete two small steps:
- Write a class that implements the Servlet interface
- Deploy the developed Java classes to the web server.
1.3Servlet mapping
Servlet mapping refers to the process of one-to-one correspondence between Servlet classes and URLs (links to front-end access servers). Servlet mapping can be configured through XML files or annotations
XML file method
XML file method: In the web.xml file, use the <servlet> element and the <servlet-mapping> element to define the correspondence between the Servlet class and the URL
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
</servlet-mapping>
In this way, the com.example.MyServlet class is mapped to the URL /myServlet, and the client can access this Servlet through http://localhost:8080/myServlet
Annotation method
Annotation method: On the Servlet class, use the @WebServlet annotation to specify the corresponding relationship of the URL
@WebServlet("/myServlet")
public class MyServlet extends HttpServlet {
// ...
}
In this way, the MyServlet class is mapped to the URL /myServlet, and the client can access this Servlet through http://localhost:8080/myServlet
multiple mapping
Note that a Servlet can be mapped to multiple URLs, that is, multiple mappings
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
<url-pattern>/myServlet2</url-pattern>
</servlet-mapping>
or
@WebServlet({"/myServlet", "/myServlet2"})
public class MyServlet extends HttpServlet {
// ...
}
In this way, the MyServlet class is mapped to the two URLs /myServlet and /myServlet2, and the client can access this Servlet through http://localhost:8080/myServlet or http://localhost:8080/myServlet2
1.4 Servlet principle
Servlets and containers:
Servlet is a Java class that implements the javax.servlet.Servlet interface to handle client requests and responses. Servlet needs to run in a container that supports the Java Servlet specification, such as Tomcat, Jetty, etc. The container is responsible for loading, initializing, invoking and destroying Servlets, and providing some services and resources to Servlets
Servlet life cycle :
The life cycle of a Servlet refers to the process from the creation to the destruction of the Servlet, which includes the following stages:
Initialization: When the container receives a request for a Servlet for the first time, it will load and instantiate the Servlet, and call its init() method for initialization. This method will only be called once, throughout the lifetime.
Service: When the container receives a request for a Servlet, it calls its service() method to process the request and generate a response. This method will be called multiple times, and this method will be executed for each request. The service() method will call the corresponding doGet(), doPost(), doPut(), doDelete() and other methods according to the requested HTTP method (GET, POST, PUT, DELETE, etc.).
Destruction: When the container decides to unload a servlet, it calls its destroy() method to release resources and perform cleanup. This method will only be called once, at the end of the entire life cycle.
Servlet mapping :
Servlet mapping refers to the process of one-to-one correspondence between Servlet classes and URLs (links to front-end access servers)
Servlet mapping can be configured through XML files or annotations
Notice
Servlet request and response :
When the client sends an HTTP request to the server, the container creates a javax.servlet.ServletRequest object and a javax.servlet.ServletResponse object and passes them to the corresponding service() method.
The ServletRequest object encapsulates the data sent by the client, including parameters, attributes, header information, cookies, etc.
The ServletResponse object encapsulates the data returned by the server, including status code, header information, cookie, output stream, etc.
If it is the HTTP protocol, the ServletRequest and ServletResponse objects will be converted to javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse objects, providing more HTTP-related methods and properties
1.5Log (log)
Log (log), record the event information of application operation, count system operation status, efficiently locate and track problems, etc.
- Execution state changes
- System entry/exit
- Business exception
- unexpected execution
- Specific program run time
- Implementation progress
- … …
java.util.logging.Logger, a simple logging tool provided by Java, only uses the info() method. Later courses use a more powerful logging framework
1.6@WebServlet
2. Introduction to Servlet
2.0GET and POST
The post request provides parameters with the same syntax, except that it is located in the "body" part of the request, so it is difficult for users to see the Post request, and the parameters are encapsulated in the request body instead of the request address
2.1ServletContext
shared data·
The data I save in this servlet can be obtained in another servlet;
Get initialization parameters
request forwarding
read resource file
2.2 HttpServletResponse response
HttpServletResponse is an interface, which is used to encapsulate the HTTP response message, referred to as the response object. It has some methods to set the status code of the response, response headers, response body and redirection and other functions.
The method responsible for sending data to the browser
- You can use the response.getWriter() method to obtain a PrintWriter object for sending character text to the client, such as HTML tags or plain text.
- You can also use the response.getOutputStream() method to obtain a ServletOutputStream object for sending byte data to the client, such as binary files such as pictures, audio, and video.
The method responsible for sending response headers to the browser
- To set the character set of the response, you can use the response.setContentType() method to specify the content-type response header, such as response.setContentType("text/html;charset=utf-8").
- To achieve automatic page refresh or jump, you can use the response.setHeader() method to set the Refresh response header, such as response.setHeader("Refresh", "5; URL=www.baidu.com").
ResponseDownload file
Servlet part
package com.web;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
@WebServlet("/down")
public class Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取下载文件的路径
String filename = req.getParameter("filename");
System.out.println(filename);
String path = this.getServletContext().getRealPath("/dowmload/" + filename);
// 获取下载文件的文件名
filename = URLEncoder.encode(filename, "UTF-8"); // 处理中文文件名乱码问题
// 设置响应头,告诉浏览器要以下载的形式打开文件
resp.setHeader("content-disposition", "attachment;filename=" + filename);
// 设置响应内容类型为二进制流
resp.setContentType("application/octet-stream");
// 获取下载文件的输入流
FileInputStream in = new FileInputStream(path);
// 创建缓冲区
byte[] buffer = new byte[1024];
int len = 0;
// 获取输出流
OutputStream out = resp.getOutputStream();
// 将输入流中的数据写入缓冲区,再从缓冲区写入输出流
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
// 关闭输入流和输出流
in.close();
out.close();
}
}
JSP section
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>下载</title>
</head>
<body>
<a href=${pageContext.request.contextPath}/down?filename=1.jpg>1.jpg</a><br>
<a href=${pageContext.request.contextPath}/down?filename=2.txt>2.txt</a><br>
</body>
</html>
The href attribute should be "/down?filename=filename", not "dowmload/filename", so that you can call your Servlet class
/down? is a URL that represents the path and parameters of the Servlet class to be accessed. /down represents the annotation @WebServlet("/down") of your Servlet class, which tells the server the mapping path of this class. ? means that it is followed by parameters, such as filename=file1.txt, this parameter will be passed to the doGet method of your Servlet class, and then you can get the value of this parameter through req.getParameter(“filename”).
Response verification code
package com.web;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/img")
public class Servlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器5秒刷新一次?
resp.setHeader("refresh","3");
//在内存中创建图片
BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
//开始画图
Graphics2D g=(Graphics2D) image.getGraphics();
//设置图片背景颜色
g.setBackground(Color.white);
g.fillRect(0,0,100,50);
//写入验证码
g.setColor(Color.GREEN);
g.setFont(new Font(null, Font.PLAIN,20));
g.drawString(makeNumber(),0,25);
//高速浏览器,这个请求用图片的方式打开
resp.setContentType("image/png");
//设置不让浏览器缓存图片
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Program","no-cache");
//把图片写给浏览器
boolean write = ImageIO.write(image,"png", resp.getOutputStream());
}
//生成随机数
private String makeNumber(){
Random r = new Random();
String num=r.nextInt(99999999)+"";
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < 8-num.length(); i++) {
sBuffer.append("x");
}
return sBuffer.toString()+num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
Response implements redirection
The concept of redirection refers to redirecting network requests to other locations through various methods, such as webpage redirection, domain name redirection, etc. The principle of redirection is that the server sends a special response to the request, including a status code and a new URL. After the browser receives the response, it automatically loads the new URL. There are different types and application scenarios of redirection, such as permanent redirection, temporary redirection, domain name alias, site migration, etc.
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/r/img");//重定向
//拆分
/*
resp.setHeader("Location","/r/img");
resp.setStatus(302);
*/
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Replenish
Login judgment
package com.web;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/login")
public class Servlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入这个请求");
//处理请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+":"+password);
//重定向一定要注意路径问题
if (username.equals("admin") && password.equals("123456")){
System.out.println("登陆成功");
//请求转发
//转发:服务器把这个请求转向另外一个Servlet去处理; (地址栏不会变)
//RequestDispatcher ,需要使用RequestDispatcher来进行处理,我们需要获得这个类,参数为要转发到的页面
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}else {
req.getRequestDispatcher("/fail.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
Interview question: The difference between redirection and forwarding
- The same point,
the page will jump- Differences
When the request is forwarded, the url will not change
When redirected, the url address bar will change
2.3 Session
-
concept
In the Web, a session means opening a website from a browser, no matter what is done in this website, until closing the browser, this process is called a session.
-
How to count the end of the session
- client closed
- server destroyed
-
Why deal with sessions
Keep the session for a long time, no matter how many times the user closes the browser, this session exists (such as Huya's one-month login free)
-
Two Mechanisms for Saving Sessions
-
Cookie:
Cookie is a client-side mechanism, and the program writes each user's data to the user's respective browser in the form of a cookie. When users use a browser to access web resources in the server, they will bring their own data. In this way, the web resource processes the user's own data.
It's like a membership card given to users by a supermarket. You will know that you have been there before when you bring it next time.
-
Session
Session is a server-side technology. Using this mechanism, the server can create an exclusive session object for each user's browser at runtime. Since the session is exclusive to the user's browser, when the user accesses the server's web resources, You can put their own data in their own sessions, and when users go to access other web resources in the server, other web resources will fetch data from their respective sessions to serve users.
For example, a supermarket saves user information on its own system, and the user can just say the member name next time.
-
2.3.1Cookie
cookie: - - Generally, it will be saved in appdata in the local user directory;
Constructor:
Cookie cookie = new Cookie(String name,String value);
The server responds with Cookie to the client:
response.addCookie(Cookie);
The server checks whether the request brought by the user has a cookie
Cookie[] cookies = Request.getCookie();
//可以使用cookie来验证用户是否来过
//判断cookies是否为空,然后遍历即可
Cookie.getName();
Cookie.getValue();
Cookie test whether the user has come
package com.example01;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
@WebServlet("/c1")
public class ResponseHTMLServlet extends HttpServlet {
Boolean flag = false;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//避免乱码问题:
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
System.out.println("1");
//通过请求获取用户的Cookie
Cookie[] cookies = req.getCookies();
if (flag){
//flag=true,表示用户不是第一次访问该url
if (cookies!=null){
//你有cookie
for (int i = 0; i < cookies.length ; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals("lastLoginTime")){
long lastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime);
resp.getWriter().println("你上一次来的时间为:"+cookie.getValue());
out.write(date.toString());
}
}
}
}else {
//flag=false,表示用户是第一次访问该url
out.write("这是您第一次访问该页面");
}
//建立一个cookie,并把这个cookie发给客户端
resp.addCookie(new Cookie("lastLoginTime",System.currentTimeMillis()+""));
//将flag置为true,当用户再次访问该url时,会直接进入读取cookie的逻辑
flag = true;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
2.3.2Session
Session
It is a server-side technology . By default, a browser exclusively occupies ansession
object. Therefore, when user data needs to be saved, the server program can write the user data to the exclusive memory of the user's browser.session
When the user uses the browser to access other programs, other programs cansession
take the user's data from the user's memory to serve the user. . It can be generally understood that a user canSession
access multiple web resources through one web resource, and each web resource canSession
read saved user data.
Session
Implementation principlesession
: After the server is created , it will write backsession
the id number to the client incookie
the form of , so that as long as the client's browser is not closed, when it visits the server again, it will takesession
theid
id number with it, and the server will pass the identification The client browsersession_id
will use the corresponding one in memorysession
to serve it.In fact, once the client connects to the server, the server will automatically generate a session, and the session can transfer data in a session (that is, multiple programs obtain data through the session), if the server restarts , the data stored in the session will be lost .
Get the Session object
How to log out of Session?
If the session object is not used for 30 minutes by default, the server will automatically destroy the session
Session can be logged out in two ways:
- When you need to manually set the Session invalidation in the program, use invalidate(); to log out the current Session.
request.getSession().invalidate();
web.xml
Configure session expiration time in the file :<!-- 设置Session的有效时间:以分钟为单位--> <session-config> <session-timeout>15</session-timeout> </session-config>
Usage scenarios:
● Save information of a logged-in user;
● Shopping cart information;
● Data that is often used throughout the website, we save it in Session;
The difference between session and cookie
Cookie
It is to write the user's data to the user's browser, which belongs to the client technology .
Session
It is to write the user's data to the user's exclusive mediumsession
, which belongs to the server technology .
Session
The object is created by the server, and the developer can call the methodrequest
of the object to get the object.getSession
session
2.3.3 Scope
2.4PrintWriter
PrintWriter is a Java class for creating and writing files. It can be used to output different types of data, from basic types such as numbers and text, to arrays and objects
package com.example01;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/example01/responsehtml")
public class ResponseHTMLServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.getWriter()
.append("<!DOCTYPE html>\n")
.append("<html\">\n")
.append("<head>\n")
.append("<meta charset=UTF-8>\n")
.append("<title>Web开发技术</title>\n")
.append("</head>\n")
.append("<body><h1>Web开发技术</h1></body></html>");
}
}
example
package com.example01;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/responsehtml")
public class ResponseHTMLServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.print("hello");
}
}