当前位置:网站首页>Servlet details
Servlet details
2022-06-24 22:13:00 【Xiao Zhang to learn】
Catalog
Servlet It's a kind of Realize dynamic pages Technology . It's a group. Tomcat Provided to the program API, Help program ape develop a simple and efficient web app. Dynamic page and static page :
Static page That is, a page whose content is always fixed . Even if the users are different / Time is different / The input parameters are different , The content of the page will not change . ( Unless the developer of the website changes the source code , Otherwise, the content of the page remains the same ).
Dynamic pages Refers to Different users / Time is different / The input parameters are different , The content of the page will change .
Servlet Namely Tomcat This HTTP The server is provided to Java A group of API, To complete Build dynamic pages This task .
One 、 first Servlet Program
1.1 Create project
Use IDEA Create a Maven project .
- menu -> file -> New projects -> Maven
1.2 Introduce dependencies
Maven After the project is created , It will automatically generate a pom.xml file . We need to be in pom.xml Introduction in Servlet API Rely on the jar package .
1) In the central warehouse https://mvnrepository.com/ Mid search “servlet”, Generally, the first result is :
2) Choose the version . Generally we use 3.1.0 edition :
Servlet And the version of Tomcat matching . If we use Tomcat 8.5, Then we need to use Servlet 3.1.0
Can be in http://tomcat.apache.org/whichversion.html Query version correspondence .
3) Put the... Provided in the central warehouse xml Copy to project's pom.xml in . Must put xml write in dependencies Inside .
The modified pom.xml by :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>servlet_project</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<packaging>war</packaging>
<build>
<finalName>hello102</finalName>
</build>
</project>
<dependencies>Inside the tag, the item depends on jar package . maven The dependency will be automatically downloaded to the local
1.3 Create directory
When the project is created , IDEA Will help us automatically create some directories .
here , Still need to create :
- establish
webappCatalog
stay main Under the table of contents , and java Directory juxtaposition , Create awebappCatalog .
2) establishweb.xml
And then inwebappCreate a... Inside the directoryWEB-INFCatalog , And create aweb.xmlfile .
- To write
web.xml
Go toweb.xmlCopy the following code in .
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
webapp Directory is the future deployment to Tomcat An important directory in . At present, we can go to webapp Put some static resources in , such as html , css etc. .
There is also an important file in this directory web.xml. Tomcat Only when this file is found can it be handled correctly webapp Dynamic resources in .
1.4 Write code
stay java Create a class in the directory HelloServlet, The code is as follows :
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;
/** * Created With IntelliJ IDEA * Description: * Users: yyyyy * Date: 2022-05-20 * Time: 9:57 */
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello world");
resp.getWriter().write("hello world" + System.currentTimeMillis());
}
}
- Create a class
HelloServlet, Inherited fromHttpServlet. - Add... Above this class
@WebServlet("/hello")annotation , ExpressTomcatOf the requests received , Path is/helloWill only callHelloServletThe code for this class . ( This path does not containContext Path) - rewrite
doGetMethod .doGetThere are two parameters to , respectively received HTTP request And the... To be constructed HTTP Respond to . This method will be inTomcatreceivedGETTrigger on request . HttpServletRequestExpress HTTP request . Tomcat according to HTTP The format of the request is character string The request in the format is transformed into aHttpServletRequestobject . Later, I want to get the information in the request ( Method , url, header, body etc. ) Are obtained through this object .HttpServletResponseExpress HTTP Respond to . Construct the response object in the code ( Construct the status code of the response , header,body etc. )resp.getWriter()Will get a stream object , Through this stream object, you can write some data , The written data will be constructed into a HTTP Responsive body part ,TomcatWill turn the entire response into a string , adoptsocketWrite back to the browser .
1.5 packaged applications
Use maven package . open maven window ( Generally in IDEA On the right you can see Maven window , If you can't see it , Can pass menu -> View -> Tool Window -> Maven open ), And then unfold Lifecycle , double-click package You can pack it .
After successful packing , You can see in the target Under the table of contents , It generates a jar package , In this way jar The bag is not what we need , Tomcat What needs to be identified is another war Packet format .
war Bao He jar The difference between packages
jar The bag is ordinary java The result of program packaging . It will contain some .class file .
war Bag is java web The program , It will contain .class Outside the document , It also includes HTML, CSS, JavaScript, picture , And others jar package . become involved war Package format can only be Tomcat distinguish .
therefore , Need to be in pom.xml One more in packing label , Indicates that the way of packing is to make a war package , stay pom.xml Add another one in build label , Built in one finalName label , It means to play war The name of the bag is hello102( The complete code is as follows 1.2 As shown in ):
Reuse maven pack , You can see the new war The result of the package :
1.6 The deployment process
hold war Package copy to Tomcat Of webapps Under the table of contents . start-up Tomcat , Tomcat Will automatically put war Packet decompression .
A more convenient deployment method , Direct use of Smart Tomcat Plugins can also :

1.7 Verification procedure
At this point, access through the browser http://127.0.0.1:8080/hello102/hello, And you can see the result .
URL Medium PATH Divided into two parts , among hello102 by Context Path, hello by Servlet Path.
When did the browser send GET request ?
- Directly in the address bar , Input URL
- adopt a Tag jump ~
- adopt img/link/script…
- adopt form Forms , method Designated as GET
- adopt ajax, type Designated as GET
When did the browser send POST request ?
- adopt form Forms , method Designated as POST
- adopt ajax, type Designated as POST
Two 、Servlet Operation principle
stay Servlet In our code, we didn't write main Method , So the corresponding doGet How is the code called ? How the response is returned to the browser ?

When the browser sends a request to the server , Tomcat As HTTP The server , You can receive this request .
HTTP Server (Tomcat) Calling Servlet, Especially when processing requests .
HTTP As an application layer protocol , The underlying protocol stack is needed to support the work . As shown in the figure below

Tomcat It's actually an application . Normal processes running in user mode (Tomcat It's actually a Java process ).
Code written by the user ( Calculate the corresponding... According to the request ), adopt Servlet and Tomcat Interact .Tomcat Further network transmission with the browser , It is still the same set of network principles that I learned before ( Packaging and distribution ).
- Receiving request :
- The user enters a URL, At this point, the browser will construct a HTTP request .
- This HTTP The request will be made layer by layer through the network protocol stack encapsulation It's binary bit flow , Finally, it is converted into optical signal through the hardware equipment of the physical layer / Electrical signals are transmitted out .
- These optical signals carrying information / Electrical signals pass through a series of network devices on the Internet , Finally reach the target host ( This process also requires the participation of network layer and data link layer ).
- The server host receives these optical signals / Electrical signals , It will be carried out layer by layer through the network protocol stack Divide up , Layers of analysis , Finally, it is reduced to HTTP request . And to Tomcat Process to process ( Determine the process according to the port number )
- Tomcat adopt Socket Read this request ( A string ), And in accordance with the HTTP The format of the request to parse the request , according to In the request Context Path Confirm one webapp, Again adopt Servlet Path Identify a specific class . Then according to the method of the current request (GET/POST/…), Decide to call this class doGet perhaps doPost Other methods . At this point in our code doGet / doPost The first parameter of the method HttpServletRequest It includes this HTTP Details of the request .
- Calculate the response according to the request :
In ourdoGet / doPostIn the method , Then we execute our own code . Our own code will be based on some information in the request , Here it isHttpServletResponseObject to set some properties . For example, the status code , header, body etc. . - Return response :
- our
doGet / doPostAfter execution , Tomcat Will automatically putHttpServletResponseThe object we just set up is converted into an object that conforms to HTTP The string of the protocol , adopt Socket Send this response . - At this time, the response data passes through the network protocol stack on the host of the server encapsulation , Finally, we get a binary bit flow , It is converted into optical signal through physical layer hardware equipment / Electrical signals are transmitted out .
- These optical signals carrying information / Electrical signals pass through a series of network devices on the Internet , Finally arrive at the host where the browser is located ( This process also requires the participation of network layer and data link layer ).
- The browser host receives these optical signals / Electrical signals , It will be carried out layer by layer through the network protocol stack
Divide up, Layers of analysis , Finally, it is reduced to HTTP Respond to , And give it to the browser for processing . - Browsers also pass Socket Read this response ( A string ), according to HTTP The format of the response . And the body The data in the browser is displayed on the browser interface according to a certain format .
3、 ... and 、Tomcat The pseudo code
Tomcat Initialization flow :
- Give Way Tomcat First, find all the... To be loaded from the specified directory
Servletclass , During the previous deployment , It's aServletThe code is compiled into.class, And then I hitwarpackage , Then copied towebappsInside ,TomcatIt will start fromwebappsTo find those.classCorresponding Servlet class , And it needs to be loaded . - According to the result of class loading just now , Create... For these classes
Servletexample . - After the instance is created , You can call the current
ServletExample ofinitThe method .init yesServletOwn method . By default init Do nothing . We are inheriting aHttpServletWhen , You can also rewrite it yourselfinit, You can do some initialization for us at this stage . - establish
TCP socket, monitor 8080 port , Wait for a client to connect . - If the loop exits ,Tomcat It's coming to an end . Each... Will be called in a loop in turn
ServletOfdestroyMethod .
Tomcat Process request :
Servlet Of service Method implementation :
class Servlet {
public void service(HttpServletRequest req, HttpServletResponse resp) {
String method = req.getMethod();
if (method.equals("GET")) {
doGet(req, resp);
} else if (method.equals("POST")) {
doPost(req, resp);
} else if (method.equals("PUT")) {
doPut(req, resp);
} else if (method.equals("DELETE")) {
doDelete(req, resp);
}
......
}
}
Servlet Of service Method will be based on the currently requested method , Decide to call one of them doXXX Method .
Calling doXXX Method time , It will trigger polymorphic Mechanism , So as to execute... In our own subclass doXXX Method
In the whole process above , It relates to Servlet Key methods , There are three main ones .
init: Initialization phase , After the object is created , It will be carried out to . The user can override this method , To perform some initialization logic .service: Call... During the request processing phase . Every time a request comes, it must be calledservicedestroy: Exit the main loop ,tomcatCall... Before the end , To release resources .
The above several key methods , It's called Servlet Life cycle of .
Four 、Servlet API Detailed explanation
4.1 HttpServlet
The core approach :
Code example : Handle GET request
Create a MethodServlet class :
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;
@WebServlet("/method")
public class MethodServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
resp.getWriter().write("post Respond to ");
}
}
Create a test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script> $.ajax({
type: 'post', url: 'method', success: function (body) {
console.log(body); } }); </script>
</body>
</html>
Enter... In the browser URL, Access page :
You can see the results in the console :
4.2 HttpServletRequest
When Tomcat adopt Socket API Read HTTP request ( character string ), And in accordance with the HTTP The format of the protocol parses the string into HttpServletRequest object .
HttpServletRequest It corresponds to a HTTP request .HTTP What is in the request , There's something here .HttpServletResponse It corresponds to a HTTP Respond to .HTTP What is in the response , There's something here .
The core approach :
| Method | describe |
|---|---|
| String getProtocol() | Returns the name and version of the request protocol |
| String getMethod() | Return requested HTTP Method name , for example ,GET、POST or PUT |
| String getRequestURI() | From the name of the agreement to HTTP In the query string of the first line of the request , Return the requested URL Part of |
| String getContextPath() | Returns a request indicating the context of the request URI part . |
| String getQueryString() | Return the request contained after the path URL The query string in , Get the complete query string |
| Enumeration getParameterNames() | Return to one String Enumeration of objects , The name of the parameter contained in the request , Get everything key, With Enum In the way of . |
| String getParameter(String name) | Returns the value of the request parameter as a string , Or if the parameter does not exist, return null , according to key Come and get it value |
| String[] getParameterValues(String name) | Returns an array of string objects , Contains the values of all given request parameters , If the parameter does not exist, return null |
| Enumeration getHeaderNames() | Returns an enumeration , Include all headers included in the request |
| String getHeader(String name) | Returns the value of the specified request header as a string |
| String getCharacterEncoding() | Returns the name of the character encoding used in the request body |
| String getContentType() | Return the MIME type , If you don't know the type, return null |
| int getContentLength() | Returns the length of the request body in bytes , And provide input stream , Or if the length is unknown, return -1 |
| InputStream getInputStream() | Used to read the requested body Content . Return to one InputStream object |
Through the above methods, you can get information about all aspects of a request .
Be careful : The request object is the content received by the server , Should not modify . Therefore, the above methods are just “ read ” Method , instead of " Write " Method .
Code example : Print request information
Create a showRequest class :
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.util.Enumeration;
@WebServlet("/showRequest")
public class ShowRequest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<h3> First line </h3>");
stringBuilder.append(req.getProtocol());
stringBuilder.append("<br>");
stringBuilder.append(req.getMethod());
stringBuilder.append("<br>");
stringBuilder.append(req.getRequestURI());
stringBuilder.append("<br>");
stringBuilder.append(req.getContextPath());
stringBuilder.append("<br>");
stringBuilder.append(req.getQueryString());
stringBuilder.append("<br>");
stringBuilder.append("<h3>header part </h3>");
Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()){
String headerName = headerNames.nextElement();
String headerValue = req.getHeader(headerName);
stringBuilder.append(headerName + ": " + headerValue + "<br>");
}
resp.setContentType("text/html; charset=utf-8");
resp.getWriter().write(stringBuilder.toString());
}
}
The deployment process . In the browser through URL http://127.0.0.1:8080/hello102/showRequest visit , You can see :
Code example : obtain GET Parameters in the request :
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;
@WebServlet("/getParameter")
public class GetParameter extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userId = req.getParameter("userId");
String classId = req.getParameter("classId");
resp.getWriter().write("userId = " + userId + ", classId = " + classId);
}
}
Enter... On the web page URL:http://127.0.0.1:8080/hello102/getParameter, You will get the following page : When there is no query string When , getParameter The value obtained is null.
Input URL:http://127.0.0.1:8080/hello102/getParameter?userId=10&classId=20
You can see :
This indicates that the server has obtained the parameters passed by the client .
obtain POST Parameters in the request (1)
POST The requested parameters are generally through body Pass it to the server . body There are many data formats in :
x-www-form-urlencoded
If the request is in this format , How the server obtains parameters and GET equally , It's also getParameter.
How to construct a request in this format at the front end ?
- form Forms
use form The form of the form , Can still pass getParameter Get the value of the parameter .
First, create the class PostGetParameterServlet class :
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;
@WebServlet("/postGetParameter")
public class PostGetParameterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Suppose the parameters passed from the front end are userId = 10&classId = 20
String userId = req.getParameter("userId");
String classId = req.getParameter("classId");
resp.getWriter().write("userId = " + userId + ", classId = " + classId);
}
}
Then create tes.html, Put it in webapp Directory :
<form action="postGetParameter" method="post">
<input type="text" name="userId">
<input type="text" name="classId">
<input type="submit" value=" Submit ">
</form>
Enter... In the browser URL:http://127.0.0.1:8080/hello102/test.html, And click the submit button , You can see the jump to a new page , And display the data just passed in .

2) postman
- json
about body yes json In this format , Manual processing is troublesome , Third party libraries can be used to directly handle json Format data . The main library used here is calledJackson(SpringOfficially recommended Library ), adoptmavenholdjacksonThis library , Download to local and import into the project .

stay pom.xml Introduction in jackson rely on :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>servlet_project</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.6.1</version>
</dependency>
</dependencies>
<packaging>war</packaging>
<build>
<finalName>hello102</finalName>
</build>
</project>
obtain POST Parameters in the request (2)
If POST In the request body Is in accordance with the JSON In the format of , Then the code that gets the parameters needs to be adjusted .
- In the browser front-end code (
test.html) in , adopt js Construct out body by json Format request
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- structure json Format request -->
<input type="text" name="userId">
<input type="text" name="classId">
<input type="button" value=" Submit " id="submit">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script> let userIdInput = document.querySelector('#userId'); let classIdInput = document.querySelector('#classId'); let button = document.querySelector('#submit'); button.onclick = function() {
$.ajax({
type: 'post', url: 'postJson', contentType: 'application/json', data: JSON.stringify({
userId: userIdInput.value, classId: classIdInput.value }), success: function(body) {
console.log(body); } }); } </script>
</body>
</html>
2) stay java In the back-end code , adopt jackson To process
need Use jackson Put the request body Read out the data in , And resolve into Java Objects in the .
import com.fasterxml.jackson.databind.ObjectMapper;
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;
class User{
public int userId;
public int classId;
}
@WebServlet("/postJson")
public class PostJsonServlet extends HttpServlet {
// Create a json Core objects of
private ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//2. Read body The request , And then use objectMapper To parse into the required object
//readValue Is to put json Format string to java The object of
// The first parameter converts that parameter , The second parameter indicates that this json Format string to which java object
User user = objectMapper.readValue(req.getInputStream(),User.class);
resp.getWriter().write("userId = " + user.userId + ", classId = " + user.classId);
}
}

readValue How to complete the conversion ?
1. The first getInputStream The data in the corresponding stream object is read ;
2. Aiming at this json String parsing , From a string => Key value pair ;
3 Traverse the key value pair , Get each one in turn key . According to this key Name , and User Compare the attribute names in the class , See if there is a matching name !! If a matching attribute is found , Put the current key Corresponding value Assign to this User In the properties of class ( In the process of assignment, type conversion will be carried out at the same time ), If there is no matching attribute , Just skip. , Take down one key.
4. When all key value pairs have been traversed , here User The object is almost constructed .
4.2 HttpServletResponse
Servlet Medium doXXX Method The purpose of is to calculate the corresponding according to the request , Then set the response data to HttpServletResponse In the object . then Tomcat It will HttpServletResponse Object according to HTTP Form of agreement Convert to a string , And pass Socket Write back to the browser .
The core approach :
Code example : Set status code
Implement a program , The user specifies the status code to return the response through parameters in the browser .
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;
@WebServlet("/status")
public class StatusServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(200);
resp.getWriter().write("hello");
}
}

Status code returned by the server , Just telling the browser , What is the current response status . It does not affect the browser to display as usual body The content in .
Code example : Automatically refresh
Implement a program , Let the browser refresh automatically every second . And display the current timestamp .
establish AutoRefreshServlet class :
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;
@WebServlet("/autoRefresh")
public class AutoRefreshServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Refresh","1");
resp.getWriter().write("timeStamp" + System.currentTimeMillis());
}
}
The deployment process , adopt URL :http://127.0.0.1:8080/hello102/autoRefresh visit , can
To see the browser automatically refresh every second :
Code example : Redirect
Implement a program , Return a redirect HTTP Respond to , Automatically jump to another page .
establish RedirectServlet class :
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;
@WebServlet("/redirect")
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Implement redirection , Let the browser automatically jump to Sogou browser
resp.setStatus(302);
resp.setHeader("Location","https://www.sogou.com");
// Another simpler way to write redirects
//resp.sendRedirect("https://www.sogou.com");
}
}
Browser interface input URL:http://127.0.0.1:8080/hello102/redirect, You can see the page Jump to Sogou homepage :
Code example : Server version confession wall
For the confession wall , It mainly provides two interfaces :
- Tell the server , What kind of data is left in the current message ( When the user clicks the submit button . Will send a message to the server HTTP request , Let the server save this message )
Appointment good , To achieve this effect , What does the client want to send HTTP request , What kind of HTTP Respond to .
Spread out according to the above ideas , There are countless ways to agree Request format !! Method can be changed , The path can change , The name of the parameter can also be changed .

We take the following request here , How to respond :
- Get... From the server , What is the current message data ( When the page loads , You need to get the stored message content from the server )

After determining the interface , You can write code , You need to write back-end code , You also need to write front-end code .
Objects and JSON Conversion between strings Java:
objectMapper.readValue hold json String to object
objectMapper.writeValueAsString Turn the object into json character string JS:
JSON.parse hold json String to object JSON.
stringify Turn the object into json character string
Create database :
边栏推荐
- 为什么有的程序员能力一般却能拿到好offer?
- That is to say, "live broadcast" is launched! One stop live broadcast service with full link upgrade
- Resolving the conflict problem of the flutter Library
- A deep learning model for urban traffic flow prediction with traffic events mined from twitter
- TCP RTT测量妙计
- C language - keyword 1
- LINQ query collection class introductory cases Wulin expert class
- [untitled]
- Reduce the pip to the specified version (upgrade the PIP through pycharm, and then reduce it to the original version)
- Jianmu continuous integration platform v2.5.0 release
猜你喜欢

L2 元年,Arbitrum Nitro 升级带来更兼容高效的开发体验

嵌入式开发:技巧和窍门——干净地从引导加载程序跳转到应用程序代码

【OpenCV 例程200篇】209. HSV 颜色空间的彩色图像分割

权限想要细化到按钮,怎么做?

Filtered data analysis

leetcode:55. 跳跃游戏【经典贪心】

想当测试Leader,这6项技能你会吗?
![[notes of Wu Enda] multivariable linear regression](/img/b1/60a702aaca58b0afa57ac2f552dabf.png)
[notes of Wu Enda] multivariable linear regression

You are using pip version 21.1.2; however, version 22.1.2 is available

代理模式详解
随机推荐
代理模式详解
Junior college background, 2 years in Suning, 5 years in Ali. How can I get promoted quickly?
03--- antireflective film
旅行商问题(TSP)的相关论文总结
How does flutter use the online transcoding tool to convert JSON to model
零代码即可将数据可视化应用到企业管理中
Heartless sword Chinese English bilingual poem 003 The sea of books
Yida technology signed a contract with seven wolves to help the digital transformation of "Chinese men's wear leader"
字符串习题总结2
Summary of papers on traveling salesman problem (TSP)
Want to be a test leader, do you know these 6 skills?
Excel layout
EasyBypass
02--- impossible phenomenon of longitudinal wave
PostMan工具介绍及安装使用
The leader of ERP software in printing industry
直播软件app开发,左右自动滑动的轮播图广告
Cannot find reference 'imread' in 'appears in pycharm__ init__. py‘
St Table + two points
leetcode:515. 在每个树行中找最大值【无脑bfs】