一 普通的html服务
class Handler extends Thread {
Socket sock;
public Handler(Socket sock) {
this.sock = sock;
}
public void run() {
try (InputStream input = this.sock.getInputStream()) {
try (OutputStream output = this.sock.getOutputStream()) {
handle(input,output);
}
} catch (Exception e) {
try {
this.sock.close();
} catch (IOException ioe) {
}
System.out.println("client disconnected.");
}
}
private void handle(InputStream input, OutputStream output) throws IOException {
System.out.println("Process new http request...");
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
// 读取HTTP请求:
boolean requestOk = false;
String first = reader.readLine();
if (first.startsWith("GET / HTTP/1.")) {
requestOk = true;
}
for (;;) {
String header = reader.readLine();
if (header.isEmpty()) { // 读取到空行时, HTTP Header读取完毕
break;
}
System.out.println(header);
}
System.out.println(requestOk ? "Response OK" : "Response Error");
if (!requestOk) {
// 发送错误响应:
writer.write("HTTP/1.0 404 Not Found\r\n");
writer.write("Content-Length: 0\r\n");
writer.write("\r\n");
writer.flush();
} else {
// 发送成功响应:
String data = "<html><body><h1>Hello, world!</h1></body></html>";
int length = data.getBytes(StandardCharsets.UTF_8).length;
writer.write("HTTP/1.0 200 OK\r\n");
writer.write("Connection: close\r\n");
writer.write("Content-Type: text/html\r\n");
writer.write("Content-Length: " + length + "\r\n");
writer.write("\r\n"); // 空行标识Header和Body的分隔
writer.write(data);
writer.flush();
}
}
}
运行后在浏览器输入http://localhost:8080/
上述是一个简单的http服务,但是要编写一个完善的HTTP服务器,以HTTP/1.1为例,需要考虑的包括: 识别正确和错误的HTTP请求; 识别正确和错误的HTTP头; 复用TCP连接; 复用线程; IO异常处理; ... 这些基础工作需要耗费大量的时间,并且经过长期测试才能稳定运行 。所以引入Servlet服务,用户不需要关注底层实现,不需要解析HTTP协议,而开发具体的业务。
二 使用Servlet
1 创建项目
将maven项目转换成web项目,也可直接创建maven web项目,这里使用已经建好的项目。
maven项目可参考: intelliJ IDEA maven项目_鲜花盔甲的主人的博客-优快云博客
1.1 右键项目Add Framework Support ,添加Web Application 支持。
1.2 出现webapp目录, 项目变为web项目
此处新建了web.xml,后面Servlet需要配置。
2 使用servlet API
2.1 配置pom.xml,引入servlet,等待包加载成功。
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
2.2 代码实现,继承HttpServlet之后,重写doGet方法。
@WebServlet(urlPatterns = "/")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
// 写入响应:
pw.write("<h1>Hello, world! faw HttpServlet</h1>");
pw.flush();
}
}
2.3 配置 web.xml
未配置会打包失败
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
3. 打包
直接打成war包,放入tomcat中运行
3.1 配置pom.xml,打包类型war包,表示Java Web Application Archive。
3.2 war包打包。
4. 运行war包。
该web应用程序没有main方法,无法直接运行war
文件,必须借助一个支持Servlet API的Web服务器,常用的有Tomcat、Jetty、GlassFish。这里使用Tomcat。
4.1 下载Tomcat。
4.2 将xxx.war放入Tomcat的webapps
目录下,切换到bin
目录,执行startup.bat
启动Tomcat服务器。
4.3 在浏览器输入http://localhost:8080/xxx/,即可看到输出。