JSP总结四(EL表达式)

来源:互联网 发布:raptor编程1到100之和 编辑:程序博客网 时间:2024/06/18 17:14

JSP总结四(EL表达式)

简介

JSP页面尽量不要使用scriptlet编写java代码,因此我们可以使用EL表达式可以替代Java语句的使用

隐含对象

与属性相关的隐含对象

属性的隐含对象有PageScope,requestScope,sessionScope,applicationScope分别对应的是JSP中的PageContext,request,session,application,因此可以取得JSP对象使用setAttribute()设置的属性,如果没有使用EL隐含对象获取属性的值,那么默认是从PageScope开始寻找

    <%        request.setAttribute("login",'true');   //绑定request对象的属性        session.setAttribute("login",'true');   //绑定session对象的属性        application.setAttribute("login","true");  //设置application对象的属性    %>    <%--获取request绑定的属性值  相当于request.getAttribute("login");--%>    <h1>${requestScope.login}<h1>    <%--获取session绑定的属性值--%>    <h1>${sessionScope.login}<h1>

与请求参数相关的隐含对象(param,paramValues)

与请求参数相关的EL隐含对象有param,paramValues。我们可以使用EL表达式可以获取表单提交的请求参数。

下面我们使用表单提交,测试一下

JSP代码(表单提交)

        <form action="demo1.jsp" method="get">            姓名:<input type="text" name="username">            密码:<input type="password" name="password">            <input type="submit" value="提交">            爱好:            打棒球:<input type="checkbox" name="hobbies">            打羽毛球:<input type="checkbox" name="hobbies">        </form>

demo1.jsp 文件(接收请求参数)

        <%--获取提交的请求参数username,password             相当于使用如下代码:                request.getParameter("username");                request.getParameter("password");        --%>        <h1>${param.username}</h1>        <h1>${param.password}</h1>        <%--获取多选框的值  相当于使用下面的代码:            request.getParameterValues("hobbies")[0]        --%>        <h1>${paramValues.hobbies[0]}</h1>        <h1>${paramValues.hobbies[1]}</h1>

与标头(Header)相关的隐含对象

如果想要取得用户请求的表头数据,那么使用header或者headerValues隐含对象。例如使用${header["User-Agent"]} 这个相当于使用<%=request.getHeader("User-Agent")%>HeaderValues对象相当于使用request.getHeaders()

cookie隐含对象

cookie的隐含对象可以取得用户设置的Cookie设置的值。如果在Cookie中设置了username属性,那么可以使用${cookie.username}

初始参数隐含对象

隐含对象initParam可以用来取得web.xml中设置的ServletContext初始参数,也就是在<context-param>中设置的初始参数。例如${initParam.initcount}的作用,相当于<%=ServletContext.getInitParameter("initCount")%>

EL运算符

使用EL运算符直接实现一些算术运算符,逻辑运算符,就如同一般常见的程序语言中的运算

算术运算符

可以直接使用加减乘除 ${1+2},${5/2},${5*3}

逻辑运算符

${true and false}=false,${true and true}=true,${true or false}=true

关系运算符

可以直接在EL表达式比较大小,返回的也是falsetrue,可以用来判断,如下:
${1<2}=false ,${(10*10)>200}=true

    <c:if text="${6>5}">        <c:out value="可以直接使用EL表达式进行比较"></c:out>    </c:if>
原创粉丝点击