1. servlet的版本
- 1.0
- 2.x
- 3.x
- 4.x
2. 编写写第一个Servlet
-
引入JavaEE(Servlet)规范
-
编一个Java文件,MyServlet.class
-
配置映射(
web.xml
)给Tomcat解析
<?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">
<servlet>
<servlet-name>MyServlet01</servlet-name>
<servlet-class>com.tony.web.MyServlet01</servlet-class>
</servlet>
<servlet>
<servlet-name>MyServlet02</servlet-name>
<servlet-class>com.tony.web.MyServlet02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet01</servlet-name>
<url-pattern>/servlet01</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MyServlet02</servlet-name>
<url-pattern>/servlet02</url-pattern>
</servlet-mapping>
</web-app>
- 打包到Tomcat的安装目录下的
webapps
目录
3. IDEA中集成Tomcat
4. IDEA对web项目的热部署
轻量级的修改之后不需要重启就能重新部署;
这个操作每个项目都需要改
5. 创建Servlet的其他姿势
了解就行了
6. Servlet的执行流程
7. HttpServlet
- HttpServlet是一个抽象类
- 里面定义了一个service(req,resp)方法,需要我们自己编写自定义的Servlet的时候去重写;
- service方法由Tomcat来调用;
8. HttpServletRequest对象
-
请求数据包的封装对象
-
由Tomcat把浏览器发送的请求数据包进行封装,封装成一个HttpServletRequest对象,然后由Tomcat传递给我们自己编写的Servlet;
System.out.println("请求方式:" + req.getMethod()); System.out.println("主机:" + req.getHeader("Host")); System.out.println("servletPath:" + req.getServletPath()); //uri: 统一资源标识符 System.out.println("uri:" + req.getRequestURI()); //url:统一资源定位符 System.out.println("url:" + req.getRequestURL()); System.out.println("name=" + req.getParameter("name")); System.out.println("age=" + req.getParameter("age")); //多个值,返回数组 String[] loves = req.getParameterValues("loves"); System.out.println(Arrays.toString(loves));
http://localhost:8080/servlet02?name=tony&age=18&loves=java&loves=python
9. HttpServletResponse对象
- 响应对象
- 可以通过响应对象给浏览器返回数据
package com.tony.web;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServlet03 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Content-Type","text/html;charset=utf-8");
resp.getWriter().write("<h1>hello</h1>");
}
}
10. 常用的MIMETYPE类型
text/html(网页类型)
application/json(json类型)
image/jpg
image/jpeg
image/png
text/css
text/plain(文本类型)
11. Json类型
{
"name": "小明",
"age": 20,
"loves": ["java", "c++", 30, "拉面"]
}
现在主流的前后端分离开发使用的都是Json作为数据交互的格式
12. 作业
- 省市联动(纯前端的)
- 预习ajax