所谓JSTL就是标签库  JSP Standard Tag Library,如果做为java初学者你看不懂那些$符号的话,就有必要来了解一下JSTL,如果你看到满眼的<%}%>(Scriptlet)觉得很糟心的话,那就更应该学学JSTL。

  代码分离一直是程序员所追求,框架的开发者每天都费尽心思想怎么实现页面和代码分离,分离的好处比如:代码清晰,美工和程序员不干扰,各做各的等。如果满眼的<%%>就是满眼的Java代码,那就又都整合到一起了。而且将代码嵌入页面,系统编译运行时,很费时的,需要将页面中的代码转换(HTML——JAVA),返回数据时还需转换(JAVA——HTML),而且如果管理不善,很容易出事故的,所以尽量使用JSTL就能提供一种善意的限制,况且用JSTL还可以有效地提高系统速度了。特别是对于那些前台开发人员,他们可能不懂Java,只是懂一些HTML和JSTL,那么就可以做出漂亮美观的页面,也不会受java或其他语言的的困扰了,维护起来也比较简单,这样页面和代码分离了,角色分配也就更明显了,整个团队的合作也就更融洽了。就比如说我吧,刚学java,对java不是很熟悉,现在无意间被调到大系统里做界面,只要我学习了标签语言,就能很容易的将那些后台程序员的结果显示在我的页面上,所有我们就更有必要学习标签库了。

 
  简介:
    迭代和条件判断
    数据管理格式化
    XML操作
    数据库访问
    函数标签库
    表达式语言EL
   
  在学习JSTL之前要了解一下EL,它和标签库联合使用,就能避免在jsp里面出现大段的java代码段了。
  EL主要用于查找作用域中的数据,然后对它们执行简单操作;它不是编程语言,甚至不是脚本编制语言。通常与 JSTL 标记一起作用,能用简单而又方便的符号来表示复杂的行为。EL的格式就是一个美元符号加一对大括号---${}。
      如果只是使用EL表达式,不需要引用任何jar包。只要jsp/servlet容器实现了相关规范就可以了。
  下面是EL的举例应用:
  jstl_el.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>

<%
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="<%=basePath%>"> <title>My JSP 'jstl_el.jsp' starting page</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="styles.css">
--> </head> <body>
<h1>测试EL表达式</h1>
<hr>
<ul>
<li>普通字符串</li>
hello(jsp脚本):<%=request.getAttribute("hello") %> <br>
hellp(EL表达式:语法$和{}):${hello }<br>
hello(EL的内置对象:pageScope,requestScope,sessionScope,applicationScope)<br>
如果不指定范围,它的搜索顺序为:pageScope---applicationScope<br>
--------------举例---------------- <br>
${requestScope.hello } <br>
--------------------------------- <br>
hellp(EL表达式:指定范围从session中取得):值为“${sessionScope.hello } ”<br>
***************************************************************************
<P>
<li>结构--->采用.进行导航,称为存取器</li><br>
姓名:${user.name } --->规范是:name 前加get,name首写字母大写也就是调getName()方法<br>
年龄:${user.age }<br>
所属组:${user.group.name }<br>
***************************************************************************
<p>
<li>map--->采用.进行导航,称为存取器</li><br>
map.key1:${map.key1 } <br>
map.key2:${map.key2 } <br>
***************************************************************************
<p>
<li>字符串数组:------>采用[]下标</li> <br>
strArray[0]:${str_array[0]} <br>
strArray[1]:${str_array[1]} <br>
strArray[2]:${str_array[2]} <br>
strArray[3]:${str_array[3]} <br>
strArray[4]:${str_array[4]} <br>
****************************************************************************
<p>
<li>对象数组:------>采用[]下标</li>
users[0]:${users[0].name } <br>
users[1]:${users[1].name } <br>
users[2]:${users[2].name } <br>
users[3]:${users[3].name } <br>
users[4]:${users[4].name } <br>
****************************************************************************
<p>
<li>list:------>采用[]下标</li>
groupList[0].name:${groupList[0].name }<br>
groupList[1].name:${groupList[1].name }<br>
groupList[2].name:${groupList[2].name }<br>
groupList[3].name:${groupList[3].name }<br>
groupList[4].name:${groupList[4].name }<br>
****************************************************************************
<p>
<li>EL表达式对运算符的支持</li>
143+454=${143+454 }<br>
150 div 30=${150 div 30 }
****************************************************************************
<p>
<li>测试empty</li>
tgb6:${empty tgb6 }<br>
tgb7:${empty tgb7 }<br>
tgb8:${empty tgb8 }<br>
tgb9:${empty tgb9 }<br> </ul>
</body>
</html>
JstlElServlet.java
package com.tgb.jstl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.sun.org.apache.bcel.internal.generic.NEW; /**
* 测试EL表达式
* @author 巨亚红
* @date 2014-1-7 下午6:26:20
* @版本 V1.0 作者: 时间: 修改:
*/
public class JstlElServlet extends HttpServlet { /**
* Constructor of the object.
*/
public JstlElServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//普通字符串
request.setAttribute("hello", "hello world"); //结构
Group group=new Group();
group.setName("提高班八期"); User user=new User();
user.setName("juyahong");
user.setAge(25);
user.setGroup(group);
request.setAttribute("user", user); //map
Map map=new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
request.setAttribute("map", map); //字符串数组
String[] strArray=new String[]{"六期","七期","八期","九期","十期"};
request.setAttribute("str_array", strArray); //对象数组
User[] users=new User[5];
for (int i = 0; i < users.length; i++) {
users[i]=new User();
users[i].setName("juyahong("+i+")");
}
request.setAttribute("users", users); //list
List groupList=new ArrayList();
for (int i = 6; i < 12; i++) {
Group group2=new Group();
group2.setName("提高班第"+i+"期");
groupList.add(group2);
}
request.setAttribute("groupList", groupList); //empty
request.setAttribute("tgb6", "");
request.setAttribute("tgb7", new ArrayList());
request.setAttribute("tgb8", "提高班第八期");
request.setAttribute("tgb9", null);
//request的分发器
request.getRequestDispatcher("/jstl_el.jsp").forward(request, response); } /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

Group.java

package com.tgb.jstl;

public class Group {
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} }

User.java

package com.tgb.jstl;

public class User {
private String name;
private int age;
private Group group;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
} }

web.xml  建立映射

 <servlet>
<servlet-name>JstlElServlet</servlet-name>
<servlet-class>com.tgb.jstl.JstlElServlet</servlet-class>
</servlet>
<!-- 映射到servlet -->
<servlet-mapping>
<servlet-name>JstlElServlet</servlet-name>
<url-pattern>/servlet/JstlElServlet</url-pattern>
</servlet-mapping>

效果:

  

  

    EL表达式非常简单,只是一个${}就解决了,但是它的功能却非常单一,只能取得特定的某一个元素。如果想要遍历就不行了,再加上一些条件分支判断什么的也不行,也无法做到日期、数字等的格式化。所以要结合相应的标签来达到这样的效果。
     那么我们就需要一个标签库即JSTL。但是需要引入它的库,将jstl.jar和standard.jar考到WEB-INF/lib下,然后采用tablib指令引入标签库。
  <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c" %>
  
  下面代码举例应用:
  

  jstl_core.jsp
<%@page import="javax.servlet.jsp.tagext.TryCatchFinally"%>
<%@page import="com.tgb.jstl.User"%>
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%
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="<%=basePath%>"> <title>My JSP 'jstl_core.jsp' starting page</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="styles.css">
--> </head> <body>
<h1>测试JSTL标签库</h1>
<ul>
<li>采用 c:out 标签</li>
hello(使用标签):<c:out value="123"></c:out> <br>
hello(使用标签,结合EL表达式):<c:out value="${hello }"></c:out><br>
hello(使用EL表达式):${hello }<br>
hello(使用EL表达式,default):${hello123 }<br>
hello(使用标签,结合EL表达式,缺省值):<c:out value="${hello123 }" default="hello123"></c:out><br>
hello(使用标签,结合EL表达式,缺省值):<c:out value="${hello123 }" >hello123</c:out><br>
welcome(使用EL表达式):${welcome } <br>
welcome(使用标签,escapeXml=true,EL表达式):<c:out value="${welcome }" escapeXml="true"></c:out> <br>
welcome(使用标签,escapeXml=false,EL表达式):<c:out value="${welcome }" escapeXml="false"></c:out> <br>
*********************************************
<li>测试c:set 和 c:remove</li>
<c:set value="juyahong" var="userId"></c:set><br>
userId:--->${userId } <br>
<c:remove var="userId"/> <br>
userId:--->${userId } <br>
*********************************************
<li>条件控制标签:--->c:if</li>
<c:if test="${v1 lt v2 }">
v1 小于v2 <br>
</c:if> *********************************************
<li>条件控制标签:c:choose,c:when,c:otherwise</li>
<c:choose>
<c:when test="${v1 gt v2 }">
v1大于v2<br>
</c:when>
<c:otherwise>
v1小于v2<br>
</c:otherwise>
</c:choose> <c:choose> <c:when test="${empty userList }">
没有符合条件的数据<br>
</c:when>
<c:otherwise>
存在用户数据<br>
</c:otherwise>
</c:choose>
*********************************************
<li>循环控制标签:--->c:forEach</li>
<h3>采用jsp脚本显示</h3> <table border="1px">
<tr>
<td>用户姓名</td>
<td>用户年龄</td>
<td>所属组</td>
</tr>
<%
List userList=(List)request.getAttribute("users");
if(userList == null || userList.size()==0){
%>
<tr>
<td colspan="3">没有符合条件的数据</td>
</tr>
<%
}else {
for(Iterator iter=userList.iterator();iter.hasNext();){
User user=(User)iter.next();
%>
<tr>
<td><%=user.getName() %></td>
<td><%=user.getAge() %></td>
<td><%=user.getGroup().getName() %></td>
</tr> <%
}
}
%>
</table>
<h3>采用c:forEach 标签</h3>
<table border="1px">
<tr>
<td>用户姓名</td>
<td>用户年龄</td>
<td>所属组</td>
</tr>
<c:choose>
<c:when test="${empty users }">
<tr>
<td colspan="3">没有符合条件的数据</td>
</tr>
</c:when>
<c:otherwise>
<c:forEach items="${users }" var="user">
<tr>
<td>${user.name }</td>
<td>${user.age }</td>
<td>${user.group.name }</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</table>
<h3>采用c:forEach ,varstatus</h3>
<table border="1px">
<tr>
<td>用户姓名</td>
<td>用户年龄</td>
<td>所属组</td>
</tr>
<c:choose>
<c:when test="${empty users }">
<tr>
<td colspan="3">没有符合条件的数据</td>
</tr>
</c:when>
<c:otherwise>
<c:forEach items="${users }" var="user" varStatus="vs">
<c:choose>
<c:when test="${vs.count mod 2==0 }">
<tr bgcolor="red">
</c:when>
<c:otherwise>
<tr>
</c:otherwise>
</c:choose>
<td>${user.name }</td>
<td>${user.age }</td>
<td>${user.group.name }</td>
</tr>
</c:forEach> </c:otherwise>
</c:choose>
</table>
<li>循环控制标签forEach:输出map</li>
<c:forEach items="${map }" var="entry">
${entry.key } ,${entry.value } <br>
</c:forEach>
<li>循环控制标签forTokens</li>
<c:forTokens items="${strTokens} " delims="#" var="v">
${v } <br>
</c:forTokens>
<li>c:catch标签</li>
<p>
<%
try{
Integer.parseInt("ahkjdhfjk");
} catch(Exception e){
out.println(e.getMessage());
}
%>
</p>
<P>
<c:catch var="msg">
<%
Integer.parseInt("ahkjdhfjk");
%>
</c:catch>
${msg }
</P> </ul>
</body>
</html>
JstlCoreServlet.java
package com.tgb.jstl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 演示JSTL核心库
* @author 巨亚红
* @date 2014-1-7 下午9:19:15
* @版本 V1.0 作者: 时间: 修改:
*/
public class JstlCoreServlet extends HttpServlet { /**
* @author 巨亚红
* @date 2014-1-8 下午5:36:05
* @版本 V1.0 作者: 时间: 修改:
*/
private static final long serialVersionUID = 1L;
/**
* Constructor of the object.
*/
public JstlCoreServlet() {
super();
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { // 普通字符串
request.setAttribute("hello", "hello world"); //HTML字符串
request.setAttribute("welcome", "<font color='red'>欢迎你来到这个世界</font>"); //条件控制标签
request.setAttribute("v1", 10);
request.setAttribute("v2", 20); request.setAttribute("userList", new ArrayList()); //结构 Group group = new Group();
group.setName("提高班第八期"); List users = new ArrayList();
for (int i=0; i<10; i++) {
User user = new User();
user.setName("juyahong(" + i+")");
user.setAge(23 + i);
user.setGroup(group);
users.add(user);
}
request.setAttribute("users", users); //map
Map map=new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");
request.setAttribute("map", map); //forTokens
request.setAttribute("strTokens", "1#2#3#4#5"); request.getRequestDispatcher("/jstl_core.jsp").forward(request, response); } }

web.xml

 <servlet>
<servlet-name>JstlCoreServlet</servlet-name>
<servlet-class>com.tgb.jstl.JstlCoreServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JstlCoreServlet</servlet-name>
<url-pattern>/servlet/JstlCoreServlet</url-pattern>
</servlet-mapping>

效果图:

  

  通过上面的例子,JSTL也学习到了大部分了,希望以后的项目中多多运用,多多学习。

Java初学者必学的JSTL的更多相关文章

  1. java开发必学知识:动态代理

    目录 1. 引言 2. 代理模式及静态代理 2.1 代理模式说明 2.2 静态代理 2.3 静态代理局限性 3. 动态代理 3.1 JAVA反射机制 3.2 JDK动态代理 3.2.1 JDK动态代理 ...

  2. java初学者必看之构造方法详细解读

    java初学者必看之构造方法详细解读 构造方法是专门用来创建对象的方法,当我们通过关键字new来创建对象时,其实就是在调用构造方法. 格式 public 类名称(参数类型 参数名称){ 方法体 } 注 ...

  3. Java初学者必知 关于Java字符串问题

    摘自 http://developer.51cto.com/art/201503/469443.htm 下面我为大家总结了10条Java开发者经常会提的关于Java字符串的问题,如果你也是Java初学 ...

  4. JAVA工程师必学技能,进阶&涨薪的推进器!这份实战教程请收下

    Netty 作为互联网中间件的基石,是 JAVA 工程师进阶为高级程序员必备的能力之一.也是目前是互联网中间件领域使用最广泛最核心的网络通信框架. Netty是一个高性能.异步事件驱动的NIO框架,它 ...

  5. java初学者必看的学习路线

    不管在编程语言的排行榜中,还是在大多数企业应用的广泛程度来看,Java一直都是当之无愧的榜首.Java语言有着独特的魅力吸引着广大的年轻人去学习,每个人学习的方式方法不一样. 第一步:首先要做好学习前 ...

  6. java初学者必看经典

    配置java环境变量: JAVA_HOME:配置JDK的目录 CLASSPATH:指定到哪里去找运行时需要用到的类代码(字节码) PATH:指定可执行程序的位置 LINUX系统(在" .ba ...

  7. java数据库学习路线和必学知识点!

    java数据库必学知识点! 分享一下数据库的学习路线和必学的知识点! 掌握mysql,Oracle在各个平台上的安装及使用 Mysql数据库基础 mysql概述.优点.运行原理及内存结构 mysql数 ...

  8. Java必学MySQL数据库应用场景

    Java教程分享Java必学之MySQL数据库应用场景,在当前的后台开发中,MySQL应用非常普遍,企业在选拔Java人才时也会考察求职者诸如性能优化.高可用性.备份.集群.负载均衡.读写分离等问题. ...

  9. Java初学者应该注意的学习问题

    作为初学者,在刚开始学习的时候,一定会走很多弯路.但其实很多弯路是不必走的,会浪费很多时间,导致学习效率大打折扣.今天小编给大家讲述一下,作为一个Java初学者,在开始学习的时候应该注意的问题,应该从 ...

随机推荐

  1. asp.net mvc之TempData、ViewData、ViewBag

    ★ViewData和ViewBag:生命周期相同,仅对当前View有效,不同的是ViewBag的类型不是字典的键值对结构,而是dynamic动态类型. ViewData ViewBag Key/Val ...

  2. 手记:配置IIS服务器,支持sis、SISX、3GP、ADP、AMR、JAD、JAR、MMF、MFM、PMD、UMD等文件下载

    发此博文原因是遇到一个 手机端读取服务器端.amr格式文件失败的例子.   反复测试发现从服务端无法播放,或下载.amr格式的文件.就想到可能是服务器站点托管服务 IIS不支持对.amr格式的解析,意 ...

  3. ADO.NET 实体数据模型 异常-“序列化类型为 XX 的对象时检测到循环引用”

    发生异常的代码如下: 1: public JsonResult GetSaleByNo1(string id) 2: { 3: SaleMvcUI.Helper.saleDBEntities sale ...

  4. MFC工程说明readme

    ======================================================================== MICROSOFT FOUNDATION CLASS ...

  5. .net将枚举转成List

    using System; using System.Collections.Generic; using System.ComponentModel; namespace zifar.SgmhWeb ...

  6. java基础篇---I/O技术(二)

    接着上篇http://www.cnblogs.com/oumyye/p/4314412.html java I/O流---内存操作流 ByteArrayInputStream和ByteArrayOut ...

  7. Android——Activity去除标题栏和状态栏

    一.在代码中设置 public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  //去 ...

  8. strace命令用法详解

    Linux利器 strace strace常用来跟踪进程执行时的系统调用和所接收的信号. 在Linux世界,进程不能直接访问硬件设备,当进程需要访问硬件设备(比如读取磁盘文件,接收网络数据等等)时,必 ...

  9. Android学习记录一——安装环境

    一直想接触这块,但是却一直耽搁到现在.找过几回资料,找过几回安装包,这两天受了些刺(gong)激(zi),决定静下心来,一点点开始吃. 接触c#都是从门外汉开始,谈不上任何编程基础,所以接触andro ...

  10. SERVER2012 FTP服务器和客户端配置

    SERVER2012 用IIS8 搭建的FTP 默认是主动模式的,导致花了一些时间去研究如何连接,总结了一下配置,希望能帮到需要的同学,以下介绍下步骤 1.服务器--计算机管理-用户-新建用户--默认 ...