1、什么是 Servlet
- 1、Servlet 是 JavaEE 规范之一,规范就是接口
- 2、Servlet 就 JavaWeb 三大组件之一。三大组件分别是:
Servlet 程序
、Filter 过滤器
、Listener监听器
- 3、Servlet 是运行在
服务器
上的一个 java 小程序,它可以接收客户端发送过来的请求,并响应数据给客户端
2、手动实现 Servlet 程序
1、编写一个类去实现 Servlet 接口
2、实现 service 方法,处理请求,并响应数据
3、到 web.xml 中去配置 servlet 程序的访问地址
举个栗子
1、新建javaee工程
2、编写类实现servlet接口
package com.lian.servlet;
import javax.servlet.*;
import java.io.IOException;
/**
* servlet是服务器上的一个小程序
*/
public class HelloServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
/**
* 专门用来请求和响应的,处理客户端请求和响应数据给客户端
* @param servletRequest
* @param servletResponse
* @throws ServletException
* @throws IOException
*/
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello servlet was accessed");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
3、web.xml 配置 servlet 程序的访问地址
<?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">
<!--
到 web.xml 中去配置 servlet 程序的访问地址,才能访问到HelloServlet
servlet标签给tomcat配置Servlet程序
-->
<servlet>
<!--servlet-name 标签:给程序起一个别名,一般是类名,和给孩子起个名字一样-->
<servlet-name>helloServlet</servlet-name>
<!--servlet-class 是servlet程序的全类名-->
<servlet-class>com.lian.servlet.HelloServlet</servlet-class>
</servlet>
<!--servlet-mapping标签 给servlet程序配置访问地址-->
<servlet-mapping>
<!--servlet-name标签的作用是告诉服务器,当前配置的地址给哪个servlet程序使用-->
<servlet-name>helloServlet</servlet-name>
<!--
url-pattern标签配置访问地址,一般以斜杠开头加名称
/: 斜杠在服务器解析的时候,表示地址为 http://ip:port/工程路径(tomcat配置的访问路径,一般我都设为/)
hello: 表示地址为 http://ip:port/工程路径/hello
-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
4、测试
我tomcat一般习惯设置配置路径为 斜杠/
浏览器访问 http://localhost:8080/hello, 控制台打印
hello servlet was accessed
3、url 地址到 Servlet 程序的访问过程
为什么请求 http://localhost:8080/hello 就会请求到Servlet呢?
4、Servlet的生命周期
1、执行Servlet构造器方法
2、执行init初始化方法
第一、二步,是在第一次访问的时候创建Servlet程序会调用
3、执行service方法
第三步,每次访问都会调用
4、执行destroy销毁方法
第四步,在web工程停止的时候调用
举个栗子
package com.lian.servlet;
import javax.servlet.*;
import java.io.IOException;
/**
* servlet是服务器上的一个小程序
*/
public class HelloServlet implements Servlet {
//构造器
public HelloServlet() {
System.out.println("1、construct method");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("2、init method");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
/**
* 专门用来请求和响应的,处理客户端请求和响应数据给客户端
* @param servletRequest
* @param servletResponse
* @throws ServletException
* @throws IOException
*/
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("3、service method");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("4、destroy method");
}
}
返回结果
#第一步和第二步只有在开始启动时执行一次
1 construct method
2 init method
hello servlet was accessed
#每次请求url地址都会执行此步骤
3 service method
3 service method
3 service method
#销毁步骤在关闭servlet程序后才会执行
4 destroy method
5、Servlet的请求分发处理
//解决GET和POST请求的分发处理
package com.lian.servlet;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* servlet是服务器上的一个小程序
*/
public class HelloServlet implements Servlet {
//构造器
public HelloServlet() {
System.out.println("1、construct method");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("2、init method");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
/**
* 专门用来请求和响应的,处理客户端请求和响应数据给客户端
* @param servletRequest
* @param servletResponse
* @throws ServletException
* @throws IOException
*/
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("3、service method");
//类型转换,因为HttpServletRequest 才有 getMethod 方法
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//获取请求方式,get 或者 post
String method = httpServletRequest.getMethod();
//这样代码很多行时就会很拥挤
if ("GET".equals(method)){
//System.out.println("get请求");
doGet();
}else if ("POST".equals(method)){
//System.out.println("post请求");
doPost();
}
}
/**
* 处理get请求
*/
public void doGet(){
System.out.println("get请求");
}
/**
* 处理post请求
*/
public void doPost(){
System.out.println("post请求");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("4、destroy method");
}
}
6、继承HttpServlet实现Servlet程序
一般在实际项目开发中,都是使用继承HttpServlet类的方式去实现Servlet程序
1、编写一个类去继承HttpServlet类
2、根据业务需要重写doGet或doPost方法
3、到web.xml中的配置Servlet程序的访问地址
举个栗子
1、继承HttpServlet
package com.lian.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 一般都是继承 servlet的子类 HttpServlet 来实现servlet程序
*/
public class HelloServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doget method");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("dopost method");
}
}
2、配置web.xml
<!--配置helloServlet2-->
<servlet>
<servlet-name>helloServlet2</servlet-name>
<servlet-class>com.lian.servlet.HelloServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet2</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
3、web下新建表单 a.html测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/hello2" method="get">
<input type="submit">
</form>
<form action="http://localhost:8080/hello2" method="post">
<input type="submit">
</form>
</body>
</html>
7、Servlet类的继承体系
8、ServletConfig类
ServletConfig类从类名上来看,就知道是Servlet程序的配置信息类
Servlet程序和ServletConfig对象都是由Tomcat负责创建,我们负责使用
Servlet程序默认是第一次访问的时候创建,ServletConfig是每个Servlet程序创建时,就创建一个对应的ServletConfig对象
1、可以获取Servlet程序的别名servlet-name
的值
2、获取初始化参数init-param
3、获取ServletContext
对象
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("2、init method");
/**
* servletConfig 可以获取servlet程序的别名
*/
System.out.println("servlet程序的别名: " + servletConfig.getServletName());
System.out.println("初始化参数username的值是 : " + servletConfig.getInitParameter("username"));
System.out.println("servletConfig是 : " + servletConfig.getServletContext());
}
8、ServletContext类
1、ServletContext是一个接口,它表示Servlet上下文对象
2、一个web工程,只有一个ServletContext对象实例
3、ServletContext对象是一个域对象
4、ServletContext是在web工程部署启动的时候创建。在web工程停止的时候销毁
什么是域对象?
域对象,是可以像Map一样存取数据的对象,叫域对象。这里的域指的是存取数据的操作范围,整个web工程
map | 域对象 | |
---|---|---|
存数据 | put | setAttribute |
取数据 | get | getAttribute |
删除数据 | remove | removeAttribute |
ServletContext类的四个作用
1、获取web.xml中配置的上下文参数context-param
2、获取当前的工程路径,格式:/工程路径
3、获取工程部署后在服务器硬盘上的绝对路径
4、像Map一样存取数据
举个栗子
1、web.xml配置文件
<!--context-param 是上下文参数(它属于整个web工程),可配置多组-->
<context-param>
<param-name>username</param-name>
<param-value>context</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>root</param-value>
</context-param>
2、继承HttpServlet类
/**
* 一般都是继承 servlet的子类 HttpServlet 来实现servlet程序
*/
public class HelloServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取web.xml中配置的上下文参数context-param
ServletContext context = getServletConfig().getServletContext();
String username = context.getInitParameter("username");
String password = context.getInitParameter("password");
System.out.println("context-param参数username的值是"+username);
System.out.println("context-param参数password的值是"+password);
//2、获取当前的工程路径,格式: /工程路径
System.out.println("当前工程路径:" + context.getContextPath());
//3、获取工程部署后在服务器硬盘上的绝对路径,斜杠被服务器解析地址为: http://ip:port/工程名/
System.out.println(context.getRealPath("/"));
//4、获取ServletContext,源码还是 this.getServletConfig().getServletContext()
ServletContext context1 = getServletContext();
context1.setAttribute("key1","value1");
System.out.println("context 中获取域数据key1的值是:"+context1.getAttribute("key1"));
}
}
9、什么是Http协议
协议是指双方,或多方,相互约定好,大家都需要遵守的规则,叫协议。
所谓HTTP协议,就是指,客户端和服务器之间通信时,发送的数据,需要遵守的规则,叫HTTP协议。HTTP协议中的数据又叫报文。
请求的HTTP协议格式
客户端给服务器发送数据叫请求。
服务器给客户端回传数据叫响应。
请求又分为GET请求,和POST请求两种
get 请求http协议内容介绍
post 请求http协议内容介绍
常用请求头说明
Accept:表示客户端可以接收的数据类型
Accpet-Languege:表示客户端可以接收的语言类型User-Agent:表示客户端浏览器的信息
Host:表示请求时的服务器ip和端口号
哪些是get请求?哪些是post请求
get请求有哪些:
1、form标签method=get
2、a标签
3、link标签引入css
4、Script标签引入js文件
5、img标签引入图片
6、iframe引入html页面
7、在浏览器地址栏中输入地址后敲回车
POST请求有哪些:
8、form标签method=post
响应的http协议格式
1、响应行
响应的协议和版本号
响应状态码
响应状态描述符
2、响应头
key:value 不同的响应头,有其不同含义
3、响应体
就是回传给客户端的数据
常用的响应码说明
200 表示请求成功
302 表示请求重定向(明天讲)
404 表示请求服务器已经收到了,但是你要的数据不存在(请求地址错误)
500 表示服务器已经收到请求,但是服务器内部错误(代码错误)
MIME类型说明
MIME是HTTP协议中数据类型。
MIME的英文全称是"MultipurposeInternetMailExtensions"多功能Internet邮件扩充服务。MIME类型的格式是“大类型/小类型”,并与某一种文件的扩展名相对应。
谷歌浏览器查看http协议
F12 查看network即可
10、HttpServletRequest 类
HttpServletRequest 类有什么作用
每次只要有请求进入 Tomcat 服务器,Tomcat 服务器就会把请求过来的 HTTP 协议信息解析好封装到 Request 对象中。 然后传递到 service 方法(doGet 和 doPost)中给我们使用。我们可以通过 HttpServletRequest 对象,获取到所有请求的 信息。
HttpServletRequest 类的常用方法
- getRequestURI() 获取请求的资源路径
- getRequestURL() 获取请求的统一资源定位符(绝对路径)
- getRemoteHost() 获取客户端的 ip 地址
- getHeader() 获取请求头
- getParameter() 获取请求的参数
- getParameterValues() 获取请求的参数(多个值的时候使用)
- getMethod() 获取请求的方式 GET 或 POST
- setAttribute(key, value); 设置域数据
- getAttribute(key); 获取域数据
- getRequestDispatcher() 获取请求转发对象
public class RequestApiServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取请求的资源路径
System.out.println("uri"+ req.getRequestURI());
//2、获取请求的统一资源定位符(绝对路径)
System.out.println("url"+req.getRequestURL());
//3、获取客户端的 ip 地址
System.out.println("ip"+req.getRemoteHost());
//4、获取请求头
System.out.println("user-agent"+req.getHeader("user-Agent"));
//5、获取请求的方式 GET 或 POST
System.out.println("请求方式"+req.getMethod());
}
}
如何获取请求参数
1、创建servlet类
public class RequestApiServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
final String password = req.getParameter("password");
String hobby = req.getParameter("hobby");
System.out.println("用户名:" + username);
System.out.println("密码:" + password);
System.out.println("兴趣爱好:" + Arrays.asList(hobby));
}
}
2、配置web.xml
<?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>requestApiServlet</servlet-name>
<servlet-class>com.lian.servlet.RequestApiServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>requestApiServlet</servlet-name>
<url-pattern>/req</url-pattern>
</servlet-mapping>
</web-app>
3、配置tomcat
4、创建表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/req" method="get">
用户名: <input type="text" name="username"><br/>
密码: <input type="password" name="password"><br/>
兴趣爱好:
<input type="checkbox" name="hobby" value="c++">C++
<input type="checkbox" name="hobby" value="java">java
<input type="checkbox" name="hobby" value="js">javaScript<br/>
<input type="submit">
</form>
</body>
</html>
11、Servlet请求转发
什么是请求的转发?
请求转发是指,服务器收到请求后,从一次资源跳转到另一个资源的操作叫请求转发
举个栗子
1、servlet1
public class Servlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取请求的参数(办事的材料)查看
String username = req.getParameter("username");
System.out.println("在 Servlet1(柜台 1)中查看参数(材料):" + username);
//2、给材料 盖一个章,并传递到 Servlet2(柜台 2)去查看
req.setAttribute("key1","柜台 1 的章");
//3、问路:Servlet2(柜台 2)怎么走
//请求转发必须要以斜杠打头,/ 斜杠表示地址为:http://ip:port/工程名/ , 映射到 IDEA 代码的 web 目录
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servlet2");
//4、走向 Sevlet2(柜台 2)
requestDispatcher.forward(req,resp);
}
}
2、servlet2
public class Servlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、 获取请求的参数(办事的材料)查看
String username = req.getParameter("username");
System.out.println("在 Servlet2(柜台 2)中查看参数(材料):" + username);
//2、 查看 柜台 1 是否有盖章
Object key1 = req.getAttribute("key1");
System.out.println("柜台 1 是否有章:" + key1);
//3、处理自己的业务
System.out.println("Servlet2 处理自己的业务 ");
}
}
3、web.xml配置servlet1和servlet2
<?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>servlet1</servlet-name>
<servlet-class>com.lian.servlet.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>com.lian.servlet.Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Web 中的相对路径和绝对路径
在 javaWeb 中,路径分为相对路径和绝对路径两种:
相对路径是:
. 表示当前目录
… 表示上一级目录
资源名 表示当前目录/
绝对路径: http://ip:port/工程路径/资源路径
在实际开发中,路径都使用绝对路径,而不简单的使用相对路径。
1、绝对路径
2、base+相对
web 中 / 斜杠的不同意义
在 web 中 / 斜杠 是一种绝对路径。
/ 斜杠 如果被浏览器解析,得到的地址是:http://ip:port/
/ 斜杠 如果被服务器解析,得到的地址是:http://ip:port/工程路径
1、/servlet1
2、servletContext.getRealPath(“/”);
3、request.getRequestDispatcher(“/”);
特殊情况: response.sendRediect(“/”); 把斜杠发送给浏览器解析。得到 http://ip:port/
12、HttpServletResponse 类
HttpServletResponse 类的作用
HttpServletResponse 类和 HttpServletRequest 类一样。
每次请求进来,Tomcat 服务器都会创建一个 Response 对象传 递给 Servlet 程序去使用。HttpServletRequest 表示请求过来的信息,HttpServletResponse 表示所有响应的信息, 我们如果需要设置返回给客户端的信息,都可以通过 HttpServletResponse 对象来进行设置
两个输出流的说明
字节流 getOutputStream(); 常用于下载(传递二进制数据)
字符流 getWriter(); 常用于回传字符串(常用)
两个流同时只能使用一个。 使用了字节流,就不能再使用字符流,反之亦然,否则就会报错
如何往客户端回传数据
要求 : 往客户端回传 字符串 数据
public class ResponseIOServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 要求 : 往客户端回传 字符串 数据
PrintWriter writer = resp.getWriter();
writer.write("response's content!!!");
}
}
响应的乱码解决
解决响应中文乱码方案一(不推荐使用)
// 设置服务器字符集为 UTF-8
resp.setCharacterEncoding("UTF-8");
// 通过响应头,设置浏览器也使用 UTF-8 字符集
resp.setHeader("Content-Type", "text/html; charset=UTF-8");
解决响应中文乱码方案二(推荐)
// 它会同时设置服务器和客户端都使用 UTF-8 字符集,还设置了响应头
// 此方法一定要在获取流对象之前调用才有效
resp.setContentType("text/html; charset=UTF-8");
请求重定向
请求重定向,是指客户端给服务器发请求,然后服务器告诉客户端说。我给你一些地址。你去新地址访问。叫请求 重定向(因为之前的地址可能已经被废弃)
请求重定向的第一种方案:
// 设置响应状态码 302 ,表示重定向,(已搬迁)
resp.setStatus(302);
// 设置响应头,说明 新的地址在哪里
resp.setHeader(“Location”, “http://localhost:8080”);
//请求重定向的第二种方案(推荐使用)
resp.sendRedirect(“http://localhost:8080”);