采用EL表达式 对于属性的访问的隐含访问顺序是
pageContext, httpServletRequest, HttpSession, ServletContext
通过以下实例 来说明
servlet
//scopeVar.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* @author he
*/
public class scopeVar extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("firstVar", "tom");
HttpSession session =request.getSession();
session.setAttribute("secondVar","jack");
ServletContext application=this.getServletContext();
application.setAttribute("thirdVar","jerry");
RequestDispatcher dis=request.getRequestDispatcher("getScopedVars.jsp");
dis.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
//getScopedVar.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>使用EL表达式获得作用域属性</h2>
<table border="1" width="80%">
<tr>
<td width="50%">使用getAttribute 方法</td>
<td width="50%">使用EL表达式</td>
</tr>
<tr>
<td width="50%"><%=request.getAttribute("firstVar")%></td>
<td width="50%">${firstVar}</td>
</tr>
<tr>
<td width="50%"><%=session.getAttribute("secondVar")%></td>
<td width="50%">${secondVar}</td>
</tr>
<tr>
<td width="50%"><%=application.getAttribute("thirdVar")%></td>
<td width="50%">${thirdVar}</td>
</tr>
</table>
</body>
</html>