JavaWeb-11 (JSP&EL表达)

简介:

JavaWeb-11 JSP&EL表达式

JSP

四、JSP语法(学好的关键:相应的Servlet)

JavaWeb-10 总结:session技术也是cookie的一种。server给浏览器创建一个篮子,并加上编号,这编号会存储到client上,当client再次訪问server时。server会读取client的ID号。假设server找得到,就在篮子中拿出该client的session,若没有就新建一个

重点:URL重写。

1、JSP模版元素

JSP模板元素:HTML页面

JSP页面中的HTML内容称之为JSP模版元素。 

JSP模版元素定义了网页的基本骨架。即定义了页面的结构和外观。

2、JSP表达式

JSP脚本表达式(expression)用于将程序数据输出到client

语法:<%= 变量或表达式 %>

举例:当前时间:<%= new java.util.Date() %> 

JSP引擎在翻译脚本表达式时,会将程序数据转成字符串,然后在对应位置用out.print(…) 将数据输给client。

JSP脚本表达式中的变量或表达式后面不能有分号(;)。

注意:现实中不同意这么写,那是html,是美工开发框架用的。

写这么多java代码没意义。正规开发中不同意出现Jsp脚本

项目架构:


下面实验要使用到的User类:

public class User {

    private String id ;

    private String username ;

    private int age ;

    public User() {
    }

    public User(String id, String username, int age) {
        super();
        this.id = id;
        this.username = username;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

实验:1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>输出表达式</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
        <%
            //String name = "张三丰" ;
            request.setAttribute("name", "张三丰") ;
            String name = (String) request.getAttribute("name") ;
            out.write(name) ;
        %>
        <br>
        :
        <%=name %>
  </body>
</html>

在浏览器输入http://localhost:8080/day1100jsp/1.jsp,IE结果:


3、JSP脚本片断

a、JSP脚本片断(scriptlet)用于在JSP页面中编写多行Java代码。语法:

<% 
        多行java代码 
%> 

注意:JSP脚本片断中仅仅能出现java代码。不能出现其他模板元素, JSP引擎在翻译JSP页面中,会将JSP脚本片断中的Java代码将被原封不动地放到Servlet的_jspService方法中。 

JSP脚本片断中的Java代码必须严格遵循Java语法,比如。每运行语句后面必须用分号(;)结束。

b、在一个JSP页面中能够有多个脚本片断,在两个或多个脚本片断之间能够嵌入文本、HTML标记和其它JSP元素。

举例:
    <%
        int x = 10;
        out.println(x);
    %>
    <p>这是JSP页面文本</p>
    <%
        int y = 20;
        out.println(y);
    %>

多个脚本片断中的代码能够相互訪问。宛如将全部的代码放在一对<%%>之中的情况。如:out.println(x);

正规开发中的JSP中不应出现java脚本:标签封装

c、单个脚本片断中的Java语句能够是不完整的,可是,多个脚本片断组合后的结果必须是完整的Java语句。比如:

    <%
        for (int i=1; i<5; i++) 
        {
    %>

        <H1>www.it315.org</H1>

    <%
        }
    %> 

实验:2.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>jsp脚本片段</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
        <table border = 1>
           <tr>
                <td>编号</td>
                <td>姓名</td>
                <td>年龄</td>
            </tr>
        <%
            List<User> list = new ArrayList<User>() ;
            list.add(new User("1","张三丰",20)) ;
            list.add(new User("2","张无忌",23)) ;
            list.add(new User("3","张翠山",25)) ;
            list.add(new User("4","张国老",28)) ;

            /*out.write("<table border = 1>") ;
            out.write("<tr><td>编号</td><td>姓名</td><td>年龄</td></tr>") ;
            for(int i = 0 ;i <list.size() ;i++){
                User u = list.get(i) ;
                out.write("<tr><td>") ;
                out.write(u.getId()) ;
                out.write("</td><td>") ;
                out.write(u.getUsername()) ;
                out.write("</td><td>") ;
                out.write(u.getAge() + "") ;
                out.write("</td></tr>") ;


            }*/
           // out.write("</table>") ;

            for(int i = 0 ;i<list.size() ;i++){
                User u = list.get(i) ;              
        %>
            <tr>
                <td><%=u.getId() %></td>
                <td><%=u.getUsername() %></td>
                <td><%=u.getAge() + "" %></td>
            </tr>
        <%
            }
        %>
        </table>
  </body>
</html>

以上的底层Servlet源代码例如以下:

2jsp.java

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;
import com.heima.bean.*;

public final class _2_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

  private static java.util.List _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.AnnotationProcessor _jsp_annotationprocessor;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
  }

  public void _jspDestroy() {
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write('\r');
      out.write('\n');

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write("    \r\n");
      out.write("    <title>jsp脚本片段</title>\r\n");
      out.write("    \r\n");
      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
      out.write("\t<!--\r\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");
      out.write("\t-->\r\n");
      out.write("\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("  \t\t<table border = 1>\r\n");
      out.write("  \t\t   <tr>\r\n");
      out.write("\t\t\t\t<td>编号</td>\r\n");
      out.write("\t\t\t\t<td>姓名</td>\r\n");
      out.write("\t\t\t\t<td>年龄</td>\r\n");
      out.write("\t\t\t</tr>\r\n");
      out.write("\t\t");

            List<User> list = new ArrayList<User>() ;
            list.add(new User("1","张三丰",20)) ;
            list.add(new User("2","张无忌",23)) ;
            list.add(new User("3","张翠山",25)) ;
            list.add(new User("4","张国老",28)) ;

            /*out.write("<table border = 1>") ;
            out.write("<tr><td>编号</td><td>姓名</td><td>年龄</td></tr>") ;
            for(int i = 0 ;i <list.size() ;i++){
                User u = list.get(i) ;
                out.write("<tr><td>") ;
                out.write(u.getId()) ;
                out.write("</td><td>") ;
                out.write(u.getUsername()) ;
                out.write("</td><td>") ;
                out.write(u.getAge() + "") ;
                out.write("</td></tr>") ;


            }*/
           // out.write("</table>") ;

            for(int i = 0 ;i<list.size() ;i++){
                User u = list.get(i) ;              

      out.write("\r\n");
      out.write("\t\t\t<tr>\r\n");
      out.write("\t\t\t\t<td>");
      out.print(u.getId() );
      out.write("</td>\r\n");
      out.write("\t\t\t\t<td>");
      out.print(u.getUsername() );
      out.write("</td>\r\n");
      out.write("\t\t\t\t<td>");
      out.print(u.getAge() + "" );
      out.write("</td>\r\n");
      out.write("\t\t\t</tr>\r\n");
      out.write("\t\t");

            }

      out.write("\r\n");
      out.write("\t\t</table>\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else log(t.getMessage(), t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

在浏览器输入:http://localhost:8080/day1100jsp/2.jsp,输出结果:


3.1、JSP声明

<%! name = "啊啊啊"%>//全局变量
<% name = "啊啊啊"%>//局部变量

JSP页面中编写的全部代码,默认会翻译到servlet的service方法中, 而Jsp声明中的java代码被翻译到_jspService方法的外面。语法:

<%!

java代码 %>

所以。JSP声明可用于定义JSP页面转换成的Servlet程序的静态代码块、成员变量和方法 。

多个静态代码块、变量和函数能够定义在一个JSP声明中,也能够分别单独定义在多个JSP声明中。

JSP隐式对象的作用范围仅限于Servlet的_jspService方法,所以在JSP声明中不能使用这些隐式对象。

实验: 3.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>jsp声明</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
        <%!
            String name = "小龙女" ;
            public static void demo(){
                  System.out.print("你好") ;              
            }

            public void demo1(){
                  System.out.print("你好") ;

            }
           public class A{}

        %>
        <%
            demo1() ;
            demo() ;
        %>
  </body>
</html>

在浏览器输入:http://localhost:8080/day1100jsp/3.jsp。在server输出的结果例如以下:


总结出来的在jsp编译环境下:事实上就是在HTML页面里,用标签编写的代码。会转成servlet类里的out.write()里的内容输出。而用<%%>括了的代码就会转成servlet类里的正常java代码

4、JSP凝视

    <!--HTML凝视-->

    //这是java凝视

    <%--<%这是jsp凝视%>--%>:这种凝视仅仅能在jsp文档里能够看见。把文档编译成了的servlet类文件就观察不到了,相当于隐身了。

实验: 4.jsp和servlet源代码

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>jsp凝视</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
        <%
            //这是java凝视
        %>
        <%--<%
            out.write("你好") ;
        %>--%>
        <!-- HTML凝视 -->
  </body>
</html>

在浏览器输入:http://localhost:8080/day1100jsp/4.jsp, 可发现Servlet源代码例如以下:

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;
import com.heima.bean.*;

public final class _4_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

  private static java.util.List _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.AnnotationProcessor _jsp_annotationprocessor;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
  }

  public void _jspDestroy() {
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write('\r');
      out.write('\n');

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write("    \r\n");
      out.write("    <title>jsp凝视</title>\r\n");
      out.write("    \r\n");
      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
      out.write("\t<!--\r\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");
      out.write("\t-->\r\n");
      out.write("\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("  \t\t");

            //这是java凝视

      out.write("\r\n");
      out.write("  \t\t");
      out.write("\r\n");
      out.write("  \t\t<!-- HTML凝视 -->\r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else log(t.getMessage(), t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

5、JSP指令

JSP指令(directive)是为JSP引擎而设计的,它们并不直接产生不论什么可见输出,而仅仅是告诉引擎怎样处理JSP页面中的其余部分。

在JSP 2.0规范中共定义了三个指令:

a. page指令


b. Include指令


c. taglib指令


page指令:演示errorPage:当你的页面出现异常后你须要去哪个页面(错误处理页面)。

演示include指令:<%@ include file = "6.jsp"%> //静态包括,在6.jsp里不能有和5.jsp同样的一部分指令标签。也能够包括txt文档(a.txt)。

以上这样的叫静态包括,也是代码级别的包括,所包括的要使用的代码的其它代码能够删除掉! <%@ taglib %>:引入标签库 除了import指令标签能够反复。

、其它指令标签仅仅能写一遍 errorPage也能够在web.xml里配置(优先级高) <error-page> <error-code>404</error-code> <location></location> </error-page>

实验:

5.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" errorPage="6.jsp" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>jsp指令标签</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>

        <%response.setCharacterEncoding("UTF-8"); %>
        <%--<%
        //  out.write(10/0) ;
        %>--%>
        aaaaaaaaaaaaaaaa
        <%@ include file="6.jsp"  %>
        <br>
        <%@ include file="a.txt" %>

  </body>
</html>

6.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" isErrorPage="true" %>
  <body>
       server正忙。请一会再来訪问
       <%--<%
           out.write(exception.getMessage()) ;
       %>  --%>  
</body>

在浏览器输入:http://localhost:8080/day1100jsp/5.jsp。

浏览器输出下面结果:


6、JSP标签

<jsp:include>标签  :动态包括

    page属性、它包括了其它路径的jsp时,里面反复的内容不用删除。

不像静态包括那样。 静态包括与动态包括之间的优缺点:静态包括(代码级别的包括。效率高)、动态包括(页面级别的包括,),他们结果没差别。

<jsp:forward>标签 : page属性:请求转发(地址栏是不变的),动态标签中的forward标签是须要配合param标签来使用吗?不一定。 <jsp:param>标签 : 怎么拿出10.jsp的param属性值,还有中文值们拿出是乱码怎么办?request.setCharacterEncodeing("UTF-8");重要)。主要用来传递參数。 value属性: name属性

实验:10.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>动作指令</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
     <%--<jsp:include page="11.jsp"></jsp:include>--%>
     <% request.setCharacterEncoding("UTF-8") ; %>

     <jsp:forward page="11.jsp?a=abc&addr=武当山">
          <jsp:param value="bbbbb" name="b"/>
          <jsp:param value="张无忌" name="name"/>
     </jsp:forward>

  </body>
</html>

11.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>动作指令</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body><%--
    111111111111111
     <%
        out.write("你好") ;
     %>
  --%>
      <%
           String a = request.getParameter("a") ;
           String b = request.getParameter("b") ;
           String addr = request.getParameter("addr") ;
           String name = request.getParameter("name") ;

          // name = new String(name.getBytes("iso-8859-1"),"UTF-8") ;

           out.write(a + ":" + b + "<br>") ;
           out.write(name + ":" + addr + "<br>") ;
      %>
  </body>
</html>

在浏览器输入:http://localhost:8080/day1100jsp/10.jsp,结果例如以下:


7、JSP内置对象

a、request

b、response

c、config

d、application

e、exception

f、Session

g、page

h、out

i、pageContext

JSP九大隐式对象表示图


7.1、out隐式对象:

a. out隐式对象用于向client发送文本数据。

b. out对象是通过调用pageContext对象的getOut方法返回的。其作用和使用方法与ServletResponse.getWriter方法返回的PrintWriter对象很相似。

c. JSP页面中的out隐式对象的类型为JspWriter,JspWriter相当于一种带缓存功能的PrintWriter,设置JSP页面的page指令的buffer属性能够调整它的缓存大小,甚至关闭它的缓存。

d. 仅仅有向out对象中写入了内容,且满足例如以下不论什么一个条件时。out对象才去调用ServletResponse.getWriter方法,并通过该方法返回的PrintWriter对象将out对象的缓冲区中的内容真正写入到Servlet引擎提供的缓冲区中:

e. 设置page指令的buffer属性关闭了out对象的缓存功能

f. out对象的缓冲区已满

g. 整个JSP页面结束

实验:7.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>out对象的细节</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
        <%
            out.write("12345") ;
            //out.flush() ;
            response.getWriter().write("67890") ;
        %>  
  </body>
</html>

在浏览器输入:http://localhost:8080/day1100jsp/7.jsp,输出结果例如以下: 


out对象总结:

out.write("123");

reponse.getWriter().write("456");

该两对象不一样。他们要输出的内容都先经过缓存,再由server整理在输出,而输出是先输出456 再123。根本原因是server会先清空out对象的缓存,那么out对象要输出的内容会把内容先存在reponse.getWriter()对象缓存里,当server要清空reponse.getWriter()对象缓存时,就会一起输出。所以是456 123

假设在指令标签的缓存属性设置xxx="0KB" 那么以上总结就不成立了,server会直接顺序输出以上内容。

7.2、pageContext对象

pageContext对象是JSP技术中最重要的一个对象,它代表JSP页面的执行环境,这个对象不仅封装了对其他8大隐式对象的引用。它自身还是一个域对象。能够用来保存数据。而且,这个对象还封装了web开发中经常涉及到的一些经常使用操作,比如引入和跳转其他资源、检索其他域对象中的属性等。jsp中最重要对象。底层代码的基础!

7.3、通过pageContext获得其它对象

getException方法返回exception隐式对象 

getPage方法返回page隐式对象

getRequest方法返回request隐式对象

getResponse方法返回response隐式对象 

getServletConfig方法返回config隐式对象

getServletContext方法返回application隐式对象

getSession方法返回session隐式对象 

getOut方法返回out隐式对象

pageContext封装其他8大内置对象的意义,思考:假设在编程过程中。把pageContext对象传递给一个普通java对象。那么这个java对象将具有什么功能?  

7.4、pageContext对象的方法

public void setAttribute(java.lang.String?

name,java.lang.Object?value) public java.lang.Object?getAttribute(java.lang.String?

name) public void?removeAttribute(java.lang.String?name)

7.5、pageContext对象中还封装了訪问其他域的方法

public java.lang.Object?

getAttribute(java.lang.String?name,int?

scope) public void setAttribute(java.lang.String?

name, java.lang.Object?value,int?scope) public void?removeAttribute(java.lang.String?

name,int?

scope)

7.5、代表各个域的常量

PageContext.APPLICATION_SCOPE

PageContext.SESSION_SCOPE

PageContext.REQUEST_SCOPE

PageContext.PAGE_SCOPE 

findAttribute方法    (*重点,查找各个域中的属性) EL表达式
  • PageContext代表jsp页面的执行环境,页面对象。也是一个域对象,封装了经常使用操作。

    1、域对象(第四个域对象了。):范围在本页面

    a、存储数据:setAttribute()、和它的重载(4个范围)
    
    b、能够将数据存放在其它范围中
    
    c、查找方法findAttribute():要从page_Scope。Request_Scope。SESSION_Scope,APPLICATION_SCOPE范围依次去寻找,找不到返回null
    

    2、提供了请求转发和包括

        forward()
    
        include()
    

实验:

8.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>pageContext对象</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
        <!--
              1. 域对象: 范围在本页面
                   a. 存储数据
                   b. 能够将数据存放到其它范围中
                   c. 查找方法 findAttribute() : 要从Page_Scope,Request_SCOPE,sESSION_SCOPE,APPLICATION_SCOPE范围依次去
                      寻找,找不到返回空字符串
              2. 提供了拿取其它8个对象的方法
              3. 提供了请求转发和包括
        -->

        <%
            pageContext.setAttribute("name", "东方不败") ;
            pageContext.setAttribute("name1", "张三丰",pageContext.REQUEST_SCOPE) ;


            String name = (String) pageContext.getAttribute("name") ;
          String name1 = (String) pageContext.getAttribute("name1") ;
            out.write(name) ;
            out.write(name1);

            pageContext.setAttribute("name2", "张无忌") ;
            request.setAttribute("name2", "张三丰") ;
            session.setAttribute("name2", "张翠山") ;
            application.setAttribute("name2", "张果老") ;

           // request.setAttribute("age", "123") ;
           // pageContext.getRequest().setAttribute("age", "123") ;
        %>
         <!--  <a href="http://blog.163.com/faith_yee/blog/9.jsp">9.jsp</a> -->
         <%
            //pageContext.forward("9.jsp") ;
             pageContext.include("9.jsp") ;
         %>
        <br>
        <%--<%
            String n = (String) pageContext.findAttribute("name2") ;
            out.write(n) ;
        %>
  --%></body>
</html>

9.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>pageContext对象</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
      9999999999999999999<br>

        <%
            //String name = (String)request.getAttribute("name1") ;         


            //out.write(name) ;

            String name = (String)pageContext.findAttribute("name2") ;
            out.write(name) ;
        %>
  </body>
</html>

在浏览器输入:http://localhost:8080/day1100jsp/8.jsp,在浏览器输出结果例如以下:


五、JSP中操作JavaBean

5.1、JavaBean的概念:

(VO:value Object, DO:Data Object 。POJO:最简单的java对象 ,DTO:Data Transfer Object)不同的场景不同的解释

遵循一定的命名规则:

1、必须有默认的构造方法
2、类的声明为public类型
3、字段都是私有的private boolean married
4、提供共同拥有的getter或setter方法(属性)。

通常是先java.io.Serializable接口

实际开发中有什么用?封装数据。便于传递数据

5.2、JavaWeb开发模型:

MVC模型(model(JavaBean数据)+veiw(JSP显示)+controller(Servlet控制器))

现实的样例:桌子+吧台+厨房(流程!)
三层架构:MVC仅仅是三层架构的表现层


三层架构:(表现层+业务逻辑层+数据訪问层)

(耦合性低:兼容性扩展性强!

评价程序猿好坏:编出来的成品的扩展性。QQ。

更新换代这么多年非常大原因是项目扩展性好

JSP开发模式 :

*SUN公司推出JSP技术后。同一时候也推荐了两种web应用程序的开发模式。一种是JSP+JavaBean模式(模型1)。一种是Servlet+JSP+JavaBean模式(模型2)。


*JSP+JavaBean模式适合开发业务逻辑不太复杂的web应用程序,这样的模式下。JavaBean用于封装业务数据。JSP即负责处理用户请求,又显示数据。

(计算器演示样例) *Servlet+JSP+JavaBean(MVC)模式适合开发复杂的web应用,在这样的模式下,servlet负责处理用户请求,jsp负责数据显示,javabean负责封装数据。 Servlet+JSP、JavaBean模式程序各个模块之间层次清晰,web开发推荐採用此种模式。(绘图MVC及三层架构)

5.3、jsp:useBean标签(重要内容:就是要封装标签里的内容!)

<jsp:useBean>标签用来干什么的:创建对象的。
<!--User user = new User();-->
在这样的标签里能够创建对象(用来取代页面里的java代码)    
属性
    1、id
    2、class:我是用哪个类创建的
    3、scope:作用范围:(拿去bean中的数据,在实例里用动作标签拿不出还有一个jsp里的session属性,尽管session是共享的。而jsp里的java代码能够拿出,老师给我们展示底层的代码)    

实验:

12.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>jsp:UseBean标签</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
     <!--  User user = new User() ; -->
      <jsp:useBean id="user" class="com.heima.bean.User" scope="session">
           <jsp:setProperty property="username" name="user" value="张无忌"/>
      </jsp:useBean>

      <jsp:getProperty property="username" name="user"/>

      <a href="http://blog.163.com/faith_yee/blog/13.jsp">13.jsp</a>
  </body>
</html>

13.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>jsp:UseBean标签</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
     <!-- 拿取bean中的数据 -->
     <!--  <jsp:getProperty property="username" name="user"/>-->
     <%
        User u = (User) session.getAttribute("user") ;
        out.write(u.getUsername()) ;   
     %>

  </body>
</html>

在浏览器输入http://localhost:8080/day1100jsp/12.jsp,输出结果例如以下:


在点击页面上的超链:进入了http://localhost:8080/day1100jsp/13.jsp,输出下面结果: 张无忌

5.4、jsp:useBean标签的内省机制

在jsp里怎么封装javaBean? 学习经验:假设搞不懂jsp怎么利用<jsp:useBean> 标签来封装JavaBean的话,能够观察jsp的底层代码:Servlet类的代码!

    <jsp:setProperty="*" name = "user"/>//内省

    <jsp:getProperty property="id" name="user"/>

    <jsp:getProperty property="username" name="user"/>

    <jsp:getProperty property="age" name="user"/>

以上过程叫内省机制。

那么内省的底层是怎么回事?

内省要求Bean的属性名和页面上的表单控制的名字一样即可

实验: 14.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>jsp:UseBean标签的内省机制</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
      <form action="15.jsp" method="post">
          编号: <input type = "text" name = "id"><br>
          姓名: <input type = "text" name = "username"><br>
          年龄: <input type = "text" name = "age"><br>
          <input type = "submit" value = "提交"><br>
      </form>

       <a href="http://blog.163.com/faith_yee/blog/15.jsp?id=111&username=abc&age=100">15.jsp</a><%--

       <jsp:forward page="15.jsp">
            <jsp:param value="1000" name="id"/>
            <jsp:param value="nba" name="username"/>
            <jsp:param value="50" name="age"/>
       </jsp:forward>
  --%></body>
</html>

15.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>jsp:UseBean标签的内省机制</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->

  </head>

  <body>
    <% request.setCharacterEncoding("UTF-8") ; %>
     <jsp:useBean id="user" class="com.heima.bean.User"></jsp:useBean>
     <!-- 封装超链的数据 -->
     <jsp:useBean id="user1" class="com.heima.bean.User"></jsp:useBean>

    <jsp:setProperty property="*" name="user"/>
     <jsp:setProperty property="id" name="user" param="id"/>
     <jsp:setProperty property="*" name="user1"/>

     <jsp:getProperty property="id" name="user" />:
     <jsp:getProperty property="username" name="user"/>:
     <jsp:getProperty property="age" name="user"/>
     <hr>
     <jsp:getProperty property="id" name="user1"/>:
     <jsp:getProperty property="username" name="user1"/>:
     <jsp:getProperty property="age" name="user1"/>
  </body>
</html>

在浏览器输入:http://localhost:8080/day1100jsp/14.jsp,页面例如以下: 


在表单里填写例如以下信息:


点击提交:


或者在14.jsp页面里点击超链,结果例如以下:


在15.jsp里的总结

<!--封装超链的数据-->
< .........>
<jsp:setProperty="*" name = "user1"/>(内省!

) <jsp:getProperty property="id" name="user1"/> <jsp:getProperty property="username" name="user1"/> <jsp:getProperty property="age" name="user1"/>

出现故障:在超链提交的数据怎么限制封装到哪个对象里?

主要看属性名+參数是否一致。

发现user所要封装的属性名+參数和user1所要封装的属性名+參数都一样。所以都封装成了对象(user+user1),所以在页面输出了两个对象的内容。15.jsp不会关心其它jsp传过来的数据是否反复或者是什么方式传过来的,仅仅要传过来的属性名+參数满足JavaBean对象里的属性名和方法的接口。那么就为这些数据新建对象。

假设想把传过来的数据指定特定的对象名能够吗?貌似不行。以上是内省机制。

六、四大域对象(相当重要)

a. PageContext:页面范围的数据。用的非常少

b. ServletRequest:请求范围的数据。

用的非常多。显示一次数据后就没实用了。这种数据应该放到该范围中

c. HttpSession:会话范围的数据。用的非常多。每次请求和响应都须要共享的数据。比方登录信息,购物信息。

d. ServletContext(application域):应用范围的数据。用的不多。全部client都共享的信息。注意同步。

数据能不能取到,关键是不是从一个地方取的数据

使用的情况详细分析

七、EL表达式(属于JSP中的技术,今天最重要!

1、EL表达式简单介绍

EL 全名为Expression Language。EL主要作用:

1、获取数据:

EL表达式主要用于替换JSP页面中的脚本表达式,以从各种类型的web域 中检索java对象、获取数据。(某个web域 中的对象,訪问javabean的属性、訪问list集合、訪问map集合、訪问数组)

2、运行运算:

利用EL表达式能够在JSP页面中运行一些主要的关系运算、逻辑运算和算术运算,以在JSP页面中完毕一些简单的逻辑运算。${user==null}

3、获取web开发经常使用对象

EL 表达式定义了一些隐式对象,利用这些隐式对象,web开发者能够非常轻松获得对web经常使用对象的引用。从而获得这些对象中的数据。

4、调用Java方法

EL表达式同意用户开发自己定义EL函数,以在JSP页面中通过EL表达式调用Java类的方法。


a、获取数据:

    老做法:

        String name  =(Stirng )session.getAttribute("name");
        out.write(name);

    EL表达式:

        El:${name}  拿到的name也是看设置好的范围来获取的。(观察底层代码)

        指定某个域对象中拿去数据:${sessionScope.name}  

        EL中存在了11个隐含对象

    第一仅仅猫的样例:

        &{user.friend.cat.name}

        &{user["friend"]["cat"]["name"]}

        用点的地方能够用中括号。反之不行

        EL表达式输出常量要加引號,不加的话会识别是变量 ${"abvca"}


    使用EL表达式获取数据语法:“${标识符}”

    EL表达式语句在运行时,会调用pageContext.findAttribute方法,用标识符为keyword,分别从page、request、session、application四个域中查找对应的对象。找到则返回对应对象。找不到则返回”” (注意。不是null,而是空字符串)。 

    演示样例:${user}

    EL表达式也能够非常轻松获取JavaBean的属性,或获取数组、Collection、Map类型集合的数据,比如:

        ${user.address.city}
        ${user.list[0]}:訪问有序集合某个位置的元素
        ${map.key}  : 获得map集合中指定key的值

    结合JSTL的foreach标签,使用EL表达式也能够非常轻松迭代各种类型的数组或集合。演示样例:

        迭代数组
        迭代collection类型集合
        迭代map类型集合

实验:project架构:


在实验中要使用到的类: User.java

package com.heima.bean;

public class User {

    private String id ;

    private String username ;

    private Friend  friend;

    private int age ;

    public User() {
    }

    public User(String id, String username, int age) {
        super();
        this.id = id;
        this.username = username;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Friend getFriend() {
        return friend;
    }

    public void setFriend(Friend friend) {
        this.friend = friend;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

Friend.java

package com.heima.bean;

public class Friend {

    private Cat cat ;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

}

Cat.java

package com.heima.bean;

public class Cat {

    private String name ;

    private String color ;

    public Cat() {
    }

    public Cat(String name, String color) {
        super();
        this.name = name;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public String getColor() {
        return color;
    }
}

实验:1.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>el表达式从域对象中获取数据</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->
  </head>

  <body>
        <%
            pageContext.setAttribute("name", "小龙女") ;
            request.setAttribute("name", "赵敏") ;
            session.setAttribute("name", "黄蓉") ;
            application.setAttribute("name", "周芷若") ;

            String name = (String) session.getAttribute("name") ;
            out.write(name) ;

            User user = new User() ;
            Friend f = new Friend() ;
            f.setCat(new Cat("喵喵","白色")) ;
            user.setFriend(f) ;

            request.setAttribute("user", user) ;

            List<User> list = new ArrayList<User>() ;
            list.add(new User("1","张无忌",20)) ;
            list.add(new User("2","乔峰",25)) ;
            list.add(new User("3","郭靖",30)) ;

            request.setAttribute("list", list) ;

            Map<String,User> map = new HashMap<String,User>() ;
            map.put("a", new User("1","张无忌",20)) ;
            map.put("b", new User("2","乔峰",25)) ;
            map.put("c", new User("3","郭靖",30)) ;

            request.setAttribute("map", map) ;
        %>
            <br>
            採用el表达式输出常量:${"abcde"}<br>
            採用el表达式拿取数据: ${name}<br>
            指定从session中拿取数据: ${sessionScope.name }<br>
            拿到人的朋友的第一仅仅猫的名字: ${user.friend.cat.name}:${user["friend"]["cat"]["name"]} <br>
            拿到人的朋友的第一仅仅猫的颜色: ${user.friend.cat.color} <br>
            拿取list中的第一个人的名字:${list[0].username} <br>
            拿取map中的乔峰的名字:${map["b"].username}:${map.b.username} <br>

  </body>
</html>

在浏览器输入:http://localhost:8080/day1101el/1.jsp,页面输出下面结果:


b、运行运算:

    语法:

        ${运算表达式},EL表达式支持例如以下运算符:


        empty运算符:

            检查对象是否为null或“空”,非常好用!!!

三元表达式: ${user!=null?

user.name : “”} ,非常好用!

! [ ] 和 . 号运算符

实验:2.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>el表达式的数学运算</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->
  </head>

  <body>
       <%
             int a = 10 ;
             request.setAttribute("a", a) ;

             String s = (String) request.getAttribute("name") ;
             out.write(s) ;
             request.setAttribute("name", s) ;

            Map<String,User> map = new HashMap<String,User>() ;
            map.put("a", new User("1","张无忌",20)) ;
            map.put("b", new User("2","乔峰",25)) ;
            map.put("c", new User("3","郭靖",30)) ;

            request.setAttribute("map", map) ;
       %>
           运行加法: ${1+1 }<br>
           运行比較运算:${ 10 >5}:${ 10 gt 5}<br>
           运行比較运算:${ a >5}<br>
           运行逻辑运算: ${a > 5 || a < 0 }<br>
           运行null运算:${name == null}<br>
           运行三元运算符: ${a>5?"哈哈":"呵呵" }<br>
           检測map是否为空:${empty map }:${ not empty map }

  </body>
</html>

在浏览器输入:http://localhost:8080/day1101el/2.jsp。页面输出结果例如以下:


c、获取web开发经常使用对象


实验:

3.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>el表达式的内置对象</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->
  </head>

  <body>
       <%request.setCharacterEncoding("UTF-8") ; %>
       <form action="4.jsp" method="get">
            姓名: <input type = "text" name = "username"><br>
            password: <input type = "text" name = "pass"><br>
            反复password: <input type = "text" name = "pass"><br>
             <input type = "submit" value = "提交"><br>
       </form>      

       <a href="http://blog.163.com/faith_yee/blog/4.jsp?username=张无忌">4.jsp</a>  
       <%--<jsp:forward page="4.jsp">
            <jsp:param value="东方不败" name="username"/>
       </jsp:forward>
  --%></body>
</html>

4.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>el表达式的内置对象</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->
  </head>

  <body><%--
     <%
         String name = request.getParameter("username") ;
         name = new String(name.getBytes("ISO-8859-1"),"GBK") ;
         out.write(name) ;
     %>--%>
       拿取表单传递的參数: ${param.username }<br>
       拿取超链传递的參数: ${param.username }<br>
       拿取请求转发传递的參数: ${param.username }<br>
       拿取重名參数的值: ${paramValues.pass[0] }: ${paramValues.pass[1] }<br>
       获取请求头的值: ${header.Referer }<br>
       获取请求头的值: ${headerValues.Referer[0] }<br>
       获取全局參数的值: ${initParam.name }<br>
       获取Cookie(是一个map): ${cookie.JSESSIONID }<br>
       获取Cookie(是一个Cookie对象)的名字: ${cookie.JSESSIONID.name }<br>
       获取Cookie(是一个Cookie对象)的值: ${cookie.JSESSIONID.value }<br>


  </body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name> 

  <context-param>
    <param-name>name</param-name>
    <param-value>山本五十六</param-value>
  </context-param>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

在浏览器输入http://localhost:8080/day1101el/3.jsp。页面结果例如以下,输入例如以下信息:


点击提交后进入4.jsp,显演示样例如以下结果:


假设在13.jsp点击超链,得到例如以下结果:


获取Cookie(是一个map)的键:${cookie.key}//拿不出

d、调用Java方法

    ${"abc"+"de"}//不行:+支持整数浮点数,不支持字符串

    EL不支持字符串的不论什么操作

    但我们能够定义函数来实现

    ${fun:toupper("abcde")}//EL不识别函数,那么怎么来实现这种方式?EL一定和底层的JAVA代码相关联,所以我们能够自己定义标签函数

实验: 5.jsp

<%@ page language="java" import="java.util.*,com.heima.bean.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/myfun" prefix="fun" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions"  prefix="fn" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>el表达式的内置对象</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->
  </head>

  <body>
        ${fun:toupper("abcde")} 
        ${fun:toupper("aaaaaaaaa") }   
        ${fun:out("abcde") }

  </body>
</html>

a.tld

<?xml version="1.0" encoding="UTF-8" ?>

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">

  <tlib-version>1.1</tlib-version>
  <short-name>fun</short-name>
  <uri>http://java.sun.com/jsp/myfun</uri>

  <function>
    <name>toupper</name>
    <function-class>com.heima.demo.Demo</function-class>
    <function-signature>java.lang.String demo(java.lang.String)</function-signature>

  </function>

  <function>
    <name>out</name>
    <function-class>com.heima.demo.Demo</function-class>
    <function-signature>void demo1(java.lang.String)</function-signature>

  </function>

 </taglib>

Demo.java

package com.heima.demo;

public class Demo {

    //将參数转变为大写
    public static String demo(String str){
        return str.toUpperCase() ;
    }

    public static void demo1(String str){
        System.out.println(str);
    }
}

在浏览器输入:http://localhost:8080/day1101el/5.jsp。得到例如以下结果:


方法总结:

1、创建一个类(后台)
2、类里写方法(静态)
3、写描写叙述性文件(注意路径)
4、页面上要用taglib指令标签引入
5、能够用EL语句是使用了

taglib里能够引用sun公司已经定义好了的方法。

用属性来改变要用法的名字

八、在地址栏里输入中文,server解析为乱码的IE解决的方法

地址栏输入有中文:

String s = request.getQueryString("username");

//String s = request.getParameter("username");

s = new String(s.getBytes("iso-8859-1"),"gbk");

out.write(s);    

下载

版权声明:本文博客原创文章。博客,未经同意,不得转载。







本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/4746773.html,如需转载请自行联系原作者


相关文章
|
11天前
|
存储 XML SQL
jsp、EL表达式、Jstl使用
jsp、EL表达式、Jstl使用
|
9月前
|
Java
欢迎来到Jsp编程课时六——EL表达式(JSP第十五课时)
欢迎来到Jsp编程课时六——EL表达式(JSP第十五课时)
80 0
|
Java
JSP EL中的函数
JSP EL中的函数
60 0
|
Java
JSP学习——EL表达式和JSTL学习小结
JSP学习——EL表达式和JSTL学习小结
90 0
|
前端开发 Java
JSP简介&&EL表达式&& JSTL
JSP简介&&EL表达式&& JSTL
JSP简介&&EL表达式&& JSTL
|
Java
strus2中页面的s标签,替换jsp的el和jstl标签
strus2中页面的s标签,替换jsp的el和jstl标签
85 0
strus2中页面的s标签,替换jsp的el和jstl标签
|
存储 Java
Jsp中的EL表达式
Jsp中的EL表达式
110 0
Jsp中的EL表达式
|
开发框架 前端开发 安全
JSP的简化:一文吃透EL表达式(下)
文章目录 1 走进EL表达式 2 关于EL表达式与Bean对象 2.1 什么是Java Bean? 2.2 使用EL表达式输出复杂Bean对象 3 EL表达式的运算 3.1 关系运算 3.2 逻辑运算 3.3 算术运算 3.4 empty运算 3.5 三元运算 3.6 点运算和中括号运算 4 EL表达式的11个隐含对象 4.1 概述 4.2 获取四个特定域中的属性 4.3 pageContext对象的使用 4.4 param、paramValues对象的使用 4.5 header、headerValues对象的使用 4.6 cookie对象的使用 4.7 initParam对象的使用
JSP的简化:一文吃透EL表达式(下)
|
设计模式 JavaScript Java
JSP的简化:一文吃透EL表达式(上)
文章目录 1 走进EL表达式 2 关于EL表达式与Bean对象 2.1 什么是Java Bean? 2.2 使用EL表达式输出复杂Bean对象 3 EL表达式的运算 3.1 关系运算 3.2 逻辑运算 3.3 算术运算 3.4 empty运算 3.5 三元运算 3.6 点运算和中括号运算 4 EL表达式的11个隐含对象 4.1 概述 4.2 获取四个特定域中的属性 4.3 pageContext对象的使用 4.4 param、paramValues对象的使用 4.5 header、headerValues对象的使用 4.6 cookie对象的使用 4.7 initParam对象的使用
JSP的简化:一文吃透EL表达式(上)