114.md 7.1 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6
# Java Servlet POST 示例

> 原文: [https://javatutorial.net/java-servlet-post-example](https://javatutorial.net/java-servlet-post-example)

本示例演示了如何使用 Servlet 的 doPost()方法来处理 POST 请求

W
wizardforcel 已提交
7
在我们以前的教程[的 Java Servlet 实现例](https://javatutorial.net/java-servlet-example)我展示了 doGet()方法的使用。 现在,我将向您展示如何使用 doPost()方法来处理表单 POST 提交。 Java Servlet 可以处理各种类型的请求。 下面的列表显示了所有方法及其用途
W
init  
wizardforcel 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

| **方法** | **SERVLET 方法** | **目的** |
| 得到 | **doGet()** | 在指定的 URL 检索资源 |
| 头 | **doHead()** | 与 GET 相同,只返回标头 |
| 开机自检 | **doPost()** | 通常用于 Web 表单提交 |
| 放 | **doPut()** | 将提供的实体存储在 URL |
| 删除 | **doDelete()** | 删除 URL 标识的资源 |
| 选件 | **doOptions()** | 返回允许的 HTTP 方法 |
| 跟踪 | **doTrace()** | 用于诊断 |

## 项目结构

在我们的项目中,我们确实需要三个文件。 pom.xml –设置 Maven 依赖关系和构建属性,web.xml –将 Servlet 和 Servlet 本身配置为 java 类

![Servlet POST Example project structure](img/b4ed971b44f7b3dfbfcc29abb9a9ce5f.jpg)

Servlet POST 示例项目结构

W
wizardforcel 已提交
26
## `pom.xml`文件
W
init  
wizardforcel 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

```java
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>net.javatutorial.tutorials</groupId>
	<artifactId>ServletPOSTExample</artifactId>
	<version>1</version>
	<packaging>war</packaging>

	<name>Servlet POST Example</name>
	<url>https://javatutorial.net</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>servletpost</finalName>
        <sourceDirectory>src/main/java</sourceDirectory>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
```

与上一教程一样,我们将 Servlet 的依赖项`javax.servlet-api``maven-war-plugin`的依赖关系用于构建网络应用

W
wizardforcel 已提交
83
## 在`web.xml`文件中映射 Servlet
W
init  
wizardforcel 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

```java
<?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_3_1.xsd"
	version="3.1">

	<display-name>Simple Servlet Application</display-name>

	<servlet>
		<servlet-name>servletPost</servlet-name>
		<servlet-class>net.javatutorial.tutorials.ServletPOST</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>servletPost</servlet-name>
		<url-pattern>/welcome</url-pattern>
	</servlet-mapping>

</web-app>
```

Servlet 被赋予一个名为“ ServletPost”的名称,该名称指向 Java 类 ServletPOST。

在 servlet 映射中,我们将 url“ / welcome”分配给 servlet

## Servlet 类

```java
package net.javatutorial.tutorials;

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 ServletPOST extends HttpServlet {

	private static final long serialVersionUID = -1641096228274971485L;

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

		// set response headers
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		// create HTML form
		PrintWriter writer = response.getWriter();
		writer.append("<!DOCTYPE html>\r\n")
			  .append("<html>\r\n")
			  .append("		<head>\r\n")
			  .append("			<title>Form input</title>\r\n")
			  .append("		</head>\r\n")
			  .append("		<body>\r\n")
			  .append("			<form action=\"welcome\" method=\"POST\">\r\n")
			  .append("				Enter your name: \r\n")
			  .append("				<input type=\"text\" name=\"user\" />\r\n")
			  .append("				<input type=\"submit\" value=\"Submit\" />\r\n")
			  .append("			</form>\r\n")
			  .append("		</body>\r\n")
			  .append("</html>\r\n");
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String user = request.getParameter("user");

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		// create HTML response
		PrintWriter writer = response.getWriter();
		writer.append("<!DOCTYPE html>\r\n")
			  .append("<html>\r\n")
			  .append("		<head>\r\n")
			  .append("			<title>Welcome message</title>\r\n")
			  .append("		</head>\r\n")
			  .append("		<body>\r\n");
		if (user != null && !user.trim().isEmpty()) {
			writer.append("	Welcome " + user + ".\r\n");
			writer.append("	You successfully completed this javatutorial.net example.\r\n");
		} else {
			writer.append("	You did not entered a name!\r\n");
		}
		writer.append("		</body>\r\n")
			  .append("</html>\r\n");
	}	

}

```

在上面的代码中, **doGet()**方法用于显示表单。 客户端(浏览器)使用 GET 请求调用网址 http://yoururl.com:8080/servletpost/welcome ,它显示以下形式

![Input form](img/95f1fe559956ea741efb40fd62af47f6.jpg)

输入形式

该 servlet 在客户端的浏览器中呈现为 HTML,如下所示:

```java
<!DOCTYPE html>
<html>
		<head>
			<title>Form input</title>
		</head>
		<body>
			<form action="welcome" method="POST">
				Enter your name: 
				<input type="text" name="user" />
				<input type="submit" value="Submit" />
			</form>
		</body>
</html>

```

提交**后,将调用 servlet 中的 doPost()**方法。 在这里,我们根据用户的输入来建立响应。 如果正确填写了姓名字段,则用户会收到问候消息

![Post response](img/f3162004e897cfca516dd5a073d65f6c.jpg)

回复后

…或警告消息(如果表单中的名称字段留空)

![Error message if name is missing](img/e9736c487096fdf35e9a3c1470cdab76.jpg)

如果缺少名称,则会出现错误消息

您可以在我们的 GitHub 存储库中找到[项目源。](https://github.com/JavaTutorialNetwork/Tutorials/tree/master/ServletPOSTExample)