目录
- 一、Servlet详解
- 1.1、核心接口和类
- 1.1.1、Servlet接口
- 1.1.2、GenericServlet
- 1.1.3、HttpServlet(推荐)
- 1.2、两种配置方法
- 1.2.1、使用web.xml
- 1.2.2、使用注解
- 二、Servlet应用
- 2.1、request对象
- 2.2、request主要方法
- 2.2、response对象
- 2.3、response主要方法
- 三、转发与重定向
- 3.1、转发
- 3.2、重定向
- 四、生命周期
- 4.1 实例化
- 4.2 初始化
- 4.3 服务
- 4.4 销毁
- 五、Servlet线程安全问题
- 5.1、线程安全问题
- 5.2、如何保证线程安全
- 六、Cookie
- 6.1、什么是Cookie
- 6.2、创建cookie
- 6.3、获取cookie
- 6.4、修改cookie
- 6.5、编码与解码
- 七、Session
- 7.1、获取Session
- 7.2、Session保存、获取数据
- 7.3、Session移除数据
- 7.4、Session生命周期
- 八、ServletContext
- 8.1、获取ServletContext对象
- 8.2、ServletContext作用
- 8.3、ServletContext应用场景
- 九、过滤器
- 9.1、实现过程
- 9.2、过滤器配置
- 9.3、过滤器链和优先级
- 9.4、过滤器应用
一、Servlet详解
在Servlet体系结构中,除了实现Servlet接口,还可以通过继承GenericServlet或HttpServlet类,完成编写。
1.1、核心接口和类
1.1.1、Servlet接口
1.1.2、GenericServlet
提供生命周期方法init和destroy的简单实现,要编写一般的Servlet只需重写抽象service方法
package com.wyy.servlet;
import jakarta.servlet.GenericServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;
public class GenServlet extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hi~~~");
}
}
1.1.3、HttpServlet(推荐)
package com.wyy.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class httpsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get");;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post");
}
}
1.2、两种配置方法
1.2.1、使用web.xml
1.2.2、使用注解
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = {"/bs","/bss"})
public class basicServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post");
}
}
二、Servlet应用
2.1、request对象
在Servlet中用来处理客户端请求需要用doGet或doPost方法的request对象
get和post的区别
2.2、request主要方法
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="/web1_war_exploded/login" method="post">
用户名:<input type="text" name="username"/><br>
密码:<input type="password" name="password"/><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>
Servlet
package com.wyy.servlet2;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(value = "/rs")
public class registerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户请求的数据
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("提交的数据: " + username + " " + password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//对request对象设置统一编码格式
req.setCharacterEncoding("utf-8");
//获取用户请求的数据
String username = req.getParameter("username");
String password = req.getParameter("password");
//System.out.println("提交的数据: " + username + " " + password);
//相应数据给客户端
resp.setContentType("text/html;charset=utf-8");
PrintWriter printWriter = resp.getWriter();
printWriter.println("注册成功");
}
}
2.2、response对象
response对象用于响应客户请求并向客户端输出信息
2.3、response主要方法
resp.getWriter();//获取字符输出流
PrintWriter printWriter = resp.getWriter();
if (admin != null){
//相应结果成功
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>结果页面</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h1>登陆成功!!!!</h1>");
printWriter.println("</body>");
printWriter.println("</html>");
}else {
//相应结果失败
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>结果页面</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h1>登陆失败</h1>");
printWriter.println("</body>");
printWriter.println("</html>");
}
三、转发与重定向
3.1、转发
转发的作用在服务端,将请求发送给服务器上的其他资源,以共同完成一次请求处理
页面跳转
数据传递
ShowAllAdminController
存数据
req.setAttribute("admins",adminList);
package com.wyy.servletProject.servlet;
import com.wyy.servletProject.entity.Admin;
import com.wyy.servletProject.service.AdminService;
import com.wyy.servletProject.service.imlp.AdminServiceimpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet(value = "/showallcontroller")
public class ShowAllAdminController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//只负责调用业务逻辑
AdminService adminService = new AdminServiceimpl();
List<Admin> adminList = adminService.showAllAdmin();
//request作用域存储数据
req.setAttribute("admins",adminList);
//通过转发跳转到显示结果的servlet
req.getRequestDispatcher("/showalljsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
ShowallAdminJSP
取数据
List<Admin> adminList = (List<Admin>) req.getAttribute("admins");
package com.wyy.servletProject.servlet;
import com.wyy.servletProject.entity.Admin;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(value = "/showalljsp")
public class ShowallAdminJSP extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Admin> adminList = (List<Admin>) req.getAttribute("admins");
PrintWriter printWriter = resp.getWriter();
if (adminList != null){
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>结果页面</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<tr>");
printWriter.println(" <td>username</td>");
printWriter.println(" <td>password</td>");
printWriter.println(" <td>phone</td>");
printWriter.println(" <td>address</td>");
printWriter.println("</tr><br>");
for (Admin admin :adminList){
printWriter.println("<tr>");
printWriter.println(" <td>"+admin.getUsername()+"</td>");
printWriter.println(" <td>"+admin.getPassword()+"</td>");
printWriter.println(" <td>"+admin.getPhone()+"</td>");
printWriter.println(" <td>"+admin.getAddress()+"</td>");
printWriter.println("</tr><br>");
}
printWriter.println("</body>");
printWriter.println("</html>");
}else {
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta charset='UTF-8'>");
printWriter.println("<title>结果页面</title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<h3>登陆失败</h3>");
printWriter.println("</body>");
printWriter.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3.2、重定向
作用在客户端,客户端将请求发送给服务器后,服务器响应给客户端一个新的请求地址,客户端重新发送请求。
页面跳转
数据传输
AServlet
重定向传数据
resp.sendRedirect("/web1_war_exploded/b?username=Tom"); //只能传String
package com.wyy.servletProject.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/a")
public class AServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//通过request作用域做数据的存储
// req.setAttribute("username","gavin");
// req.getRequestDispatcher("/b").forward(req,resp);
resp.sendRedirect("/web1_war_exploded/b?username=Tom");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
BServlet
重定向传数据
String username = req.getParameter("username");
package com.wyy.servletProject.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/b")
public class BServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String s = (String) req.getAttribute("username");
String username = req.getParameter("username");
System.out.println("B executed ..." + username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
当两个Servlet需要传数据时,选择forward转发,不建议使用sendRedirect进行传递
四、生命周期
四个阶段
4.1 实例化
4.2 初始化
4.3 服务
4.4 销毁
package com.wyy.servlet3;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet(value = "/ls")
public class lifeServlet implements Servlet {
public lifeServlet(){
System.out.println("1、实例化");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("2、初始化");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("3、接收请求,相应结果");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("4、销毁");
}
}
五、Servlet线程安全问题
5.1、线程安全问题
5.2、如何保证线程安全
package com.wyy.servlet3;
import jakarta.servlet.ServletException;
import jakarta.servlet.SingleThreadModel;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class SafeServlet extends HttpServlet implements SingleThreadModel {
private String massage = "";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
synchronized (this){
//假设接收参数
//调用业务逻辑,得到登录结果
massage = "登陆成功";
PrintWriter printWriter = resp.getWriter();
printWriter.println(massage);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.wyy.servlet3;
import jakarta.servlet.ServletException;
import jakarta.servlet.SingleThreadModel;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class SafeServlet extends HttpServlet {
// private String massage = "";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String massage = "";
//假设接收参数
//调用业务逻辑,得到登录结果
massage = "登陆成功";
PrintWriter printWriter = resp.getWriter();
printWriter.println(massage);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
六、Cookie
将浏览器与web服务器之间多次交互当作一个整体来处理,并且将多次交互所涉及的数据(即状态)保存下来。
分类:
- 客户端状态管理技术:将状态保存在
客户端
。代表性的是Cookie技术
。 - 服务器状态管理技术:将状态保存在
服务器端
。代表性的是session技术
(服务器传递sessionID时需要使用Cookie的方式)
6.1、什么是Cookie
- Cookie是在浏览器访问Web服务器某个资源时,
由Web服务器在HTTP响应消息头中附带传送给浏览器的一小段数据
- 一旦Web浏览器保存了某个Cookie,那么它在以后每次访问该Web浏览器时,都应在Http请求头中将这个Cookie回传给Web服务器。
- 一个Cookies是由标识该信息的名称(name)和值(value)组成。
6.2、创建cookie
package com.wyy.cookies;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/cs")
public class cookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务端创建cookie
Cookie cookie = new Cookie("username","gavin");
Cookie cookie2 = new Cookie("passward","123456");
//设置cookie的访问路径
cookie.setPath("/web1_war_exploded/get");
cookie2.setPath("/web1_war_exploded");
//设置cookie生命周期
cookie.setMaxAge(60*60);
cookie2.setMaxAge(60*60);
//将cookie响应给客户端
resp.addCookie(cookie);
resp.addCookie(cookie2);
}
}
6.3、获取cookie
package com.wyy.cookies;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/get")
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//通过request对象获取所有的cookie
Cookie[] cookies = req.getCookies();
//通过循环遍历数组
if (cookies != null){
for (Cookie cookie : cookies){
System.out.println(cookie.getName()+":"+cookie.getValue());
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6.4、修改cookie
package com.wyy.cookies;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/cs2")
public class CookieServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("username","aaron");
cookie.setPath("/web1_war_exploded/get");
cookie.setMaxAge(60*60*24*7);
resp.addCookie(cookie);
}
}
如果改变cookie的name有效路径会新建cookie,而改变cookie的值,有效期会覆盖原有的cookie
6.5、编码与解码
编码
URLEncoder.encode("姓名","UTF-8"),URLEncoder.encode("张三","UTF-8")
package com.wyy.cookies;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
@WebServlet(value = "/cs3")
public class CookisServlet3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie(URLEncoder.encode("姓名","UTF-8"),URLEncoder.encode("张三","UTF-8"));
cookie.setPath("/web1_war_exploded/get");
cookie.setMaxAge(600);
resp.addCookie(cookie);
}
}
解码
URLDecoder.decode(cookie.getName(),"UTF-8")+":"+URLDecoder.decode(cookie.getValue(),"UTF-8")
package com.wyy.cookies;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
@WebServlet(value = "/get")
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//通过request对象获取所有的cookie
Cookie[] cookies = req.getCookies();
//通过循环遍历数组
if (cookies != null){
for (Cookie cookie : cookies){
System.out.println(URLDecoder.decode(cookie.getName(),"UTF-8")+":"+URLDecoder.decode(cookie.getValue(),"UTF-8"));
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
七、Session
概述
- Session用于记录用户的状态。Session指的是在一段时间内,单个客户端与Web服务器的一连串相关的交互过程。
- 在一个Session中,客户可能会多次请求访问同一个资源,也有可能请求访问各种不同的服务器资源。
原理
服务器会为每一次会话分配一个Session对象
同一个浏览器发起的多次请求,同属于- 次会话(Session)
- 首次使用到Session时, 服务器会自动创建Session,并创建Cookie存储Sessionld发送回客户端
使用
- Session作用域: 拥有存储数据的空间,作用范围是
一次会话有效
- 一次会话是使用同一浏览器发送的多次请求。一旦浏览器关闭,则结束会话
- 可以将数据存入Session中,在一次会话的任意位置进行获取
- 可传递任何数据(基本数据类型、对象、集合、数组)
7.1、获取Session
package com.wyy.Session;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(value = "/ss")
public class SessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//通过request获取Session对象
HttpSession session = req.getSession();
System.out.println(session.getId());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
7.2、Session保存、获取数据
保存
session.setAttribute("username","gavin");
获取
session.getAttribute("username");
package com.wyy.Session;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(value = "/getvalue")
public class GetValueServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取Session对象
HttpSession session = req.getSession();
String s = (String) session.getAttribute("username");
System.out.println("从session中获得了"+s);
}
}
7.3、Session移除数据
session.removeAttribute("username");
package com.wyy.Session;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(value = "/remove")
public class RemoveServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("username");
}
}
request session区别
- request是一 次请求有效,请求改变,则request改变
- session是一 次会话有效,浏览器改变,则session改变
7.4、Session生命周期
- 开始:第一次使用到Session的请求产生, 则创建Session
- 结束:
- 浏览器关闭,则失效
- Session超时,则失效
- session.setMaxlIactielnterallseconds//设置最大有效时间(单位:秒)
- 手工销毁,则失效
- session.invalidate/);//登录退出、注销
八、ServletContext
- 全局对象,也拥有作用域,对应一个Tomcat中的Web应用
- 当Web服务 器启动时,会为每一个Web应用程序创建一块共享的存储区域(ServletContext)。
- ServletContext在Web服务器启动时创建,服务器关闭时销毁。
8.1、获取ServletContext对象
- GenericServlet提供 了getServletContext()方法。(推荐) this getServletContext();
- HttpServletRequest提供 了getServletContext()方法。(推荐)
- HttpSession提 供了getServletContext()方法。
package com.wyy.servletProject.servlet.controller;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(value = "/ctxController")
public class ServletContextController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//方式一 this getServletContext);
ServletContext servletContext = this.getServletContext();
//方式二 request对象获取
ServletContext servletContext1 = req.getServletContext();
//方式三 Session对象获取
HttpSession session = req.getSession();
ServletContext servletContext2 = session.getServletContext();
System.out.println(servletContext);
System.out.println(servletContext1);
System.out.println(servletContext2);
}
}
8.2、ServletContext作用
-
获取项目的真实路径
servletContext.getRealPath("/")
-
获取项目上下文路径
servletContext.getContextPath()
-
全局容器(ServletContext拥有作用域,可以存储数据到全局容器中)
- 存储数据: servletContext.setAttribute(“name”,value);
- 获取数据: servletContext getAttrbute(“name”);
- 移除数据: servletContext.removeAttribute(“name”);
package com.wyy.servletProject.servlet.controller;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(value = "/ctxController")
public class ServletContextController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//方式一 this getServletContext);
ServletContext servletContext = this.getServletContext();
//获取项目的真实路径
System.out.println(servletContext.getRealPath("/"));
//获取项目的上下文路径
System.out.println(servletContext.getContextPath());
//全局容器
servletContext.setAttribute("context","info");
}
}
package com.wyy.servletProject.servlet.controller;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/showContext")
public class ShowContextController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//先获取ServletContext对象
ServletContext servletContext = this.getServletContext();
String s = (String) servletContext.getAttribute("context");
System.out.println(s);
}
}
8.3、ServletContext应用场景
- HttpServletRequest: 一次请求,请求响应之前有效
- HttpSession: 一次会话开始,浏览器不关闭或不超时之前有效
- ServletContext: 服务器启动开始,服务器停止之前有效
九、过滤器
处于客户端和服务器目标资源之间的一道过滤技术。
作用:
- 执行地位在Servlet之前, 客户端发送请求时,会先经过Filter, 再到达目标Servlet中;响应时,会根据执行流程再次反向执行Filter
- 可以解决多个Servlet共性代码的冗余问题(例如:乱码处理、登录验证)
9.1、实现过程
- 编写Java类 实现Filter接口
- 在doFilter方 法中编写拦截逻辑
- 设置拦截路径
package com.wyy.Filter;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(value = "/t")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("===myfilter====");
//让请求继续
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("====end====");
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
9.2、过滤器配置
注解配置
@WebFilter(value = "/t")
xml配置
package com.wyy.Filter;
import jakarta.servlet.*;
import java.io.IOException;
public class xmlFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("Web.xml配置过滤器");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
package com.wyy.Filter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/test")
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("TestServlet");
}
}
<filter>
<filter-name>xml</filter-name>
<filter-class>com.wyy.Filter.xmlFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>xml</filter-name>
<url-pattern>/test</url-pattern>
</filter-mapping>
拦截路径
后缀拦截
package com.wyy.Filter;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServlet;
import java.io.IOException;
@WebFilter(value = "*.html")
public class HtmlFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("拦截html请求");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
通配符拦截
package com.wyy.Filter;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(value = "/*")
public class AllFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("拦截所有请求");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
9.3、过滤器链和优先级
过滤器链
客户端对服务器请求之后,服务器调用Servlet之前会执行一组过滤器(多个过滤器),那么这组过滤器就称为一条过滤器链。
每个过滤器实现某个特定的功能,当第一个Filter的doFiter方 法被调用时,Web服务器会创建一个代表Filter链的ilterChain对象传递给该方法。在doFilter方法中, 开发人员如果调用了FilterChain对象的doFiter方法,则Web服务器会检查FilterChain对象中是否还有flter,如果有,则调用第2个filter,如果没有,则调用目标资源。
在一个Web应用中,可以开发编写多个Filter,这些Filter组合 起来称之为一个Filter链。 优先级:
- 如果为注解的话,是按照类全名称的字符串顺序决定作用顺序
- 如果web.xml, 按照filter-mapping注册顺序,从上往下
- web.xml配置 高于注解方式
- 如果注解和web.xml同时配置,会创建多个过滤器对象,造成过滤多次。
9.4、过滤器应用
解决编码
package com.wyy.Filter;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebServlet;
import java.io.IOException;
@WebFilter(value = "/*")
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//统一处理请求和响应的乱码
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html;charset=utf-8");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
权限验证
package com.wyy.servletProject.filter;
import com.wyy.servletProject.entity.Manager;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(value = "/showallcontroller")
public class checkfilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//权限验证 验证管理员是否登录
//向下转型 拆箱
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession();
Manager mgr = (Manager) session.getAttribute("mgr");
if (mgr != null){
filterChain.doFilter(request,response);
}else {
response.sendRedirect(request.getContextPath()+"/loginMgr.html");
}
}
@Override
public void destroy() {
Filter.super.destroy();
}
}