04 jstl标准标签库

本节讲述标准标签库jstl的用法,其主要作用就是用标签代替java代码,当然底层还是java代码。

1、环境约束

  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64
  • servlet3.0

2、前提约束

  • 完成servlet的三种实现方式,假设该项目的名称为为servlet-jstl
  • 在pom.xml中加入依赖
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
  • 在servlet-test/src/main/java文件夹下创建net.wanho.jstl包
  • 在net.wanho.jstl包中创建JSTLServlet.java

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/jstl")
public class JSTLServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<String> list = new ArrayList<>();
        list.add("ali");
        list.add("xiaoli");
        list.add("zhangli");
        req.setAttribute("list", list);
        req.setAttribute("role", "admin");
        req.getRequestDispatcher("jstl.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • 在servlet-test/src/main/webapp文件夹下创建jstl.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<c:forEach items="${list}" var="user">
    <c:out value="${user}"></c:out>
</c:forEach>
<c:if test="${role == 'admin'}">管理员</c:if>
</body>
</html>
  • 启动,浏览器访问 http://localhost:8088/jstl,得到以下界面:
    jstl输出
    以上就是jstl标准标签库的基本用法。
发布了358 篇原创文章 · 获赞 0 · 访问量 2736

猜你喜欢

转载自blog.csdn.net/langli204910/article/details/105277943
今日推荐