jsp底层理解代码(九大内置对象与四大域)
一、使用场景
场景:login.jsp
底层代码:login_jsp.java --> login_jsp.class
import java.net.URLDecoder;public class login_jsp extends nds org.apache.jasper.runtime.HttpJspBaseimplements org.apache.jasper.runtime.JspSourceDependent,org.apache.jasper.runtime.JspSourceImports{/**发送请求,就会触发该方法*/public void _jspService(HttpServletRequest request, HttpServletResponse response){//九大内置对象HttpServletRequest request;//请求对象(请求域对象)HttpServletResponse response;//响应对象HttpSession session;//会话域对象ServletConfig config;//当前JSP(Servlet)的配置文件对象ServletContext application;//全局域对象(表示整个项目)JSPWriter out;//当前JSP的输出流对象//当前JSP的上下文关系对象(相当于国家的外交官,可以获取其他8大内置对象)PageContext pageContext;Object page = this;//当前JSP页面对象(表示当前页面)Exception exception;//当前JSP页面的异常对象//九大内置对象的初始化pageContext = _jspxFactory.getPageContext(this, request, response,null, true, 8192, true);this.request = request;this.response = response;session = pageContext.getSeesion();config = pageContext.getServletConfig();application = pageContext.getServletContext();out = pageContext.getOut();page = this;exception = pageContext.getException();response.setContentType("text/html;charset=UTF-8");out.writer("<html>\r\n");out.writer("<head>\r\n");out.writer(" <title>Title</title>\r\n");out.writer("</head>\r\n");out.writer("<body>\r\n");out.writer("\r\n");out.writer("<html>\r");out.writer("<html>\r");out.writer("<html>\r");Cookie[] cookies = request.getCookies();if(cookies != null){int count = 0;for (Cookie cookie : cookies) {String name = cookie.getName();String value = URLDecoder.decode(cookie.getValue(),"UTF-8");if("username".equals(name)){session.setAttribute("username",value);count++;}if("name".equals(name)){session.setAttribute("name",value);count++;}if("role".equals(name)){session.setAttribute("role",value);count++;}}if(count == 3){response.sendRedirect("index.jsp");}}String msg = (String) request.getAttribute("msg");out.print((msg!=null)?msg:"");out.writer("\r\n");out.writer(" <h1>登录页面</h1>");.....}}
二、九大内置对象与四大域
<%//JSP九大内置对象:// request;// response;// session;// out;// application;// config;// page;// pageContext;// exception;//JSP九大内置对象里有四大域// request;// session;// application;// pageContext;//注意:页面域存储的数据只能在当前页面有效pageContext.setAttribute("msg","aaa");//注意:请求域存储的数据只能在本次请求中有效request.setAttribute("msg","bbb");//注意:会话域存储的数据只能在对应的客户端中有效session.setAttribute("msg","ccc");//注意:全局域存储的数据在整个项目中都有效application.setAttribute("msg","ddd");%>
三、EL表达式
EL获取四大域里的数据
优先级别:页面域>请求域>会话域>全局域
el底层理解:${msg}
<%
Object msg = pageContext.getAttribute(“msg”);
if(msg != null){
out.print(msg);
return;
} msg = request.getAttribute(“msg”);
if(msg != null){
out.print(msg);
return;
} msg = session.getAttribute(“msg”);
if(msg != null){
out.print(msg);
return;
} msg = application.getAttribute(“msg”);
if(msg != null){
out.print(msg);
return;
}
%>
JSTL:优化JSP页面的逻辑代码(分支、循环)