HTTP、Tomcat、Servlet
1. Web核心
2. HTTP
2.1 概述
2.2 请求数据格式
2.3 响应数据格式
/* 自定义服务器 */
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8080); // 监听指定端口
System.out.println("server is running...");
while (true){
Socket sock = ss.accept();
System.out.println("connected from " + sock.getRemoteSocketAddress());
Thread t = new Handler(sock);
t.start();
}
}
}
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 {
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 {
// 发送成功响应:
//读取html文件,转换为字符串
BufferedReader br = new BufferedReader(new FileReader("http/html/a.html"));
StringBuilder data = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null){
data.append(line);
}
br.close();
int length = data.toString().getBytes(StandardCharsets.UTF_8).length;
writer.write("HTTP/1.1 200 OK\r\n");
writer.write("Connection: keep-alive\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.toString());
writer.flush();
}
}
}
3. Tomcat
3.1 概述
3.2 基本使用
3.3 IDEA中创建Maven Web项目
3.4 IDEA中使用Tomcat
4. Servlet
4.1 概述
4.2 快速入门
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>web-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- tomcat 插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>
/** * Servlet 快速入门 */
@WebServlet("/demo1")
public class ServletDemo1 implements Servlet {
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("servlet hello world~");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
@Override
public void init(ServletConfig config) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
}
4.3 Servlet执行流程
4.4 Servlet生命周期
/** * Servlet 生命周期方法 */
@WebServlet(urlPatterns="/demo2",loadOnStartup = 1)
public class ServletDemo2 implements Servlet {
/** * 初始化方法 * 1. 调用时机:默认情况下,Servlet被第一次访问时,调用 * * loadOnStartup: * 2. 调用次数:1次 * @param config * @throws ServletException */
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init...");
}
/** * 提供服务 * 1. 调用时机:每一次Servlet被访问时,调用 * 2. 调用次数:多次 * * @param req * @param res * @throws ServletException * @throws IOException */
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("servlet hello world~");
}
/** * 销毁方法 * 1. 调用时机:内存释放或者服务器关闭的时候,Servlet对象会被销毁,调用 * 2. 调用次数:1次 */
@Override
public void destroy() {
System.out.println("destroy...");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public ServletConfig getServletConfig() {
return null;
}
}
/** * Servlet 方法介绍 */
@WebServlet(urlPatterns="/demo3",loadOnStartup = 1)
public class ServletDemo3 implements Servlet {
private ServletConfig config;
/** * 初始化方法 * 1. 调用时机:默认情况下,Servlet被第一次访问时,调用 * * loadOnStartup: * 2. 调用次数:1次 * @param config * @throws ServletException */
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
System.out.println("init...");
}
@Override
public ServletConfig getServletConfig() {
return config;
}
/** * 提供服务 * 1. 调用时机:每一次Servlet被访问时,调用 * 2. 调用次数:多次 * * @param req * @param res * @throws ServletException * @throws IOException */
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("servlet hello world~");
}
/** * 销毁方法 * 1. 调用时机:内存释放或者服务器关闭的时候,Servlet对象会被销毁,调用 * 2. 调用次数:1次 */
@Override
public void destroy() {
System.out.println("destroy...");
}
@Override
public String getServletInfo() {
return "";
}
}
4.5 Servlet体系结构
public class MyHttpServlet implements Servlet {
@Override
public void init(ServletConfig config) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// 根据请求方式的不同,进行分别的处理
HttpServletRequest request = (HttpServletRequest) req;
//1. 获取请求方式
String method = request.getMethod();
//2. 判断
if("GET".equals(method)){
// get方式的处理逻辑
doGet(req,res);
}else if("POST".equals(method)){
// post方式的处理逻辑
doPost(req,res);
}
}
protected void doPost(ServletRequest req, ServletResponse res) {
}
protected void doGet(ServletRequest req, ServletResponse res) {
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
4.6 Servlet urlPattern配置
/** * urlPattern:一个Servlet可以配置多个访问路径 */
@WebServlet(urlPatterns = {
"/demo7","/demo8"})
public class ServletDemo7 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("demo7 get...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
/** * urlPattern: * * 精确匹配(最常用) */
@WebServlet(urlPatterns = "/user/select")
public class ServletDemo8 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("demo8 get...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
/** * urlPattern: * * 目录匹配:/user/* */
@WebServlet(urlPatterns = "/user/*")
public class ServletDemo9 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("demo9 get...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
/** * urlPattern: * * 扩展名匹配: *.do */
@WebServlet(urlPatterns = "*.do")
public class ServletDemo10 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("demo10 get...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
/** * urlPattern: * * 任意匹配:/ */
//@WebServlet(urlPatterns = "/")
public class ServletDemo11 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("demo11 get...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
文章评论