Servlet介绍:
Servlet是JavaWeb最为核心的内容,它是Java提供的一门动态web资源开发技术;
Servlet是JavaEE规范之一,其实就是一个接口,将来我们需要定义Servlet类实现Servlet接口,并
由web服务器运行Servlet;
Servlet域对象:
Servlet域对象指的是通过Servlet API提供的一组对象,用于在Servlet和JSP之间共享数据。Servlet域对象主要有以下四种:
request域对象(HttpServletRequest):
它表示当前请求及其所包含的信息,例如请求头、请求参数、请求体等。request域对象可以将数据保存在请求范围内,在同一个请求周期内,所有同一请求的Servlet、JSP之间都可以共享这些数据。
使用方式如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = "小白";
request.setAttribute("username", username); // 将数据保存在request域中
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
在 index.jsp 页面中使用 request 域中的数据:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>request域演示</title>
</head>
<body>
<h3>request域数据:${username}</h3> <!-- 使用EL表达式获取request域中的数据 -->
</body>
</html>
除了在jsp页面上使用之外,还可以在请求转发的目标servlet中使用;
session域对象(HttpSession):
它表示客户端与服务器之间的会话,可以将数据保存在会话范围内,在整个会话周期内,所有由同一客户端发起的请求之间都可以共享这些数据。
使用方式如下:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String username = "小白";
session.setAttribute("username", username); // 将数据保存在session域中
response.sendRedirect("/index.jsp");
}
在 index.jsp 页面中使用 session 域中的数据:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>session域演示</title>
</head>
<body>
<h3>session域数据:${sessionScope.username}</h3> <!-- 使用EL表达式获取session域中的数据 -->
</body>
</html>
application域对象(ServletContext):
它表示Web应用程序的上下文,可以将数据保存在该应用程序的全局范围内,在整个Web应用程序周期内,所有Servlet、JSP之间都可以共享这些数据。
使用方式如下:
public class MyServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
String company = "ABC公司";
context.setAttribute("company", company); // 将数据保存在application域中
}
}
在 index.jsp 页面中使用 application 域中的数据:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>application域演示</title>
</head>
<body>
<h3>application域数据:${applicationScope.company}</h3> <!-- 使用EL表达式获取application域中的数据 -->
</body>
</html>
page域对象(PageContext):
它表示当前JSP页面及其所包含的信息,例如JSP页面的请求、响应、输出流等。page域对象可以将数据保存在JSP页面范围内,在同一个JSP页面内的所有代码段之间都可以共享这些数据。
使用方式如下:
<%
String title = "JSP页面";
pageContext.setAttribute("title", title); // 将数据保存在page域中
%>
<html>
<head>
<title>${title}</title> <!-- 直接使用EL表达式获取page域中的数据 -->
</head>
<body>
<h3>page域数据:${title}</h3> <!-- 使用EL表达式获取page域中的数据 -->
</body>
</html>
在JSP页面中使用${}表达式获取域对象数据时,按照以下顺序进行查找
- 首先
${}
表达式会在 page 域中查找该属性,如果查找到,则返回该属性的值。 - 如果在 page 域中没有找到该属性,则会继续在 request 域中查找,如果找到,则返回该属性的值。
- 如果在 request 域中也没有找到该属性,则会继续在 session 域中查找,如果找到,则返回该属性的值。
- 如果在 session 域中也没有找到该属性,则会继续在 application 域中查找,如果找到,则返回该属性的值。
- 如果在以上四个域对象中都没有找到该属性,则返回空字符串。