Servlet依赖坐标
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
定义一个类,实现 Servlet 接口,重写所有方法,该实现方法需要加 @WebServlet 注解,loadOnStartup >= 0 时,服务器在实例化的过程中就会创建 Servlet 对象
@WebServlet(urlPatterns="/demo1",loadOnStartup=1)
public class ServletDemo1 implements Servlet {
public void service(){}
}
Tomcat访问 http://localhost:8080/Servlet/demo1
生命周期
Ⅰ加载和实例化:通常由容器创建
Ⅱ初始化:容器调用 Servlet.init() 方法初始化对象,只调用一次
Ⅲ请求服务:调用 Servlet.service() 方法处理请求
Ⅳ服务终止:释放内存或容器关闭时,调用 Servlet.destroy(),之后实例被垃圾收集器回收
重写doGet、doPost
doGet:常用于不含敏感信息的查询场景(在url地址中显示)
doPost:对安全性有要求的场景
中文乱码
Post:request.setCharacterEncoding(" 编码形式 ");
get:new String ( username.getBytes ( "原编码" ),( "新编码" ));
Tomcat8 以下中得到字节的十六进制后使用 ISO-8859-1 编码
forward(转发)(Request)
req.getRequestDispatcher(path,forward(request,respone)); 路径 和 参数
req.setAttribute(key,value); 存储
req.getAttribute(key); 获取
req.removeAttribute(key); 删
①不改变地址
②只能转发在服务器内部的资源
③只发送一次请求(相当于浏览器到A资源,A转发到B资源,最后由B到浏览器)
Response(重定向)
rssp.setStatus(); 设置相应状态码
resp.setHeader(key,value); 设置头
resp.getWriter(); 设置字符输出流
resp.getOutputStream(); 设置字节输出流(例如图片等)
动态获取虚拟目录:String str = request.getContextPath() ;
简化的重定向形式: resp.sendRedirect(str+@WebServlet); 直接跳转
①地址栏发生变化 ②可以去任意地址 ③发生两次请求(相当于浏览器到A资源,A返回给浏览器,浏览器再去找B)
字节输出流
导入依赖commons-io
FileInputStream fil = new FileInputStream(path);
ServletOutputStream os = new ServletOutputStream();
IOTtils.copy(fil,os);