Summary of JavaWeb servlet learning notes (I)

IT_ Holmes 2022-01-27 05:19:56 阅读数:267

summary javaweb servlet learning notes

1.Servlet Some steps

By implementing Servlet Interface to implement Servlet Program .

Servlet Life cycle of :
1. perform Servlet Constructor method .
2. perform init Initialization method .
3. perform service Method .
4. perform destroy Destruction method .

The first 1,2 Step : Is to create a call on the first access .
The first 3 Step : Is called every time you visit ,( For example, refresh the client ).
The first 4 Step :web Call when the project stops .

package com.test01;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class HelloServlet implements Servlet{

public HelloServlet() {

System.out.println("1. Constructor method ");
}
@Override
public void destroy() {

// TODO Auto-generated method stub
System.out.println("4.destory Method ");
}
@Override
public ServletConfig getServletConfig() {

// TODO Auto-generated method stub
return null;
}
@Override
public String getServletInfo() {

// TODO Auto-generated method stub
return null;
}
@Override
public void init(ServletConfig config) throws ServletException {

// TODO Auto-generated method stub
System.out.println("2. Initialization method ");
}
//service Methods are designed to handle requests and responses .
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

System.out.println("3. service Method ");
//ServletRequest There's nothing in the method getMethod() Method, but its sub interface HttpServletRequest There is .
HttpServletRequest httpServletRequset = (HttpServletRequest)req;
// How to get the client request :
String method = httpServletRequset.getMethod();
if("GET".equals(method)) {

doGet();
}else if("POST".equals(method)) {

doPost();
}
}
// This method is used to perform the acquisition get Operation after request 
public void doGet() {

System.out.println(" For receiving GET After the request , This method is used to perform get Method .");
}
// This method is used to perform post Operation after request 
public void doPost() {

System.out.println(" For receiving POST After the request , This method is used to perform POST Method .");
}
}

2.Servlet Medium service Method

GET and POST Distribution request steps :

//service Methods are designed to handle requests and responses .
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

System.out.println("3. service Method ");
//ServletRequest There's nothing in the method getMethod() Method, but its sub interface HttpServletRequest There is .
HttpServletRequest httpServletRequset = (HttpServletRequest)req;
// How to get the client request :
String method = httpServletRequset.getMethod();
if("GET".equals(method)) {

doGet();
}else if("POST".equals(method)) {

doPost();
}
}

3. Web.xml Some configuration of

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>WebTest02</display-name>
<!-- servlet Label to Tomcat To configure Servlet Program -->
<servlet>
<!-- servlet-name Label to Servlet The program has an alias , It is generally set to class name . -->
<servlet-name>HelloServlet</servlet-name>
<!-- servlet-class The label is Servlet The full class name of the program . -->
<servlet-class>com.test01.HelloServlet</servlet-class>
</servlet>
<!-- servlet-mapping Label to servlet Program configuration access address -->
<servlet-mapping>
<!-- servlet-name Function of label : Tell the server , Which address do I currently configure Servlet Program usage . With the above name Don't confuse -->
<servlet-name>HelloServlet</servlet-name>
<!-- url-pattern Function of label : Configure access address . -->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>`

4. By inheritance HttpServlet Realization Servlet Program


In addition to the implementation Servlet Interface , And through inheritance HttpServlet Realization Servlet Program .

  • 1. Write a class inheritance HttpServlet class .
  • 2. Rewrite according to business needs doGet or doPost Method .
  • 3. To web.xml Configuration in Servlet Program access address .

Usually create servlet Program , We can go straight to IDEA or eclise In the direct new One servlet Program , Define the configuration information , Pay attention to is 3.0 After the version is the annotation version ,2.5 It used to be xml Don't confuse the version .

5. Servlet Interface , GenericServlet class , HttpServlet Relationships between classes


 Insert picture description here

Pay attention to is : HttpServlet There are service() Method , And there will be judgments, such as get still post, To carry out doGet or doPost Method , So we just need to inherit HttpServlet, rewrite doGet and doPost that will do .

6. ServletConfig

6.1 ServletConfig Classes and ServletContext Class differences


ServletConfig and ServletContext( Containers ) It's the opposite .
ServletConfig It's all for private use , Defined in that servlet in , that servlet You can get the above parameter values ;
and ServletContext Containers are shared , Set in the webapp Home directory ! be-all servlet You can call .

6.2 ServletConfig class Use


ServletConfig Class is Servlet Configuration information class .

It has three functions :
Can get Servlet Program alias ,servlet-name Value .
Get initialization parameters init-param.
obtain ServletContext object .


This category is generally in init() In the method :

package com.test01;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class HelloServlet implements Servlet{

public HelloServlet() {

System.out.println("1. Constructor method ");
}
@Override
public void destroy() {

System.out.println("4.destory Method ");
}
@Override
public ServletConfig getServletConfig() {

return null;
}
@Override
public String getServletInfo() {

return null;
}
@Override
public void init(ServletConfig config) throws ServletException {

System.out.println("2. Initialization method ");
//1. obtain servlet-name Alias value :
System.out.println(" An alias for :"+config.getServletName());
//2. Get initialization parameters init-name:
System.out.println(" Initialize parameters username The value of is :"+config.getInitParameter("username"));
System.out.println(" Initialize parameters url Value :"+config.getInitParameter("url"));
//3. obtain ServletContext object 
System.out.println(config.getServletContext());
}
//service Methods are designed to handle requests and responses .
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

System.out.println("3. service Method ");
//ServletRequest There's nothing in the method getMethod() Method, but its sub interface HttpServletRequest There is .
HttpServletRequest httpServletRequset = (HttpServletRequest)req;
// How to get the client request :
String method = httpServletRequset.getMethod();
if("GET".equals(method)) {

doGet();
}else if("POST".equals(method)) {

doPost();
}
}
// This method is used to perform the acquisition get Operation after request 
public void doGet() {

System.out.println(" For receiving GET After the request , This method is used to perform get Method .");
}
// This method is used to perform post Operation after request 
public void doPost() {

System.out.println(" For receiving POST After the request , This method is used to perform POST Method .");
}
}

ServletConfig An object can define its own , You don't have to use init Parameter in method .

ServletConfig con = getServletConfig();
String str = con.getInitParameter("[ Corresponding init-param Another name for ]");

The above corresponds to web.xml Of init-param The label is as follows :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>WebTest02</display-name>
<!-- servlet Label to Tomcat To configure Servlet Program -->
<servlet>
<!-- servlet-name Label to Servlet The program has an alias , It is generally set to class name . -->
<servlet-name>HelloServlet</servlet-name>
<!-- servlet-class The label is Servlet The full class name of the program . -->
<servlet-class>com.test01.HelloServlet</servlet-class>
<!-- init-param The function is to initialize parameters -->
<init-param>
<!-- Parameter name -->
<param-name>username</param-name>
<!-- Parameter values -->
<param-value>root</param-value>
</init-param>
<init-param>
<!-- Parameter name -->
<param-name>url</param-name>
<!-- Parameter values -->
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</init-param>
</servlet>
<!-- servlet-mapping Label to servlet Program configuration access address -->
<servlet-mapping>
<!-- servlet-name Function of label : Tell the server , Which address do I currently configure Servlet Program usage . With the above name Don't confuse -->
<servlet-name>HelloServlet</servlet-name>
<!-- url-pattern Function of label : Configure access address . -->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>HelloServlet02</servlet-name>
<servlet-class>com.test01.HelloServlet02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet02</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
</web-app>

In summary :Servlet Program and ServletConfig Objects are created by Tomcat Created , We are only responsible for using .

Servlet By default, the program is created the first time it is accessed ,ServletConfig Is each Servlet When the program is created , Just create a corresponding ServletConfig object .


In other ways through getServletConfig() You can also get the current Servlet programmatic ServletConfig object .

package com.test01;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet02 extends HttpServlet{

@Override
public void init(ServletConfig config) throws ServletException {

// TODO Auto-generated method stub
super.init(config); //
System.out.println(" Rewrote init Method , The main attention is to inherit the parent class init Method , Pass on config Parameters !!!"
+ " Or the following getServletConfig() Methods will report mistakes !");
// Why do things turn out like this? , Just read the source code .
}
/* * doGet() The method is in get Call when requested . */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

System.out.println("HelloServlet2 Of doGet Method ");
// In other ways through getServletConfig() You can also get the current Servlet programmatic ServletConfig object .
ServletConfig sc = getServletConfig();
System.out.println(sc);
}
/* * doPost() The method is in Post Call when requested . */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

System.out.println("HelloServlet2 Of doPost Method ");
}
}

We need to pay attention to , One Servlet There is only one program ServletConfig object , They are one-to-one correspondence , Don't mix up. .

7. ServletContext class

7.1 ServletConfig Classes and ServletContext Class differences


Here I'm emphasizing the difference between the two :

ServletConfig and ServletContext( Containers ) It's the opposite .
ServletConfig It's all for private use , Defined in that servlet in , that servlet You can get the above parameter values ;
and ServletContext Containers are shared , Set in the webapp Home directory ! be-all servlet You can call .

7.2 What is? ServletContext?

ServletContext It's an interface , He said Servlet Context object .

One web engineering , only one ServletContext Object instances ( Single design ).

ServletContext Object is a domain object .
( What is domain object , It's like map equally , Objects that can store data , It's called a domain object . The domain here refers to the operating range of accessing data .)

 Insert picture description here

7.3 ServletContext The role of ?

I said that before ServletContext It's like a sharing operation , be-all servlet Programs can be used , The attribute value in .

context-param The configuration is as follows :( It is configured in webapp In the label !)

<context-param>
<param-name>username</param-name>
<param-value>context</param-value>
</context-param>

Also use getServletContext() Method call :

ServletContext servletContext = getServletContext();
String initParameter = servletContext.getInitParameter("jdbc.driver");
System.out.println(initParameter);
//ServletContext servletContext2 = getServletConfig().getServletContext();
// This method is no different from the above , Just look at the source code .

1. obtain web.xml The context parameters configured in the context-param.
2. Get the current project path , Format :/ Project path .
3. Get the absolute path on the server hard disk after project deployment .
4. image map Can store data as well .


The first three steps :

package com.test01;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ContextServlet extends HttpServlet{

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

//1. obtain web.xml The context parameters configured in the context-param.
ServletContext context = getServletConfig().getServletContext();
String name = context.getInitParameter("username");
System.out.println("context-param Parameters username The parameter value of is :"+ name);
System.out.println("context-param Parameters password The parameter value of is :"+context.getInitParameter("password"));
//2. Get the current project path , Format :/ Project path .
System.out.println(" Get the current project path :"+context.getContextPath());
//3. Get the absolute path on the server hard disk after project deployment .
/* * Parameters here "/", The slash is resolved by the server :http://ip:port/ project name / . * Why can we get the absolute path address value through the diagonal bar ? * He is a mapping to web In the catalogue , Need to know tomcat Some details , remember "/" Represents the location of the current path of the current disk . * Of course, you can also set other relative paths for him through this current path , for example "/CSS", Is to expand a path down . */
System.out.println(" Get the path of the project to the hard disk on the server :"+context.getRealPath("/"));
System.out.println(" Get the path of the project to the hard disk on the server :"+context.getRealPath("/CSS"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>WebTest02</display-name>
<!-- context-param Is the context parameter ( It belongs to the whole world web engineering ) -->
<context-param>
<param-name>username</param-name>
<param-value>context</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>root</param-value>
</context-param>
<!-- init-param The function is to initialize parameters -->
<init-param>
<!-- Parameter name -->
<param-name>username</param-name>
<!-- Parameter values -->
<param-value>root</param-value>
</init-param>
<init-param>
<!-- Parameter name -->
<param-name>url</param-name>
<!-- Parameter values -->
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>ContextServlet</servlet-name>
<servlet-class>com.test01.ContextServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextServlet</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>

Step four : Store the data

package com.test01;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ContextServlet01 extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

ServletContext context = getServletContext();// It can also be called directly getServletContext It's OK , The source code still needs to call getServletConfig().
// Before saving, no matter what string value is null
System.out.println(" Before saving :Context1 obtain key1 The value of is :"+context.getAttribute("key1"));
context.setAttribute("key1", "value");
// Because there is only one project ServletContext object , Once set up , This can be accessed after accessing or other objects ServletContext The content attribute value of the object .
System.out.println("Context1 Get domain data from key1 The value of is :"+context.getAttribute("key1"));
System.out.println("Context1 Get domain data from key1 The value of is :"+context.getAttribute("key1"));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>WebTest03</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>username</param-name>
<param-value>context</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>root</param-value>
</context-param>
<servlet>
<description></description>
<display-name>ContextServlet01</display-name>
<servlet-name>ContextServlet01</servlet-name>
<servlet-class>com.test01.ContextServlet01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextServlet01</servlet-name>
<url-pattern>/context1</url-pattern>
</servlet-mapping>
<!-- If executed above ServletContext01 To set the content of ServletContext Properties of , We can also be in ContextServlet02 Get property value within class , Because it's singleton mode , only one ServletContest object .-->
<servlet>
<description></description>
<display-name>ContextServlet02</display-name>
<servlet-name>ContextServlet02</servlet-name>
<servlet-class>com.test01.ContextServlet02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextServlet02</servlet-name>
<url-pattern>/context2</url-pattern>
</servlet-mapping>
</web-app>

7.4 Thermal deployment ( Thermal loading )


Here's an explanation of hot loading and hot deployment , Hot loading is when we are tomcat After deploying the project , We modify the code in the project ,tomcat Will automatically heat load , Remove and reload the project , This process is called thermal loading . This deployment is called hot deployment .

Besides , Note that hot loading only loads { } What's inside , Modify method permissions , Add method , modify web.xml You can't touch it . This will restart tomcat;

7.5 tomcat Associated source code


We want to see the source code , Just look at tomcat Medium servlet-api It can't be , Because it's full of .class Bytecode file , We need to see that the source code must be .java file , So we're going to tomcat The official download src The source code can associate them attach get up , To view the source code !

 Insert picture description here

image Servlet,GenericServlet,HttpServlet It's all in tomcat Medium , We don't bring our own , therefore , First set , We want to add library Medium server runtime.

 Insert picture description here

8. Http agreement


The data sent by the client to the server is called a request .
The data returned by the server to the client is called response .

http Yes 8 Request format in :
 Insert picture description here


The request is divided into GET Request and POST Ask for two .

GET The format of the requested message is as follows :
 Insert picture description here

POST The format of the requested message is as follows :
 Insert picture description here

9. When to use doGet Accept get request , When to use doPost Accept post request ?

The following are common special cases :
 Insert picture description here

10. Responsive HTTP Form of agreement

 Insert picture description here

11. Response code Status description

 Insert picture description here

12. MIME Type specification

MIME yes HTTP Data types in the protocol .

 Insert picture description here

13. HttpServletRequest object


Every time you have a request to enter Tomcat The server ,Tomcat The server will report the request HTTP The protocol information is parsed and packaged to Request In the object , Then pass it on to service() Method (doGet and doPost) For us to use .

We can go through HttpServletRequest object , Get all the requested information .

Once per request , Just create one HttpServletRequest object , The request is completed and destroyed .


HttpServletRequest Some methods corresponding to the object :

package com.test.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestAPIServlet extends HttpServlet{

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//request.getRequestURI(): Get the requested resource path .
System.out.println(" Get the requested resource path :"+request.getRequestURI());
//request.getRequestURL()): Get the requested uniform resource locator ( Absolute path ).
System.out.println(" Get the requested uniform resource locator ( Absolute path ):"+request.getRequestURL());
//request.getRemoteHost(): Gets the name of the requesting client ip Address .
/* * Use localhost or 127.0.0.1 During the interview , Naturally obtained client ip Namely 127.0.0.1 * If you use real ip During the interview , Then what you get is also true ip Address value of .*/
System.out.println(" Get the client ip Address :"+request.getRemoteHost());
//request.getHeader("xxx"): Get the information in a specific request header .
System.out.println(" Get request header User-Agent Information about :"+request.getHeader("User-Agent"));
//request.getMethod(): Get request method .
System.out.println(" Get request method :"+request.getMethod());
}
}

14. How to accept parameter requests sent by clients ?

Need to use getParameter() and getParameterValues() Method :


package com.test.servlet;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ParameterServlet extends HttpServlet{

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

//req.getParameter("xxx") Method : Get request parameters 
String username = req.getParameter("username");
String password = req.getParameter("password");
//req.getParameterValues("xxx"): Also get request parameters , But when multiple values are sent .
/* * image input Of checkbox type , You can perform a multiple selection operation , Send multiple parameters to the server at the same time .*/
String[] hobby = req.getParameterValues("hobby");
System.out.println(" user name :"+username);
System.out.println(" password :"+password);
System.out.println(" Hobby :"+Arrays.asList(hobby));
}
}

Be careful , When you call post request , Send data to client , If you send Chinese characters , It's going to be messy !

Use req.setCharacterEncoding(“UTF-8”) To solve the problem of garbled code .

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

// Set the character set of the request body to UTF-8, So as to solve post Chinese garbled problem of request .
// This api The method must be called before accepting the request content. , The request content is still garbled , Like the one below username,password Wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait, wait , The method must be executed before it can be free from garbled code !!
req.setCharacterEncoding("UTF-8");
System.out.println("-------doPost--------");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobby = req.getParameterValues("hobby");
System.out.println(" user name :"+username);
System.out.println(" password :"+password);
System.out.println(" Hobby :"+Arrays.asList(hobby));
}

15. Request forwarding

What is request forwarding ?
Request forwarding means , After the server receives the request , Jump from one resource to another .

 Insert picture description here


Servlet1 and Servlet2 Request forwarding :

Servlet1:

package com.test.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet{

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

// Processing request parameters 
String username = req.getParameter("username");
System.out.println("Servlet1( Counter 1) View processing parameters ( material ):"+username);
// to username, With the , Affix a seal as a sign 
req.setAttribute("key1", " Counter 1 Chapter of ");
System.out.println(" The seal has been stamped ");
// Asking directions : towards Servlet2 In dealing with 
/* * Here, the request forwarding must be in "/" Diagonal bar start , It represents :http://ip:port/ project name */
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servlet2");
System.out.println(" know servlet2 Where is it ");
// trend servlet2
requestDispatcher.forward(req, resp);
}
}

Servlet2:

package com.test.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet{

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

String username = req.getParameter("username");
System.out.println("Servlet2( Counter 2) View parameters in ( material ):"+username);
// Must be with Servlet1 It's the same as the key !
Object key1 = req.getAttribute("key1");
System.out.println(" Counter 1 Whether there is a chapter :"+key1);
// Deal with your own business 
System.out.println("Servlet2 Deal with your own business ");
}
}

 Insert picture description here

matters needing attention :
1. image WEB-INF This directory can no longer be accessed directly by the browser , However, it can be accessed indirectly through request forwarding .
2. He is not allowed to access resources other than the project ! because "/" The inclined pole represents the beginning of the current project , If you want to visit again www.baidu.com That's impossible .

16. base label effect


Request conversion jump page , If you use …/…/ This operation will not return to the desired page , Here's why :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
This is a a Under the b Under the c.html page <br>
<!-- Notice the ../../ Relative paths , It refers to the last time you came to the current page url route , Instead of following the path on the server side !!! -->
<!-- For example, by using request transformation to operate the page that jumps over , Then he compares the request to convert the access at that time url Address comparison . -->
<a href="../../index.html"> Jump back to home page </a>
<a href="a/b/c.html"> Request forwarding :a/b/c.html</a>
</body>
</html>

So in this case , You use base label .

In addition, pay attention to the following two situations :
http://127.0.0.1:8080/WebTest04/a/b/
http://127.0.0.1:8080/WebTest04/a/b
this b There is a difference between having a diagonal bar at the back and not having a diagonal bar ! A diagonal bar indicates that it is a catalogue , No, it's just a file .

17. " / ", The function of diagonal bar is different in different scenes

 Insert picture description here

On the browser side , Diagonal bars represent :http://ip:port/

Resolve on the server , Diagonal bars represent :http://ip:port/ project name /

stay Servlet in ,Web.xml Configured url-pattern A diagonal bar in the middle , Represents that there is no... To visit url Then access the class pointed to ( Specific view ,20 Add ).

18. HttpServletResponse class

18.1 HttpServletResponse Introduction to and Two response flows


HttpServletResponse Classes and HttpServletRequest Class is the same , Every time I ask to come in ,Tomcat A common server is Response Object passed to Servlet Program usage .HttpServletRequest Accept the requested information ;HttpServletResponse Is the response message .

If we need to set the information returned to the client , Both can pass HttpServletResponse Object to set .


Two response flows , A byte stream , A character stream .

Byte stream : response.getOutputStream() , Binary system

Character stream :response.getWriter() , character

Two streams can only call one !

18.2 How to send data back to the client


Create a character or byte stream , call print() or write() Method send data .

package com.test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ResponseIOServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter write = response.getWriter();
// Transfer data to the client , use write or print Fine 
//write.print("");
write.write("response's content");
}
}

Respond to the problem of Chinese garbled code :

Mode one : By setting the server character set and browser character set

package com.test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ResponseIOServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// Check it out. , The default character set for the response :
//System.out.println(response.getCharacterEncoding());//ISO-8859-1, This character set does not support 
// Here we set the character set of the server , It may not match the character set of the browser or client , However, we can set the browser character set by setting the response header 
// Set the server character set 
response.setCharacterEncoding("UTF-8");;
// Set browser character set ( Set... By response header )
response.setHeader("Content-Type", "text/html; charset=UTF-8");
PrintWriter write = response.getWriter();
// Transfer data to the client , use write or print Fine 
//write.print("");
write.write(" Zhang San ");
}
}

Mode two :response.setContentType() Method , This method is to both server and client ( Response head ) Character set for .

But this method must be in getting the stream (writer or print Method ) Set up before , Otherwise, useless is equivalent to no setting .

package com.test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ResponseIOServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// One line of code , Directly replace the above two lines .
response.setContentType("text/html; charset=UTF-8");
PrintWriter write = response.getWriter();
write.write(" Zhang San ");
}
}

19. request redirections

19.1 The first way

request redirections , The client sends a request to the server , Then the server gives the client address , Let the client go to the new address to access .( Because the previous address may be abandoned )

The steps of redirection are simple , as follows :
 Insert picture description here


We visit Response1 when , Relocate to Response2 :

response1:

package com.test.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Response1 extends HttpServlet{

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

System.out.println("Resonse1, Going on it ");
// Set response status code 302, Indicates redirection , Has been removed 
resp.setStatus(302);
// Set the response header to indicate where the new address is 
resp.setHeader("Location", "http://localhost:8080/WebTest04/response2");
}
}

response2:

package com.test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Response2 extends HttpServlet{

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

resp.setContentType("text/html; charset=UTF-8");
PrintWriter write = resp.getWriter();
write.write(" Li Si ");
}
}

matters needing attention :
This is equivalent to the browser sending two requests , Therefore, it should be understood that the front and back are not shared by one object !

19.2 The second way ( Recommended )

response.sendRedirect() Method directly defines redirection .

package com.test.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Response1 extends HttpServlet{

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

System.out.println("Resonse1, Going on it ");
resp.sendRedirect("http://localhost:8080/WebTest04/response2");
}
}

20. Servlet Add

20.1 load-on-startup label


By default ,Servlet The life cycle is , After the project starts , Create... On first visit Servlet object , Execute... After creation init Method .

however , We can set load-on-startup Attribute let servlet Create... When the project starts .

load-on-startup The default is negative ( Default :-1) , A negative number represents the first access to create . If we set it to be greater than or equal to 0 The book of , It means that the server is created when it starts .

 Insert picture description here

20.2 url-pattern Set to \ The role of


url-pattern Set to \ The role of , The function is very simple, which is to reveal the bottom , For example, the user sends it from the browser url No such address , Then it will find <url-pattern>/</url-pattern> Corresponding class to execute .

 Insert picture description here
Be careful : These are not the same as the one in front " / " The role is confused .

20.3 adopt Server modify tomcat The default path


 Insert picture description here

copyright:author[IT_ Holmes],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/01/202201270519170623.html