Article Directory
- 1. Getting Started with Servlet Development
- Three, ServletConfig and ServletContext
-
- (1) ServletConfig interface
- (2) ServletContext interface
-
- 1. Obtain the initialization parameters of the web application
- 2. Case demonstration Obtaining the container initialization parameters of the web application
- 3. Implement multiple Servlet objects to share data
- 4. The case demonstrates that multiple Servlet objects share data
- 5. Read the resource files under the web application
- 6. Case demonstration to read the resource files under the web application
- Four, HttpServletResponse object
- Five, HttpServletResponse application
- Six, HttpServletRequest object
1. Getting Started with Servlet Development
(1) Realize the first Servlet program
Goal: Master how to use IDEA tools to develop Servlet programs
1. Use IDEA to complete the development of Servlet
In actual development, IDEA (or Eclipse, etc.) tools are usually used to complete the development of Servlets. We use IDEA to complete the development of Servlets, because IDEA will not only automatically compile Servlets, but also automatically create web.xml file information to complete the mapping of Servlet virtual paths.
(1) Create a new Web project
Select the "Create New Project" option on the IDEA homepage to enter the interface for creating a new project.
In the New Project interface, select the "Java" option on the left column, and then check the "Web Application" option. After the selection is complete, click the "Next" button to enter the interface for filling in the project information.
In the New Project interface, the "Project name" option is used to refer to the name of the project, and the "Project localtion" option is used to specify the root directory of the Web project. The root directory of the project is set to D:\web_work\chapter04, and WebDemo is used as the name of the web project. After the setting is complete, click the "Finish" button to enter the development interface.
Modify the Artifact name - WebDemo
edit Tomcat server configuration
Switch to the [Server] tab
Start the server to view the effect
(2) Create a Servlet class
Create a new net.huawei.servlet package
and create the ServletDemo01 class in the net.huawei.servlet package.
At this point, the IDEA tool will automatically generate the Servlet code.
In order to better demonstrate the running effect of the Servlet, add some codes to the doGet() and doPost() methods of ServletDemo01. Set the urlPatterns attribute value in the @WebServlet annotation: urlPatterns = "/demo01"
package net.huawei.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 功能:Servlet演示类
* 作者:华卫
* 日期:2023年03月12日
*/
@WebServlet(name = "ServletDemo01", urlPatterns = "/demo01")
public class ServletDemo01 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取字符输出流
PrintWriter out = response.getWriter();
// 输出信息
out.print("<h1>Hello Servlet World~</h1>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
In fact, a Servlet is essentially an HTML page embedded in a Java program.
(3) Start the Servlet
Start the server and display the home page
Access the url address "localhost:8080/WebDemo/demo01"
corresponding to the ServletDemo01 class on the page
If you want to display a red message and display it in the center, you need to use the style
2. Classroom exercise - Create a Web project and use Servlet to display personal information
Create a Java Enterprise project
Set the project name and save location
Click the [Finish] button
to see the name of the Artifacts
Change the name to ShowInfo
Configure the tomcat server
Delete ShowInfo in the Deployment and add it again
Switch to the [Server] tab, view the URL
Start the tomcat server
, and check the effect Modify the home page file to display personal information in a table
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>个人信息</title>
</head>
<body>
<table style="text-align: center" border="1" align="center" cellpadding="5">
<tr>
<td>学号</td>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>专业</td>
<td>班级</td>
<td>手机</td>
</tr>
<tr>
<td>20210201</td>
<td>陈燕文</td>
<td>女</td>
<td>18</td>
<td>软件技术专业</td>
<td>2021软件2班</td>
<td>15890456780</td>
</tr>
</table>
</body>
</html>
Start the server and check the results
Create a net.huawei.servlet package and create an InfoServlet class in the package
package net.huawei.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 功能:显示个人信息
* 作者:华卫
* 日期:2023年03月31日
*/
@WebServlet(name = "InfoServlet", urlPatterns = "/info")
public class InfoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取字符输出流
PrintWriter out = response.getWriter();
// 往客户端输出信息
out.print("<!DOCTYPE html>");
out.print("<html>");
out.print("<head>");
out.print("<meta charset='UTF-8'");
out.print("<title>个人信息</title>");
out.print("</head>");
out.print("<body style='text-align: center'>");
out.print("<table border='1' align='center' cellpadding='5'>");
out.print("<tr>");
out.print("<td>学号</td>");
out.print("<td>姓名</td>");
out.print("<td>性别</td>");
out.print("<td>年龄</td>");
out.print("<td>专业</td>");
out.print("<td>班级</td>");
out.print("<td>手机</td>");
out.print("</tr>");
out.print("<tr>");
out.print("<td>20210201</td>");
out.print("<td>陈燕文</td>");
out.print("<td>女</td>");
out.print("<td>18</td>");
out.print("<td>软件技术专业</td>");
out.print("<td>2021软件2班</td>");
out.print("<td>15890456780</td>");
out.print("</tr>");
out.print("</table>");
out.print("</body>");
out.print("</html>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Start the tomcat server, visit http://localhost:8080/ShowInfo/info
page, there are Chinese garbled characters, you need to set the character encoding (to view the default character encoding of the Chrome browser), set the character encoding of the response object
to UTF-8, which is consistent with the character encoding currently used by the browser Restart the tomcat
server, visit http://localhost:8080/ShowInfo/info
Regardless of the character encoding currently used by the browser, set the content type of the response object to require the browser to use the specified character encoding Restart Tomcat server, visit
http://localhost:8080/ShowInfo/info
to view the character encoding currently used by the browser, which has been changed to GBK
(2) Servlet configuration
Goal: Master two ways to complete the Servlet configuration: through the configuration file web.xml of the Web application, and through the @WebServlet annotation to complete the Servlet configuration. If you want the Servlet to
run correctly in the server and process the request information, you must perform appropriate configuration. There are two main ways to configure the Servlet, which are to complete the configuration through the Web application configuration file web.xml and use the @WebServlet annotation.
1. Use web.xml to configure Servlet
In the web.xml file, registration is performed through tags, and several sub-elements are included under the tags.
Map the Servlet to the URL address, use the label to map, and use the sub-label to specify the name of the Servlet to be mapped. The name must be the same as the one registered under the label before; use the sub-label to map the URL address, and "/" must be added before the address, otherwise it cannot be accessed.
Register the Servlet in the deployment description file web.xml, then you can comment out the annotation on the InfoServlet class.
Restart the tomcat server and visit http://localhost:8080/ShowInfo/info
2. @WebServlet annotation attribute
The @WebServlet annotation is used to replace the etc. tags in the web.xml file. This annotation will be processed by the container during project deployment, and the container will deploy the corresponding class as a Servlet according to the specific attribute configuration. For this, the @WebServlet annotation provides some attributes.
The @WebServlet annotation can be marked on any class that inherits the HttpServlet class, which belongs to the class-level annotation. The InfoServlet class is annotated with the @WebServlet annotation below.
Comment out the registration tag for InfoServlet in the web.xml file.
Restart the tomcat server, visit http://localhost:8080/ShowInfo/info
and use the @WebServlet annotation to mark the InfoServlet class as a Servlet. The name attribute value in the @WebServlet annotation is used to specify the name attribute of the servlet, which is equivalent to, if the name attribute of @WebServlet is not set, its default value is the full class name of the Servlet. The urlPatterns attribute value is used to specify the matching pattern of a set of servlet urls, which is equivalent to a label. If you need to set multiple properties in the @WebServlet annotation, separate them with commas. The @WebServlet annotation can greatly simplify the configuration steps of Servlet and reduce the development difficulty of developers.
3. Configure multiple urls for a Servlet
It's like a person has multiple external contact methods
Start the server, visit http://localhost:8080/ShowInfo/info
visit http://localhost:8080/ShowInfo/message
(3) Servlet life cycle
Goal: Master the three life cycles of Servlet, initialization phase, running phase and destruction phase
1. Servle life cycle - initialization phase
When the client sends an HTTP request to the Servlet container to access the Servlet, the Servlet container will first parse the request to check whether the Servlet object already exists in the memory, and if so, use the Servlet object directly; It should be noted that in the entire life cycle of the Servlet, its init () method is only called once.
2. Servlet life cycle - running phase
This is the most important stage in the Servlet life cycle. At this stage, the Servlet container will create a ServletRequest object representing the HTTP request and a ServletResponse object representing the HTTP response for the client request, and then pass them as parameters to the Servlet's service() method. The service() method obtains the client request information from the ServletRequest object and processes the request, and generates a response result through the ServletResponse object. During the entire life cycle of the Servlet, for each access request of the Servlet, the Servlet container will call the service () method of the Servlet once, and create new ServletRequest and ServletResponse objects, that is, the service () method will be called multiple times during the entire life cycle of the Servlet.
3. Servlet life cycle - destruction phase
When the server is shut down or the web application is removed from the container, the servlet is destroyed along with the web application. Before destroying the Servlet, the Servlet container will call the Servlet's destroy() method to allow the Servlet object to release the resources it occupies. The destroy() method is also called only once during the entire life cycle of the Servlet. It should be noted that once the Servlet object is created, it will reside in memory and wait for the client's access. The Servlet object will not be destroyed until the server is closed or the web application is removed from the container.
4. Case demonstration Servlet life cycle
Create the ServletDemo02 class in the WebDemo project, write the init() method and the destroy() method in the ServletDemo02 class, and rewrite the service() method to demonstrate the execution effect of the Servlet life cycle method.
package net.huawei.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 功能:演示Servlet生命周期
* 作者:华卫
* 日期:2023年03月12日
*/
@WebServlet(name = "ServletDemo02", value = "/demo02")
public class ServletDemo02 extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("init()方法被调用……");
}
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("service()方法被调用……");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<h1>演示Servlet生命周期~</h1>");
}
@Override
public void destroy() {
System.out.println("destroy()方法被调用……");
}
}
Start the tomcat server, visit http://localhost:8080/WebDemo/demo02
to refresh the browser twice, visit ServletDemo02 twice, and view the print results of the tomcat console.
The init() method is only executed at the first visit, and the service() method is executed at each visit.
If you want to remove ServletDemo02, you can stop the WebDemo project in IDEA. At this time, the Servlet container will call the destroy() method of ServletDemo02, and the message "destroy() method was called..." will be printed on the IDEA console.
For example: we can only be born once (init() method), die once (destroy() method), and can change jobs many times in the middle to provide different services to the society (service() method).
Three, ServletConfig and ServletContext
(1) ServletConfig interface
Goal: Master how to use ServletConfig to obtain configuration information
1. ServletConfig interface
During the running of Servlet, some configuration information is often needed, such as the encoding used by the file, etc., which can be configured in the attributes of the @WebServlet annotation. When Tomcat initializes a Servlet, it will encapsulate the configuration information of the Servlet into a ServletConfig object, and pass the ServletConfig object to the Servlet by calling the init(ServletConfig config) method. ServletConfig defines a series of methods to obtain configuration information.
2. Case demonstration ServletConfig method call
Take the getInitParameter() method as an example to explain the invocation of the ServletConfig method
Create the ServletDemo03 class in the net.huawei.servlet package of the WebDemo project
package net.huawei.servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
/**
* 功能:演示ServletConfig方法的调用
* 作者:华卫
* 日期:2023年03月31日
*/
@WebServlet(name = "ServletDemo03", urlPatterns = "/demo03",
initParams = {@WebInitParam(name="encoding", value = "utf-8"),
@WebInitParam(name="text-color", value = "red"),
@WebInitParam(name="font-size", value= "25")})
public class ServletDemo03 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应对象内容类型
response.setContentType("text/html; charset=utf-8");
// 获取打印输出流
PrintWriter out = response.getWriter();
// 获取Servlet配置对象
ServletConfig config = getServletConfig();
// 获取初始化参数名枚举对象
Enumeration<String> initParams = config.getInitParameterNames();
// 遍历初始化参数名枚举对象,输出参数名及其值
while (initParams.hasMoreElements()) {
String initParam = initParams.nextElement();
out.print(initParam + " : " + config.getInitParameter(initParam) + "<br />");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Start the tomcat server and visit http://localhost:8080/WebDemo/demo03
(2) ServletContext interface
Goal: Master the usage of ServletContext interface
1. Obtain the initialization parameters of the web application
When the Servlet container starts, a unique ServletContext object will be created for each web application to represent the current web application. The ServletContext object not only encapsulates all the information of the current Web application, but also realizes the sharing of data among multiple Servlets.
In the web.xml file, you can configure the initialization information of the Servlet, and you can also configure the initialization information of the entire Web application. The configuration method of the initialization parameters of the web application is as follows.
<context-param>
<param-name>参数名</param-name>
<param-value>参数值</param-value>
</context-param>
<context-param>
<param-name>参数名</param-name>
<param-value>参数值</param-value>
</context-param>
The element is located in the root element, and its child elements are used to specify the name and parameter value of the parameter. The parameter name and parameter value can be obtained respectively by calling the getInitParameterNames() and getInitParameter(String name) methods defined in the ServletContext interface.
2. Case demonstration Obtaining the container initialization parameters of the web application
In the web.xml file of the WebDemo project, configure container initialization parameter information and Servlet information
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>college</param-name>
<param-value>泸州职业技术学院</param-value>
</context-param>
<context-param>
<param-name>address</param-name>
<param-value>泸州市龙马潭区长桥路2号</param-value>
</context-param>
<context-param>
<param-name>secretary</param-name>
<param-value>何杰</param-value>
</context-param>
<context-param>
<param-name>president</param-name>
<param-value>谢鸿全</param-value>
</context-param>
</web-app>
Create the ServletDemo04 class in the net.huawei.servlet package
package net.huawei.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
/**
* 功能:获取Web应用的容器初始化参数
* 作者:华卫
* 日期:2023年03月31日
*/
@WebServlet(name = "ServletDemo04", urlPatterns = "/demo04")
public class ServletDemo04 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应对象内容类型
response.setContentType("text/html; charset=utf-8");
// 获取打印输出流
PrintWriter out = response.getWriter();
// 获取Servlet容器对象
ServletContext context = getServletContext();
// 获取容器的初始化参数名枚举对象
Enumeration<String> paramNames = context.getInitParameterNames();
// 通过循环遍历显示全部参数名与参数值
while (paramNames.hasMoreElements()) {
// 获取参数名
String name = paramNames.nextElement();
// 按参数名获取参数值
String value = context.getInitParameter(name);
// 输出参数名和参数值
out.print(name + " : " + value + "<br />");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Start the tomcat server and visit http://localhost:8080/WebDemo/demo04
3. Implement multiple Servlet objects to share data
Since all Servlets in a Web application share the same ServletContext object, the domain attributes of the ServletContext object can be accessed by all Servlets in the Web application. The ServletContext interface defines four methods for adding, deleting, and setting ServletContext domain attributes.
4. The case demonstrates that multiple Servlet objects share data
Create the ServletDemo05 class in the net.huawei.servlet package
package net.huawei.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 功能:写入域属性
* 作者:华卫
* 日期:2023年03月31日
*/
@WebServlet(name = "ServletDemo05", urlPatterns = "/demo05")
public class ServletDemo05 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应对象内容类型
response.setContentType("text/html; charset=utf-8");
// 获取Servlet容器对象
ServletContext context = getServletContext();
// 写入域属性
context.setAttribute("id", "20210201");
context.setAttribute("name", "陈雅雯");
context.setAttribute("gender", "女");
context.setAttribute("age", "18");
context.setAttribute("major", "软件技术专业");
context.setAttribute("class", "2021软件2班");
context.setAttribute("telephone", "15890903456");
// 获取打印输出流
PrintWriter out = response.getWriter();
// 输出提示信息
out.print("<h3>成功地写入了域属性~</h3>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Create the ServletDemo06 class in the net.huawei.servlet package
package net.huawei.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
/**
* 功能:读取域属性
* 作者:华卫
* 日期:2023年03月31日
*/
@WebServlet(name = "ServletDemo06", urlPatterns = "/demo06")
public class ServletDemo06 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应对象内容类型
response.setContentType("text/html; charset=utf-8");
// 获取打印输出流
PrintWriter out = response.getWriter();
// 获取Servlet容器对象
ServletContext context = getServletContext();
// 获取全部域属性名枚举对象
Enumeration<String> attributeNames = context.getAttributeNames();
// 通过循环显示域属性名与域属性值
while (attributeNames.hasMoreElements()) {
// 获取域属性名
String name = attributeNames.nextElement();
// 获取域属性值
Object value = context.getAttribute(name);
// 输出域属性名与域属性值
out.print(name + " : " + value + "<br />");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Start the tomcat server, first visit http://localhost:8080/WebDemo/demo05
and then visit http://localhost:8080/WebDemo/demo06
There are many domain attributes that we did not write, if we only want to display the domain attributes we wrote, then we need to modify the code of ServletDemo06 Restart the server, visit http://localhost:8080/WebDemo/demo05 and then visit http://localhost:8080/WebDemo/
demo0
6
5. Read the resource files under the web application
The ServletContext interface defines some methods for reading Web resources, which are implemented by the Servlet container. The servlet container returns the IO stream of the associated resource file, the absolute path of the resource file in the file system, etc. according to the path of the resource file relative to the web application.
6. Case demonstration to read the resource files under the web application
Create a property file - college.properties in the net.huawei.servlet package
name = 泸州职业技术学院
address = 泸州市龙马潭区长桥路2号
secretary = 何杰
president = 谢鸿全
Create the ServletDemo07 class in the net.huawei.servlet package
package net.huawei.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
/**
* 功能:读取资源文件
* 作者:华卫
* 日期:2023年03月13日
*/
@WebServlet(name = "ServletDemo07", urlPatterns = "/demo07")
public class ServletDemo07 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置内容类型
response.setContentType("text/html; charset=utf-8");
// 获取Servlet容器对象
ServletContext context = getServletContext();
// 获取打印输出流
PrintWriter out = response.getWriter();
// 读取资源文件,得到字节输入流
InputStream in = context.getResourceAsStream(
"/WEB-INF/classes/net/huawei/servlet/college.properties");
// 创建属性对象(Map接口的实现类)
Properties pros = new Properties();
// 属性对象加载资源文件的资源文件输入流
pros.load(in);
// 往客户端输出属性值
out.println("name = " + pros.getProperty("name") + "<br />");
out.println("address = " + pros.getProperty("address") + "<br />");
out.println("secretary = " + pros.getProperty("secretary") + "<br />");
out.println("president = " + pros.getProperty("president") + "<br />");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Start the tomcat server and visit http://localhost:8080/WebDemo/demo07
The path problem of the property file.
The encoding of the byte stream obtained by reading the property file is ISO-8859-1, and a transcoding process is required.
Restart the tomcat server and visit http://localhost:8080/WebDemo/demo07.
In the development of web projects, developers may need to obtain the absolute path of resources. Obtain the absolute path of the resource file by calling the getRealPath(String path) method.
Create the ServletDemo08 class in the net.huawei.servlet package
package net.huawei.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 功能:获取资源的绝对路径
* 作者:华卫
* 日期:2023年03月13日
*/
@WebServlet(name = "ServletDemo08", urlPatterns = "/demo08")
public class ServletDemo08 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取Servlet容器对象
ServletContext context = getServletContext();
// 获取打印输出流
PrintWriter out = response.getWriter();
// 创建资源路径字符串
String path = "/WEB-INF/classes/net/huawei/servlet/college.properties";
// 获取资源绝对路径
String realPath = context.getRealPath(path);
// 输出资源绝对路径
out.println("college.properties: " + realPath);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Restart the tomcat server and visit http://localhost:8080/WebDemo/demo08
Four, HttpServletResponse object
3. Case demonstration to send response message body
Create the net.huawei.response package
Create the PrintServlet01 class in the net.huawei.response package
package net.huawei.response;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
/**
* 功能:演示响应体输出字节流
* 作者:华卫
* 日期:2023年04月07日
*/
@WebServlet(name = "PrintServlet01", urlPatterns = "/print01")
public class PrintServlet01 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 定义字符串数据
String data = "欢迎访问泸州职业技术学院~";
// 获取字节输出流对象
OutputStream out = response.getOutputStream();
// 往客户端输出信息
out.write(data.getBytes());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Restart the tomcat server, visit http://localhost:8080/WebDemo/print01
and create the PrintServlet02 class in the net.huawei.response package
package net.huawei.response;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 功能:演示响应体打印字符流
* 作者:华卫
* 日期:2023年04月07日
*/
@WebServlet(name = "PrintServlet02", urlPatterns = "/print02")
public class PrintServlet02 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 定义字符串数据
String data = "欢迎访问泸州职业技术学院~";
// 获取打印字符流
PrintWriter out = response.getWriter();
// 往客户端输出信息
out.println(data);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Restart the tomcat server and visit http://localhost:8080/WebDemo/print02
In order to solve the problem of Chinese garbled characters on the page, modify the code
Restart the tomcat server and visit http://localhost:8080/WebDemo/print02
Five, HttpServletResponse application
2. Case demonstration to realize request redirection
Create the login page - login.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登录</title>
</head>
<body>
<form action="login" method="post">
<fieldset>
<legend>用户登录</legend>
<table cellpadding="2" align="center">
<tr>
<td align="right">用户名:</td>
<td>
<input type="text" name="username"/>
</td>
</tr>
<tr>
<td align="right">密码:</td>
<td>
<input type="password" name="password"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Create a welcome page - welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录成功</title>
</head>
<body>
<h3 style="text-align: center">欢迎你,登录成功~</h3>
</body>
</html>
Create a LoginServlet class in the net.huawei.response package to process user login requests
package net.huawei.response;
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;
/**
* 功能:登录处理程序
* 作者:华卫
* 日期:2023年04月07日
*/
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html; charset=utf-8");
// 获取登录表单提交的用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 判断是否登录成功,决定重定向到不同页面
if ("howard".equals(username) && "903213".equals(password)) {
// 重定向到欢迎页面
response.sendRedirect("/WebDemo/welcome.html");
} else {
// 重定向到登录页面
response.sendRedirect("/WebDemo/login.html");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Restart the tomcat server, visit http://localhost:8080/WebDemo/login.html,
fill in the user name "howard" and password "903213" on the login.html page,
click the login button, and jump to the welcome page
Click the login button, jump to the welcome page
2. Case demonstration to solve the problem of garbled characters
Create a ChineseServlet class in the net.huawei.response package
package net.huawei.response;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 功能:演示解决中文乱码问题
* 作者:华卫
* 日期:2023年03月13日
*/
@WebServlet(name = "ChineseServlet", urlPatterns = "/chinese")
public class ChineseServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 创建数据字符串
String data = "欢迎访问泸州职业技术学院~";
// 获取打印字符输出流
PrintWriter out = response.getWriter();
// 在页面输出信息
out.println(data);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Restart the tomcat server and visit http://localhost:8080/WebDemo/chinese
The contents displayed by the browser are all "???~", indicating that garbled characters have occurred. The reason for the garbled characters here is that the character output stream of the response object uses the ISO-8859-1 character code table when encoding. When the browser decodes the received data, it will use the default code table GB2312 to decode "63" into "?". Therefore, the browser displays the twelve characters of "Welcome to Luzhou Vocational and Technical College" as "???".
Solve the page garbled problem
The HttpServletResponse interface provides a setCharacterEncoding() method, which is used to set the character encoding method. Next, modify the ChineseServlet class. Add a line of code before the code String data = "Welcome to Luzhou Vocational and Technical College~"; and set the code table used for character encoding to utf-8.
The contents displayed by the browser are all "???~", indicating that garbled characters have occurred. The reason for the garbled characters here is that the character output stream of the response object uses the ISO-8859-1 character code table when encoding. When the browser decodes the received data, it will use the default code table GB2312 to decode "63" into "?". Therefore, the browser displays the twelve characters of "Welcome to Luzhou Vocational and Technical College" as "???".
Solve the page garbled problem
The HttpServletResponse interface provides a setCharacterEncoding() method, which is used to set the character encoding method. Next, modify the ChineseServlet class. Add a line of code before the code String data = "Welcome to Luzhou Vocational and Technical College~"; and set the code table used for character encoding to utf-8.
Restart the tomcat server and visit http://localhost:8080/WebDemo/chinese.
Although the garbled characters displayed in the browser are not "??? ", it is not the "Welcome to Luzhou Vocational and Technical College " that needs to be output. This is due to the decoding error of the browser. The encoding method of the character output stream of the response object is UTF-8, and the decoding method used by the browser is GBK.
Change the encoding method of the character output stream setting of the response object to GBK
Changing the encoding method of the character output stream setting of the response object to GBK is
a better way to solve the problem of Chinese garbled characters on the page, and directly ask the browser to display Chinese in accordance with a certain character encoding
.
Restart the tomcat server and visit http://localhost:8080/WebDemo/chinese
// 设置HttpServletResponse使用utf-8编码
response.setCharacterEncoding("utf-8");
// 通知浏览器使用utf-8解码
response.setHeader("Content-Type", "text/html;charset=utf-8");
Six, HttpServletRequest object
(1) Relevant methods for obtaining request line information
Goal: Master the method of using the HttpServletRequest interface to get the request line
1. Related methods
Method declaration function description
String getMethod( ) This method is used to obtain the request method in the HTTP request message (such as GET, POST, etc.) String getRequestURI( ) This method is used to obtain the resource name part in the request line, that is, the data String after the host and port of the URL and before the parameter part. The protocol name and version, such as HTTP/1.0 or HTTP
/1.1 String getContextPath( ) This method is used to obtain the path belonging to the Web application in the request URL. This path starts with "/", which means relative to the root directory of the entire Web site, and does not end with "/ " . If the request URL belongs to the root directory of the Web site, the return result is an empty string ("") String getServletPath( ) This method is used to obtain the name of the Servlet or the path mapped by the Servlet String getRemoteAddr( ) This method is used to obtain the IP address of the requesting client, and its format is similar to "192.168.0.3" String getRemoteHost( ) This method is used to obtain the complete host name of the requesting client, its format is similar to "pc1.itc ast.cn". It should be noted that if the complete host name of the client cannot be resolved, this method will return the client's IP address. int getRemotePort() This method is used to obtain the port number of the requesting client's network connection String getLocalAddr() This method is used to obtain the IP address of the current requesting network connection on the Web server
Note that the result returned by the getRequestURL() method is a StringBuffer type, not a String type, which makes it easier to modify the result
2. Case demonstration
Create the net.huawei.request package, and create the RequestLineServlet class in the package
package net.huawei.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;
import java.io.PrintWriter;
/**
* 功能:输出请求行的相关信息
* 作者:华卫
* 日期:2023年03月13日
*/
@WebServlet(name = "RequestLineServlet", urlPatterns = "/request")
public class RequestLineServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html;charset=utf-8");
// 获取字符输出流
PrintWriter out = response.getWriter();
// 获取并输出请求行的相关信息
out.println("getMethod: " + request.getMethod() + "<br />");
out.println("getRequestURI: " + request.getRequestURI() + "<br />");
out.println("getQueryString: " + request.getQueryString() + "<br />");
out.println("getProtocol: " + request.getProtocol() + "<br />");
out.println("getContextPath: " + request.getContextPath() + "<br />");
out.println("getPathInfo: " + request.getPathInfo() + "<br />");
out.println("getPathTranslated: " + request.getPathTranslated() + "<br />");
out.println("getServletPath: " + request.getServletPath() + "<br />");
out.println("getRemoteAddr: " + request.getRemoteAddr() + "<br />");
out.println("getRemoteHost: " + request.getRemoteHost() + "<br />");
out.println("getRemotePort: " + request.getRemotePort() + "<br />");
out.println("getLocalAddr: " + request.getLocalAddr() + "<br />");
out.println("getLocalName: " + request.getLocalName() + "<br />");
out.println("getLocalPort: " + request.getLocalPort() + "<br />");
out.println("getServerName: " + request.getServerName() + "<br />");
out.println("getServerPort: " + request.getServerPort() + "<br />");
out.println("getScheme: " + request.getScheme() + "<br />");
out.println("getRequestURL: " + request.getRequestURL() + "<br />");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Restart the tomcat server and visit http://localhost:8080/WebDemo/request
getContextPath: /WebDemo + getServletPath: /request = getRequestURI: /WebDemo/request getScheme:
http + ":" + getServerName: localhost + ":" + getServerPort: 8080 + getRequestURI: /WebDemo/request = getRequestURL: http://localhost:8080/WebDemo/request URI: Uniform Resource Identifier Uniform Resource Identifier URL: Uniform Resource Locator Uniform Resource Locator Demo Request String Class Exercise: Output query string
information
on
the
console
package net.huawei.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;
import java.io.PrintWriter;
/**
* 功能:输出请求行的相关信息
* 作者:华卫
* 日期:2023年04月14日
*/
@WebServlet(name = "RequestLineServlet", urlPatterns = "/request")
public class RequestLineServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html; charset=utf-8");
// 获取字符输出流
PrintWriter out = response.getWriter();
// 获取并输出请求行的相关信息
out.println("getMethod: " + request.getMethod() + "<br />");
out.println("getRequestURI: " + request.getRequestURI() + "<br />");
out.println("getQueryString: " + request.getQueryString() + "<br />");
out.println("getProtocol: " + request.getProtocol() + "<br />");
out.println("getContextPath: " + request.getContextPath() + "<br />");
out.println("getPathInfo: " + request.getPathInfo() + "<br />");
out.println("getPathTranslated: " + request.getPathTranslated() + "<br />");
out.println("getServletPath: " + request.getServletPath() + "<br />");
out.println("getRemoteAddr: " + request.getRemoteAddr() + "<br />");
out.println("getRemoteHost: " + request.getRemoteHost() + "<br />");
out.println("getRemotePort: " + request.getRemotePort() + "<br />");
out.println("getLocalAddr: " + request.getLocalAddr() + "<br />");
out.println("getLocalName: " + request.getLocalName() + "<br />");
out.println("getLocalPort: " + request.getLocalPort() + "<br />");
out.println("getServerName: " + request.getServerName() + "<br />");
out.println("getServerPort: " + request.getServerPort() + "<br />");
out.println("getScheme: " + request.getScheme() + "<br />");
out.println("getRequestURL: " + request.getRequestURL() + "<br />");
// 在控制台输出请求字符串的信息
if (request.getQueryString() != null) {
String strQuery = request.getQueryString();
String[] queries = strQuery.split("&");
for (String query : queries) {
String[] fields = query.split("=");
System.out.println(fields[0] + " : " + fields[1]);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Restart the tomcat server, visit http://localhost:8080/WebDemo/request?username=howard&password=903213 You
can also continue to split the query string by =
2. Case demonstration
Create the RequestHeadersServlet class in the net.huawei.request package
package net.huawei.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;
import java.io.PrintWriter;
import java.util.Enumeration;
/**
* 功能:演示获取请求头的信息
* 作者:华卫
* 日期:2023年04月14日
*/
@WebServlet(name = "RequestHeaderServlet", urlPatterns = "/header")
public class RequestHeaderServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html; charset=utf-8");
// 获取字符输出流
PrintWriter out = response.getWriter();
// 获取请求头名枚举对象
Enumeration<String> headerNames = request.getHeaderNames();
// 遍历所有请求头,并通过getHeader()方法获取一个指定名称的头字段
while (headerNames.hasMoreElements()) {
// 获取头字段名称
String headerName = headerNames.nextElement();
// 输出头字段名称及其值
out.println(headerName + " : " + request.getHeader(headerName) + "<br />");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Restart the tomcat server, visit http://localhost:8080/WebDemo/header
and press the F12 key to view the request header information through the developer tool
3. Case demo request forwarding
Create the RequestForwardServlet class in the net.huawei.request package, save the data in the request object, and then forward it to another Servlet for processing
package net.huawei.request;
import javax.servlet.RequestDispatcher;
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;
/**
* 功能:演示请求转发
* 作者:华卫
* 日期:2023年03月13日
*/
@WebServlet(name = "RequestForwardServlet", urlPatterns = "/forward")
public class RequestForwardServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html;charset=utf-8");
// 设置请求对象属性
request.setAttribute("message", "欢迎访问泸州职业技术学院~");
// 获取请求派发器对象(参数是请求转发的Servlet的url)
RequestDispatcher dispatcher = request.getRequestDispatcher("/result");
// 请求转发给url为`/result`的Servlet
dispatcher.forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Create the ResultServlet class in the net.huawei.request package to obtain and output the data stored in the request object in the RequestForwardServlet class
package net.huawei.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;
import java.io.PrintWriter;
/**
* 功能:处理转发的请求
* 作者:华卫
* 日期:2023年03月13日
*/
@WebServlet(name = "ResultServlet", urlPatterns = "/result")
public class ResultServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html;charset=utf-8");
// 获取字符输出流
PrintWriter out = response.getWriter();
// 获取请求转发保存在request对象里的数据
String message = (String) request.getAttribute("message");
// 输出获取的信息
if (message != null) {
out.println("转发来的消息:" + message);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Correspondence diagram
Restart the tomcat server and visit http://localhost:8080/WebDemo/forward
Note: The address bar still displays the request path of RequestForwardServlet, but the browser displays the content to be output in ResultServlet. This is because request forwarding is a behavior that occurs inside the server. From RequestForwardServlet to ResultServlet is a request, and the request attribute can be used for data sharing (same request forwarding) in one request.
2. Case demonstration
Create a registration page - register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<form action="register" method="post">
<fieldset>
<legend>新用户注册</legend>
<table cellpadding="2" align="center">
<tr>
<td align="right">用户名:</td>
<td>
<input type="text" name="username" />
</td>
</tr>
<tr>
<td align="right">密码:</td>
<td>
<input type="password" name="password" />
</td>
</tr>
<tr>
<td align="right">性别:</td>
<td>
<input type="radio" name="gender" value="男"/> 男
<input type="radio" name="gender" value="女"/> 女
</td>
</tr>
<tr>
<td align="right">兴趣:</td>
<td>
<input type="checkbox" name="interest" value="看电影"/>看电影
<input type="checkbox" name="interest" value="敲代码"/>敲代码
<input type="checkbox" name="interest" value="玩游戏"/>玩游戏
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="注册"/>
<input type="reset" value="重填" />
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Create the RquestParamsServlet class in the net.huawei.request package to obtain the data submitted by the registration form
package net.huawei.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;
import java.io.PrintWriter;
/**
* 功能:获取请求参数
* 作者:华卫
* 日期:2023年04月14日
*/
@WebServlet(name = "RequestParamsServlet", urlPatterns = "/register")
public class RequestParamsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html; charset=utf-8");
// 获取字符输出流
PrintWriter out = response.getWriter();
// 获取注册表单提交的数据
String username = request.getParameter("username");
String password = request.getParameter("password");
String gender = request.getParameter("gender");
String[] interests = request.getParameterValues("interest");
// 输出获取的表单数据
out.println("姓名:" + username + "<br />");
out.println("密码:" + password + "<br />");
out.println("性别:" + gender + "<br />");
out.print("兴趣:");
for (int i = 0; i < interests.length; i++) {
out.println(interests[i]);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Restart the tomcat server, visit http://localhost:8080/WebDemo/register.html, fill in the form data
and click the [Register] button
(5) Solve the problem of Chinese garbled characters in request parameters
Objective: Master how to solve the problem of Chinese garbled characters in request parameters
In the HttpServletRequest interface, a setCharacterEncoding() method is provided, which is used to set the decoding method of the request object
Modify the ResquestParamsServlet class, add a line of code, and set the character encoding of the request object
Restart the tomcat server, visit http://localhost:8080/WebDemo/register.html, fill in the form data
and click the [Register] button, there is no Chinese garbled characters on the page
Record the screen to demonstrate the registration operation
2. Case demonstration to pass data through the Request object
Create the RquestServlet01 class in the net.huawei.request package
package net.huawei.request;
import javax.servlet.RequestDispatcher;
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;
/**
* 功能:设置请求对象属性,请求转发
* 作者:华卫
* 日期:2023年04月14日
*/
@WebServlet(name = "RequestServlet01", urlPatterns = "/request01")
public class RequestServlet01 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html; charset=utf-8");
// 设置请求对象属性
request.setAttribute("id", "20210201");
request.setAttribute("name", "陈燕文");
request.setAttribute("gender", "女");
request.setAttribute("age", "18");
request.setAttribute("major", "软件技术专业");
request.setAttribute("class", "2021级软件2班");
request.setAttribute("phone", "15890903456");
// 获取请求派发器对象(参数是请求转发的Servlet的url)
RequestDispatcher dispatcher = request.getRequestDispatcher("/request02");
// 请求转发给url为`/request02`的Servlet
dispatcher.forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Create the RquestServlet02 class in the net.huawei.request package
package net.huawei.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;
import java.io.PrintWriter;
import java.util.Enumeration;
/**
* 功能:获取请求转发的数据
* 作者:华卫
* 日期:2023年04月14日
*/
@WebServlet(name = "RequestServlet02", urlPatterns = "/request02")
public class RequestServlet02 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html; charset=utf-8");
// 获取字符输出流
PrintWriter out = response.getWriter();
// 获取请求对象属性名枚举对象
Enumeration<String> attributes = request.getAttributeNames();
// 获取请求转发保存在request对象里的数据并输出
while (attributes.hasMoreElements()) {
// 获取属性名
String attribute = attributes.nextElement();
// 输出属性名及其值
out.println(attribute + " : " + request.getAttribute(attribute) + "<br />");
}
// 删除请求对象的属性
while (attributes.hasMoreElements()) {
// 获取属性名
String attribute = attributes.nextElement();
// 删除属性
request.removeAttribute(attribute);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Start the server, visit http://localhost:8080/WebDemo/request01
and modify RequestServlet02 to display only student information
package net.huawei.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;
import java.io.PrintWriter;
/**
* 功能:获取请求转发的数据
* 作者:华卫
* 日期:2023年04月14日
*/
@WebServlet(name = "RequestServlet02", urlPatterns = "/request02")
public class RequestServlet02 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应体内容类型
response.setContentType("text/html; charset=utf-8");
// 获取字符输出流
PrintWriter out = response.getWriter();
// 获取请求转发保存在request对象里的数据并输出
out.println("学号:" + request.getAttribute("id") + "<br />");
out.println("姓名:" + request.getAttribute("name") + "<br />");
out.println("性别:" + request.getAttribute("gender") + "<br />");
out.println("年龄:" + request.getAttribute("age") + "<br />");
out.println("专业:" + request.getAttribute("major") + "<br />");
out.println("班级:" + request.getAttribute("class") + "<br />");
out.println("手机:" + request.getAttribute("phone") + "<br />");
// 删除请求对象的属性
request.removeAttribute("id");
request.removeAttribute("name");
request.removeAttribute("gender");
request.removeAttribute("age");
request.removeAttribute("major");
request.removeAttribute("class");
request.removeAttribute("phone");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Start the server and visit http://localhost:8080/WebDemo/request01