您的位置:首页 > Web前端 > JavaScript

day16-EL&JSTL

2017-09-18 18:37 260 查看
EL表达式

JSTL

EL表达式:

什么是EL:简化JSP的写法.减少<%  %> .

 

使用EL表达式:

* 语法:${ EL表达式
}

 

EL的功能:

* 获取数据:(是放在JSP的四个域中的)

* 执行运算:

* 操作WEB开发的常用的对象:

* 调用Java中方法:--很少用.

 

【EL获取数据】

<% //pageContext.setAttribute("name", "pValue");  %>

 

<%=pageContext.getAttribute("name")%><!-- 如果没找到返回null -->

${ pageScope.name }
<!-- 返回的是"" -->不显示在页面上

${ name } <!-- 类似findAttribute("name")先从page域中查找,没找到去request域中查询,没有找到去session域中找,没有找到就去application域中找
-->

${ arrs[0] }      获取数组的数据

${ list[0] }           获取List集合的数据

${ map.aaa }           获取Map集合的数据

${ user.id }            获取对象的数据(前提是类中有setget方法)

 

User user1 = newUser(1,"aaa","123");

List<User> userList = newArrayList<User>();

userList.add(user1);

获取对象的集合的数据

${ userList[0].id } -${ userList[0].username } - ${ userList[0].password }

 

*****点 .和[]的区别. 

    * []用于有下标的数据(数组,list集合) .用于有属性的数据(map,对象)

* 如果属性名中包含有特殊的字符.必须使用[]

点出来的都是有get方法的

 

map.put("ddd.eee","李凤");

${ map[“ddd.eee”]}

又例如头数据的获取 ,
常含特殊符号

 

对象中嵌套对象的情形:

User类中的成员变量中嵌套UserDtail类的对象,UserDtail中有age成员:



 网页中的jsp可以写为: ${ user.ud.age }

【EL执行运算】

<%
         pageContext.setAttribute("n1",
"10");
         pageContext.setAttribute("n2",
"20");
         pageContext.setAttribute("n3",
"30");
         pageContext.setAttribute("n4",
"40");
%>
<h3>EL执行算数运算</h3>
${ n1 + n2 + n3 }
<h3>EL执行逻辑运算</h3>唯一有用的
${ n1 < n2 } -${ n1 lt
n2 } <!-- less than--><br/>
${ n1 > n2 } - ${ n1 gt
n2 } <!-- great than --><br/>
${ n1 <= n2 } - ${ n1 le
n2 } <!-- less equal --><br/>
${ n1 >= n2 } - ${ n1 ge
n2 } <!-- great equal --><br/>
${ n1 == n2 } - ${ n1 eq
n2 } <!-- equal --><br/>
 
<h3>EL执行关系运算</h3>
${ n1<n2 && n3 < n4 } - ${ n1<n2 and
n3 < n4 }<br/>
${ n1<n2 || n3 < n4 } - ${ n1<n2 or
n3 < n4 }<br/>
${ !(n1 < n2) } - ${ not(n1<n2) }
 
<h3>EL执行三元运算</h3>
${ n1 < n2 ? "正确":"错误" }
<h3>empty运算</h3>
${ user == null } - ${ empty
user }
${ user != null } - ${ not empty user }

 

【EL操作WEB开发的常用对象11个】

<!--
       pageScope,requestScope,sessionScope,applicationScope-
获取JSP中域中的数据
       param ,paramValues     -
接收参数.
       header,headerValues - 获取请求头信息
       initParam                  -
获取全局初始化参数
       cookie                        - WEB开发中cookie
       pageContext                     - WEB开发中的pageContext.
 -->
 
<h3>接收请求的参数.还有数组参数</h3>
<!-- 传统方式 -->
<%=request.getParameter("id")
%>
<%=request.getParameter("name")
%>
<%=Arrays.toString(request.getParameterValues("hobby"))
%>
<hr/><!-- EL方式 -->
${ param.id }
${ param.name }
${ paramValues.hobby[0] }
${ paramValues.hobby[1] }
 
<h3>获取请求头</h3>
<%=request.getHeader("User-Agent")
%>
<hr/>
${ header["User-Agent"] }
 
<h3>获取全局初始化参数</h3>
${ initParam.username }
 
<h3>获取Cookie中的值</h3>  
用于记住用户名
${cookie.history.value }
 
<h3>获取PageContext中的对象</h3>
IP地址:${ pageContext.request.remoteAddr }显示请求端的IP,也就是自己的IP
工程路径:${ pageContext.request.contextPath }用于替换src中的工程名,但是直接写在src中的话会请求服务器很多次,所以用来定义成局部变量,

例如:

<%
    String  root  =request.getContextPath();
%>
 使用的方法  href= "<%=root
%>/pages/reset.css"

JSTL

 

网页表单绕过前台校验的办法:网页保存到本地,打开本地源码把里面的校验js代码删除掉,保存,然后点开网页就可以绕过前台校验了..所以一般都需要设置前后台的校验才能安全.

 

什么是JSTL:是jsp的标签库.

为什么学习JSTL:

* JSTL和EL结合 替换页面中<%%>

JSTL版本:

* JSTL1.0                    :不支持EL表达式.

* JSTL1.1 和 1.2         :支持EL表达式.

 

JSTL的标签库:包含了五类标签.

* core(核心标签), fn(JSTL提供EL函数库),fmt(国际化标签),xml(XML标签),sql(SQL标签),

 

使用JSTL:

* 引入JSTL的相关的jar包(2个).

standard.jar  .   jstl.jar

* 在页面中引入标签库.<%@ taglib uri=”” prefix=””%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  

【JSTL的核心标签的用法】

* if

* forEach

 

<h1>JSTL的核心标签库:if标签</h1>

<c:set
var="n1"
value="10"scope="page"></c:set>
<c:set
var="n2"value="20"
scope="page"></c:set>
<c:if
test="${ n1 < n2 }"var="flag"
scope="page">
       n1 小于 n2
</c:if>
<c:if
test="${ n1 >= n2 }">
       n1 大于等于 n2
</c:if>
 
<c:if
test="${ flag }">
       n1 小于 n2
</c:if>

 

JSTL与El混搭(用于用户登录):

<c:if
test="${user.name !='' }">
欢迎您${user.name }
</c:if>
<c:if
test="${user.name =='' }">
<a
href="">登录</a>
</c:if>

 

 

<h1>JSTL的常用的标签一</h1>
<c:set
var="i"value="张三"
scope="page"></c:set>
${ i }
<c:set
var="city"value="上海"
scope="page"></c:set>
<c:out
value="${ city }"default="北京"></c:out>  city没有值的时候输出北京
<c:out
value="<h1>标题一</h1>"
escapeXml="false"></c:out>     将<>当成标签,设置不转义

<h1>JSTL常用标签:forEach</h1>

<h3>遍历数组</h3>
<%
       String[] arrs = {"李旭华","李冠希","董阳阳"};
       pageContext.setAttribute("arrs", arrs);
%>
<c:forEach
var="i"items="${ arrs }">   items是要遍历的东西
       ${ i }
</c:forEach>
 
<h3>遍历List集合</h3>
<%
       List list = new
ArrayList();
       list.add("李旭华");
       list.add("李冠希");
       list.add("董阳阳");
       pageContext.setAttribute("list", list);
%>
<c:forEach
var="i"items="${ list }">
       ${ i }
</c:forEach>
 
 
<h3>遍历Map集合</h3>
<%
       Map<String,String> map =new HashMap<String,String>();
       map.put("aaa","李旭华");
       map.put("bbb","李冠希");
       map.put("ccc","董阳阳");
       pageContext.setAttribute("map", map);
%>
<c:forEach
var="entry"items="${ map }">
       ${ entry.key }-${ entry.value}
</c:forEach>
 
<h3>遍历从1到10</h3>
<c:forEach
var="i"begin="1" end="10" step="2">  每次加2
       ${ i }
</c:forEach>
 
<h3>遍历从100到300</h3>
<c:forEach
var="i"begin="100"
end="300"step="5"  varStatus="status">
       <c:if
test="${ status.count % 3 == 0 }">  到第三个数的时候  ,count十个数,index是索引
              <font
color="red">${ i }</font>       把字变红
       </c:if>
       <c:if
test="${ status.count % 3 != 0 }">
              ${ i }
       </c:if>
</c:forEach>

【JSTL的提供EL的函数库】

<h1>JSTL提供的EL的函数库</h1>

${ fn:contains("Hello World","Hello")}

${ fn:length("HelloWorld") }

${ fn:toLowerCase("ABCDE") }

<c:forEach var="i" items='${fn:split("a-b-c-d","-") }'>

       ${i }

</c:forEach>

 

 

实现商品列表显示功能:

<body>
<h1>商品列表页面</h1>
<table
border="1"width="100%">
         <tr>
                   <td>商品编号</td>
                   <td>商品名称</td>
                   <td>商品价格</td>
                   <td>是否热门</td>
                   <td>商品描述</td>
         </tr>
         <c:forEach
var="p"items="${list }">
         <tr>
                   <td>${
p.pid }</td>
                   <td>${
p.pname }</td>
                   <td>${
p.shop_price }</td>
                   <td>
                           
<c:if
test="${ p.is_hot == 1 }">
                                    

                           
</c:if>
                           
<c:if
test="${ p.is_hot != 1 }">
                                    

                           
</c:if>
                   </td>
                   <td>${
p.pdesc }</td>
         </tr>      

         </c:forEach>
</table>
</body>

 

public
class
ProductDao {
         publicList<Product> findAll()
throws SQLException {
                   QueryRunnerqueryRunner =
newQueryRunner(JDBCUtils.getDataSource());
                   Stringsql =
"select *from product order by pdate desc";
                   List<Product>list =
queryRunner.query(sql,
newBeanListHandler<Product>(Product.class));
                   return
list;
         }

使用MVC设计模式完成转账的案例:

设计一个页面,输入三个值,一个是付款人,一个是收款人,一个是转账的金额.不能出现付款人的钱被扣除而收款人没有收到钱的情况发生.而且要使用MVC的设计模式.

对设计模式的理解:遇到非技术问题造成的维护不便或者实现过程复杂的时候,对整个代码的实现过程进行思考,到生活实际中的可能相似的事务流程中去寻找模式.



内省:底层是基于反射的,但是只是拿到JavaBean的set和get方法.

前5天实用知识点总结

后台的servlet代码:

package review;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class TestA
*/
public class TestA extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//综合回顾

//前后台交互
//1、前台向后台传递
//request.getParameter("");    获得前台传递的值
扩展前台向后台的数据注入,比如在servlet类中定义一个private TestModel tm;并且生成set方法, 那么如果前台如果传过来的是name为TestModel.name的属性的话,那么这个传递过来的数据就会自动封装到tm中.

//2、后台向前台传递

//单个字符
request.setAttribute("msg", "el表达式获得单个字符");
//存model对象
TestModel tm=new TestModel();
tm.setId(1);
tm.setName("java5");
request.setAttribute("tm", tm);
//数组
List<TestModel> tms=new ArrayList<TestModel>();
tms.add(tm);
tms.add(tm);
request.setAttribute("tms", tms);
//session
request.getSession().setMaxInactiveInterval(60);
request.getSession().setAttribute("session1", "这是session对象");
//cookie
Cookie cookie=new Cookie("cookie1", URLEncoder.encode("这是cookie对象","utf-8"));

//cookie.setPath(uri);
//cookie.setMaxAge(60);
response.addCookie(cookie);
//3、跳转
//response.sendRedirect("/review/index.jsp");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

前台的jsp页面:

<%@page import="java.net.URLDecoder"%>
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
<span style=" font: 20px; color: red">EL表达式 获得单个字符的用法</span><br>
${msg }<br>
<span style=" font: 20px; color: red">EL表达式 获得对象的用法</span><br>
${tm.id}<br>
${tm.name}<br>
<span style=" font: 20px; color: red">EL表达式 获得数组的用法</span><br>
<c:forEach var="tm" items="${tms }">
${tm.id}-----${tm.name}
</c:forEach>
<span style=" font: 20px; color: red">EL表达式 获得session的用法</span><br>
${session1}<br>
<span style=" font: 20px; color: red">EL表达式 获得cookie的用法</span><br>
<%
String info="";
Cookie[] cookies=request.getCookies();
for (Cookie cookie : cookies) {
if("cookie1".equals(cookie.getName())){
info=cookie.getValue();
}
}
info=URLDecoder.decode(info, "utf-8");
request.setAttribute("info", info);
%>
<%=info %><br>
${info }

<span style=" font: 20px; color: red">jstl  if的用法</span><br>
<c:if test="${tm.name== 'java5'}">
hello ${tm.name}
</c:if>
</body>
</html>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: