Java初学者必学的JSTL

  所谓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>

效果:

  Java初学者必学的JSTL

Java初学者必学的JSTL

  

    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>

效果图:

Java初学者必学的JSTL

Java初学者必学的JSTL

  

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

上一篇:Servlet--ServletRequest接口,ServletResponse接口


下一篇:15个初学者必看的基础SQL查询语句