從用戶角度看,JSP 就是一個網頁。html
從開發者角度看,它其實就是一個繼承了 Servlet 的 java 類,因此能夠直接說 JSP 就是一個 Servlet。java
HTML 一般狀況下用來顯示一成不變的靜態內容,但實際上大部分咱們須要的網頁上是須要顯示一些靜態數據的,這些動做都涉及到了邏輯處理,這些都須要代碼輔助完成。web
HTML 中是不支持寫 java 代碼的,而JSP 裏面能夠寫 java 代碼。express
查看 JSP 翻譯後的文件示例:apache
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.92 * Generated at: 2019-01-04 07:39:33 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.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\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write(" <title>Title</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("<h1>hhhh</h1>\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="page.jsp" %>
將指定 JSP 文件包含到當前 JSP。數組
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>page1</title> </head> <body> <% String str = "hello";%> <%=str%> <h1>這是 page1 的內容</h1> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>page2</title> </head> <body> <%@include file="page1.jsp" %> <h1>這是 page2 的內容</h1> </body> </html>
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.92 * Generated at: 2019-01-04 08:25:20 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class page2_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; static { _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1); _jspx_dependants.put("/page1.jsp", Long.valueOf(1546590314039L)); } private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.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\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write(" <title>page2</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write(" <title>page1</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); String str = "hello"; out.write('\r'); out.write('\n'); out.print(str); out.write("\r\n"); out.write("<h1>這是 page1 的內容</h1>\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n"); out.write("\r\n"); out.write("<h1>這是 page2 的內容</h1>\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
<%@ taglib prefix="" uri="" %>
<jsp:include page="page1.jsp"></jsp:include>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>page1</title> </head> <body> <% String str = "hello";%> <h1>這是 page1 的內容</h1> <%=str%> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>page2</title> </head> <body> <jsp:include page="page1.jsp"></jsp:include> <h1>這是 page2 的內容</h1> </body> </html>
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.92 * Generated at: 2019-01-04 08:49:08 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class page2_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.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\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write(" <title>page2</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "page1.jsp", out, false); out.write("\r\n"); out.write("<h1>這是 page2 的內容</h1>\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
<jsp:forward page="page2.jsp"></jsp:forward>
請求轉發功能。瀏覽器
至關於執行以下代碼:tomcat
request.getRequestDispatcher("page2.jsp").forward(request, response);
還能夠搭配 param 標籤傳遞參數:cookie
<jsp:forward page="page2.jsp"> <jsp:param name="name" value="zhangsan"></jsp:param> <jsp:param name="age" value="20"></jsp:param> </jsp:forward>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>page1</title> </head> <body> <jsp:forward page="page2.jsp"> <jsp:param name="name" value="zhangsan"></jsp:param> <jsp:param name="age" value="20"></jsp:param> </jsp:forward> <h1>這是 page1 的內容</h1> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>page2</title> </head> <body> <h1>這是 page2 的內容</h1> <hr> <% String name = request.getParameter("name"); Integer age = Integer.parseInt(request.getParameter("age")); %> name:<%=name%> <br> age:<%=age%> </body> </html>
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.92 * Generated at: 2019-01-04 09:18:25 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class page1_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.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\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write(" <title>page1</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\r\n"); if (true) { _jspx_page_context.forward("page2.jsp" + "?" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("name", request.getCharacterEncoding())+ "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("zhangsan", request.getCharacterEncoding()) + "&" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("age", request.getCharacterEncoding())+ "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("20", request.getCharacterEncoding())); return; } out.write("\r\n"); out.write("<h1>這是 page1 的內容</h1>\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
所謂內置對象,就是咱們能夠直接在 JSP 中使用的已經建立好的對象,有九個以下:session
<%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" language="java" %> <html> <head> <title>Title</title> </head> <body> <% out.write("這是 out 輸出的內容"); %> <% response.getWriter().write("這是 response.getWriter() 輸出的內容"); %> </body> </html>
能夠看到在代碼中 response.getWriter() 是後輸出的,可是實際訪問時它倒是先輸出的。這是由於 out 對象輸出的內容會放到 response 的緩衝區中, response.getWriter() 的內容輸出後纔會接着輸出 out 對象輸出的內容。而經過查看 JSP 對應 java 代碼咱們知道,JSP 頁面內容就是使用 out 對象輸出的,因此得出結論:當咱們在 JSP 中使用 response.getWriter() 輸出內容時,在瀏覽器渲染後 response.getWriter() 輸出的內容會出如今頁面的最頂部。
EL 表達式能夠幫助咱們簡化 JSP 中的 java代碼。
<%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" language="java" %> <html> <head> <title>Title</title> </head> <body> <% pageContext.setAttribute("str", "from pageContext"); request.setAttribute("str", "from request"); session.setAttribute("str", "from session"); application.setAttribute("str", "from application"); %> ${pageScope.str} <br> ${requestScope.str} <br> ${sessionScope.str} <br> ${applicationScope.str} <br> <%--在 el 表達式中不指定 scope 直接使用 name,會依次在 pageContext->request->session->application --%> ${str} </body> </html>
<%@ page import="java.util.List" %> <%@ page import="java.util.ArrayList" %> <%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" language="java" %> <html> <head> <title>Title</title> </head> <body> <% String[] array = {"a", "b", "c", "d"}; pageContext.setAttribute("array", array); List list = new ArrayList(); list.add(11); list.add(22); list.add(33); list.add(44); pageContext.setAttribute("list", list); %> ${array[0]},${array[1]},${array[2]},${array[3]} <hr/> ${list[0]},${list[1]},${list[2]},${list[3]} </body> </html>
<%@ page import="java.util.HashMap" %> <%@ page import="java.util.Map" %> <%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" language="java" %> <html> <head> <title>Title</title> </head> <body> <% String[] array = {"aa", "bb"}; Map map = new HashMap(); map.put("name1", "zhangsan"); map.put("name2", "lisi"); map.put("name3", "wangwu"); map.put("name4", "zhaoliu"); pageContext.setAttribute("map", map); %> ${map["name1"]},${map["name2"]},${map.name3},${map.name4} </body> </html>
package com.zze.bean; public class User { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
<%@ page import="com.zze.bean.User" %> <%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" language="java" %> <html> <head> <title>Title</title> </head> <body> <% User user = new User(); user.setName("張三"); user.setAge(18); pageContext.setAttribute("user", user); %> 姓名:${pageScope.user.name} <br> 年齡:${user.age} </body> </html>
隱式對象即在 EL 表達式中能直接使用的對象,有 11 個以下:
JSTL 是一個不斷完善的開放源代碼的 JSP 標籤庫。
它的做用是簡化 JSP 中代碼中 java 代碼的編寫,即替換 <% %> 寫法,通常與 EL 表達式配合使用。
一、 導包: jstl.jar、standard.jar 。
二、在 JSP 中使用 taglib 指令引入標籤庫。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>set</title> </head> <body> <%-- 參數: var:名稱 value:值 scope:默認爲 page ,還有 request、session、application 選項 爲 page 時,至關於 <% pageContext.setAttribute("名稱","值"); %> 爲 request 時,至關於 <% request.setAttribute("名稱","值"); %> 爲 session 時,至關於 <% session.setAttribute("名稱","值"); %> 爲 application 時,至關於 <% application.setAttribute("名稱","值"); %> --%> <c:set var="age" value="18" scope="page"></c:set> ${age} </body> </html>
簡單的 if 條件判斷。
<%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>if</title> </head> <body> <c:set var="age" value="18" scope="page"></c:set> <%-- 參數: test:條件表達式 var:指定變量接收條件表達式結果 scope:標識條件表達式中的變量從哪一個域中取 下面代碼至關於: --%> <% Integer age = Integer.parseInt(pageContext.getAttribute("age").toString()); boolean flag = age >= 18; pageContext.setAttribute("flag", flag); if (flag) { %> 成年人 <% } %> <c:if test="${age>=18}" var="flag" scope="page"> 成年人 </c:if> ${flag}
<%@ page import="com.zze.bean.User" %> <%@ page import="java.util.ArrayList" %> <%@ page import="java.util.List" %> <%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>forEach</title> </head> <body> <%-- for 循環 參數: begin:起始數字 end:結束數字 var:定義一個變量代指當前遍歷對象 step:增幅 --%> <c:forEach begin="1" end="10" var="item" step="2"> ${item} </c:forEach> <% List<User> userList = new ArrayList<User>(); userList.add(new User("張三", 18)); userList.add(new User("李四", 19)); userList.add(new User("王五", 20)); pageContext.setAttribute("userList", userList); %> <hr> <%-- foreach 循環 參數: begin:起始下標從 0 開始 end:結束下標 step:下標增幅 var:定義一個變量代指當前遍歷對象 items:指定要遍歷的可迭代對象 varStatus:定義一個保存了當前遍歷信息的對象,有以下屬性: begin:當前遍歷的起始下標從 0 開始 end:當前遍歷的結束下標 step:當前遍歷的下標增幅 count:當前遍歷的是第幾個,從 1 開始 current:代指當前遍歷對象,和 var 定義的變量指向同一個地址 first:當前遍歷對象是不是第一個 last:當前遍歷對象是不是最後一個 index:當前遍歷對象的下標 --%> <c:forEach begin="0" end="${userList.size()}" step="2" var="user" items="${userList}" varStatus="s"> user.name:${user.name},user.age:${user.age},s.step:${s.step},s.begin:${s.begin},s.end:${s.end},s.count:${s.count},s.current:${s.current},s.current == user:${s.current == user},s.first:${s.first},s.last:${s.last}<br> </c:forEach> </body> </html>
一、建立一個標籤處理類,該類須要繼承 SimpleTagSupport 類,重寫 doTag 方法:
package com.zze.tag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; public class HelloTag extends SimpleTagSupport { @Override public void doTag() throws JspException, IOException { getJspContext().getOut().print("<h1>Hello My Tag!!!</h1>"); } }
二、在 WEB-INF 下建立標籤庫配置文件:
<?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"> <description>tag created by zze</description> <tlib-version>1.0</tlib-version> <short-name>myTag</short-name> <!--標籤庫惟一標識--> <uri>zze.test</uri> <tag> <description>Outputs Hello</description> <!--標籤名稱--> <name>helloTag</name> <tag-class>com.zze.tag.HelloTag</tag-class> <body-content>empty</body-content> </tag> </taglib>
三、在 jsp 中使用:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="mytag" uri="zze.test"%> <html> <head> <title>自定義標籤庫測試</title> </head> <body> <mytag:helloTag/> </body> </html>
一、建立一個標籤處理類,聲明一個屬性並給它 setter ,重寫 doTag 方法:
package com.zze.tag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; import java.util.HashMap; public class TableTag extends SimpleTagSupport { private String map; public void setMap(String map) { this.map = map; } @Override public void doTag() throws JspException, IOException { HashMap<String, Integer> maps = (HashMap<String, Integer>) (getJspContext().getAttribute(map)); Object[] array = maps.keySet().toArray(); for (String str : maps.keySet()) { getJspContext().getOut().write("<tr>"); getJspContext().getOut().write("<td>"); getJspContext().getOut().write(str); getJspContext().getOut().write("</td>"); getJspContext().getOut().write("<td>"); getJspContext().getOut().write("" + maps.get(str)); getJspContext().getOut().write("</td>"); getJspContext().getOut().write("</tr>"); } } }
二、在 WEB-INF 下建立標籤庫配置文件:
<?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"> <description>tag created by zze</description> <tlib-version>1.0</tlib-version> <short-name>myTag</short-name> <uri>zze.test</uri> <tag> <name>tr</name> <tag-class>com.zze.tag.TableTag</tag-class> <body-content>empty</body-content> <attribute> <!--聲明一個屬性--> <name>map</name> <required>true</required> <fragment>true</fragment> </attribute> </tag> </taglib>
三、在 jsp 中使用:
<%@ page import="java.util.HashMap" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="mytag" uri="zze.test" %> <html> <head> <title>自定義標籤庫測試</title> </head> <body> <% HashMap<String, Integer> maps = new HashMap<String, Integer>(); maps.put("張三", 18); maps.put("李四", 23); maps.put("王五", 23); pageContext.setAttribute("map", maps); %> <table border="1"> <mytag:tr map="map"/> </table> </body> </html>