Java入门系列13 -- JSP与JSTL

2021-12-10  本文已影响0人  YanZi_33

JSP

在IDEA中关于JSP的配置
image.png image.png image.png image.png
JSP的注释
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>JSP页面</title>
</head>
<body>
   <h2>Hello JSP!!!</h2>

   <!-- HTML注释 -->
   <%-- JSP注释 --%>

   <%-- Java脚本段代码 --%>
   <%
       //单行注释
       /*多行注释*/
   %>
</body>
</html>
Scriptlet
<%--
  Created by IntelliJ IDEA.
  User: ljj
  Date: 2021/12/10
  Time: 下午10:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>脚本小程序</title>
</head>
<body>

  <%-- 第一种:Java脚本段--%>
  <%
      String str = "Hello JSP";
      //输出到控制台
      System.out.println(str);
      //输出到浏览器
      out.print(str);
      out.write("全局变量: " + num);
  %>

  <%-- 第二种:声明--%>
  <%!
      //声明全局变量
      int num = 100;
  %>

  <%-- 第三种:输出表达式--%>
  <%=str%>

</body>
</html>
JSP的指令标签
静态包含
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>头部</title>
</head>
<body>

    <h2>头部内容</h2>

</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>底部</title>
</head>
<body>
    <h2>底部内容</h2>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>静态包含</title>
</head>
<body>

   <%@include file="JSP_header.jsp"%>
   <h2>主体内容</h2>
   <%@include file="JSP_footer.jsp"%>

</body
</html>
动态包含
<jsp:include page="JSP_footer.jsp">
        <jsp:param name="name" value="admin"/>
        <jsp:param name="msg" value="<%=str%>"/>
</jsp:include>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>头部</title>
</head>
<body>

    <h2>头部内容</h2>

</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>底部</title>
</head>
<body>
    <h2>底部内容</h2>
    <!-- 获取JSP05中的参数 -->
    <%
        String name = request.getParameter("name");
        String msg = request.getParameter("msg");
        out.print(name + msg);
    %>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>动态包含</title>
</head>
<body>
    <jsp:include page="JSP_header.jsp"></jsp:include>
    <h2>主体内容</h2>
    <jsp:include page="JSP_footer.jsp"></jsp:include>

    <!-- 定义参数 -->
    <%
        String str = "lisi";
    %>
    <jsp:include page="JSP_footer.jsp">
        <jsp:param name="name" value="admin"/>
        <jsp:param name="msg" value="<%=str%>"/>
    </jsp:include>

</body>
</html>
JSP的四大域对象
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>JSP四大域对象</title>
</head>
<body>

   <%
       //page范围
       pageContext.setAttribute("name1","yanzi");
       //request范围
       request.setAttribute("name2","yanzi");
       //session范围
       session.setAttribute("name3","yanzi");
       //application范围
       application.setAttribute("name4","yanzi");
   %>

   <!-- JSP中服务端跳转 -->
   <%-- <jsp:forward page="JSP07.jsp"></jsp:forward> --%>

   <!--  客户端跳转 超链接跳转 -->
   <a href="JSP07.jsp">跳转</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>获取域对象</title>
</head>
<body>
   <%
       //page范围
       out.println("page范围: " + pageContext.getAttribute("name1") + "<br>");
       //request范围
       out.println("request范围: " + request.getAttribute("name2") + "<br>");
       //seesion范围
       out.println("seesion范围: " + session.getAttribute("name3") + "<br>");
       //application范围
       out.println("application范围: " + application.getAttribute("name4") + "<br>");
   %>
</body>
</html>
利用JSP实现一个简单的用户登录
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
    <form action="loginServlet" method="post">
        姓名: <input type="text" name="name"> <br>
        密码: <input type="password" name="password"> <br>
        <button>登录</button>
        <!-- 获取后台设置在作用域中的数据 -->
        <span style="color: #ff0000;font-size: 12px"><%=request.getAttribute("msg")%></span>
    </form>
</body>
</html>
package com.sf.controller;

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;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //接收客户端的参数
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        if (name == null || "".equals(name.trim())) {
            //提示用户信息
            req.setAttribute("msg","用户名不能为空!!!");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
            return;
        }

        if (password == null || "".equals(password.trim())) {
            //提示用户信息
            req.setAttribute("msg","密码不能为空!!!");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
            return;
        }

        if (!"admin".equals(name) || !"admin".equals(password)) {
            //提示用户信息
            req.setAttribute("msg","登录失败!!!");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
            return;
        }

        //登录成功
        //设置登录信息到session作用域
        req.getSession().setAttribute("name",name);
        //跳转到index.jsp
        resp.sendRedirect("index.jsp");
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
      <h2>欢迎<%=session.getAttribute("name")%>登录!!!</h2>
  </body>
</html>
EL表达式
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL表达式</title>
</head>
<body>

   <%
       pageContext.setAttribute("name","yanzi1");
       request.setAttribute("name","yanzi2");
       session.setAttribute("name","yanzi3");
       application.setAttribute("name","yanzi4");

       //定义局部变量
       String str = "Hello";
   %>

   <!-- 获取数据 -->
   获取局部变量: ${str} <br>
   获取域对象: ${name} <br>
   获取指定范围的域对象: <br>
   &nbsp;&nbsp;page范围: ${pageScope.name} <br>
   &nbsp;&nbsp;request范围: ${requestScope.name} <br>
   &nbsp;&nbsp;session范围: ${sessionScope.name} <br>
   &nbsp;&nbsp;application范围: ${applicationScope.name} <br>

</body>
image.png
EL表达式的基本使用
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="com.sf.bean.User" %><%--
  Created by IntelliJ IDEA.
  User: ljj
  Date: 2021/12/11
  Time: 下午9:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL表达式的基本使用</title>
</head>
<body>
    <!-- List -->
    <%
        //list是限域变量名
        List<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        request.setAttribute("list",list);
        //map是限域变量名
        Map map = new HashMap();
        map.put("aaa","111");
        map.put("bbb","222");
        map.put("ccc","333");
        request.setAttribute("map",map);

        //Java Bean对象
        User user = new User();
        user.setUserId(1000);
        user.setName("yanzi");
        user.setPassword("asd123");
        request.setAttribute("user",user);
    %>
    <h4>获取list</h4>
    获取List的size: ${list.size()} <br>
    获取List的指定下标的值: ${list[1]} <br>
    <h4>获取map</h4>
    获取Map指定key的value值: ${map.aaa} -- ${map.bbb}
    <h4>获取Java Bean</h4>
    获取Java Bean对象: ${user} <br>
    获取Java Bean中的属性: ${user.name} -- ${user.getPassword()}
</body>
</html>
package com.sf.bean;

public class User {
    private Integer userId;
    private String name;
    private String password;

    public User() {

    }

    public User(Integer userId, String name, String password) {
        this.userId = userId;
        this.name = name;
        this.password = password;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
image.png
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="com.sf.bean.User" %><%--
  Created by IntelliJ IDEA.
  User: ljj
  Date: 2021/12/11
  Time: 下午10:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

   <%
       request.setAttribute("str1","aaaa");
       request.setAttribute("str2","");
       request.setAttribute("str3",null);

       List list1 = new ArrayList();
       List list2 = null;
       List list3 = new ArrayList();
       list3.add(1);
       request.setAttribute("list1",list1);
       request.setAttribute("list2",list2);
       request.setAttribute("list3",list3);

       Map map1 = null;
       Map map2 = new HashMap();
       Map map3 = new HashMap();
       map3.put("aaa","111");
       request.setAttribute("map1",map1);
       request.setAttribute("map2",map2);
       request.setAttribute("map3",map3);

       User user1 = null;
       User user2 = new User();
       User user3 = new User();
       user3.setUserId(123);
       request.setAttribute("user1",user1);
       request.setAttribute("user2",user2);
       request.setAttribute("user3",user3);

   %>

   <div>判断字符串是否存在</div>
   ${empty str} <br>
   ${empty str1} <br>
   ${empty st2} <br>
   ${empty str3} <br>
   <hr>
   <div>判断List是否存在</div>
   ${empty list1} <br>
   ${empty list2} <br>
   ${empty list3} <br>
   <hr>
   <div>判断Map是否存在</div>
   ${empty map1} <br>
   ${empty map2} <br>
   ${empty map3} <br>
   <hr>
   <div>判断Java Bean对象是否存在</div>
   ${empty user1} <br>
   ${empty user2} <br>
   ${empty user3} <br>
</body>
</html>
image.png
 Created by IntelliJ IDEA.
  User: ljj
  Date: 2021/12/11
  Time: 下午10:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

   <%
       request.setAttribute("a",10);
       request.setAttribute("b",2);
       request.setAttribute("c","aa");
       request.setAttribute("d","bb");
   %>

   <div>比较两个值是否相等 返回true,false</div>
   ${a == b}
   ${c == d}
   ${c eq d}
   ${a == 5}
   ${c == 'aa'}
   <hr>
   <div>加减乘除</div>
   ${a + b}
   ${a / b}
   ${a - b}
   ${a * b}
   <hr>
   <div>大于,小于</div>
   ${a > b}
   ${a + 1 > 10}
   ${a + b >= 10}
   ${a > b && b > 5}
   ${a + b > 10 || a - b > 5}
</body>
</html>
image.png
JSTL
image.png Snip20211211_66.png image.png image.png
条件动作标签
if标签
<c:if test="${表达式}">
        说明
</c:if> 
<%--
  Created by IntelliJ IDEA.
  User: ljj
  Date: 2021/12/11
  Time: 下午11:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>if标签</title>
</head>
<body>

    <%
        request.setAttribute("num",10);
    %>

    <c:if test="${num > 0}">
        数值大于0
    </c:if> 
    <c:if test="${num <= 0}">
        数值不大于0
    </c:if>
    <c:if test="${num > 100}" var="flag" scope="request"></c:if>
    ${flag} -- ${requestScope.flage}

</body>
</html>
choose,when与otherwise标签
<c:choose>
         <c:when test="${表达式}">

         </c:when>
         <c:when test="${表达式}">

         </c:when>
         <c:when test="${表达式}">

         </c:when>
         <c:when test="${表达式}">

         </c:when>
</c:choose>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

     <%
         request.setAttribute("score",80);
     %>

     <c:choose>
         <c:when test="${score < 60}">
             <h2>你是个人渣</h2>
         </c:when>
         <c:when test="${score == 60}">
             <h2>可以,你及格了</h2>
         </c:when>
         <c:when test="${score > 60 && score < 80}">
             <h2>良好了</h2>
         </c:when>
         <c:otherwise>
             <h2>你非常的优秀</h2>
         </c:otherwise>
     </c:choose>
</body>
</html>
迭代标签
<c:forEach var="限域变量名" begin="开始数" end="结束数" step="间隔数" >
       
</c:forEach>
<c:forEach var="限域变量名" items="要被循环的数据">
       
</c:forEach>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %><%--
  Created by IntelliJ IDEA.
  User: ljj
  Date: 2021/12/12
  Time: 下午12:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
   //迭代
   <c:forEach var="i" begin="0" end="10" step="2">
       ${i} &nbsp;
   </c:forEach>

   <%
       List<String> list = new ArrayList<>();
       for (int i = 0; i < 10; i++) {
           list.add("A:" + i);
       }
       pageContext.setAttribute("list",list);
   %>
   //循环
   <c:forEach var="item" items="${list}" >
       ${item} &nbsp;
   </c:forEach>
</body>
</html>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.sf.bean.User" %>
<%@ page import="javax.jws.soap.SOAPBinding" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %><%--
  Created by IntelliJ IDEA.
  User: ljj
  Date: 2021/12/12
  Time: 下午12:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
   <!-- 遍历数组 -->
   <%
       List<User> list = new ArrayList<>();
       User user1 = new User(1,"yanzi1","asd123");
       User user2 = new User(2,"yanzi2","asd123");
       User user3 = new User(3,"yanzi3","123456");
       list.add(user1);
       list.add(user2);
       list.add(user3);
       //将数据设置到作用域
       request.setAttribute("list",list);
   %>
   <!-- 集合判空处理 -->
   <c:if test="${!empty list}">
       <table align="center" width="800" border="1" style="border-collapse: collapse">
           <tr>
               <th>用户编号</th>
               <th>用户名称</th>
               <th>用户密码</th>
               <th>用户操作</th>
           </tr>
           <c:forEach var="user" items="${list}">
               <tr align="center">
                   <td>${user.userId}</td>
                   <td>${user.name}</td>
                   <td>${user.password}</td>
                   <td><button>修改</button></td>
               </tr>
           </c:forEach>
       </table>
   </c:if>

   <!-- 遍历Map -->
   <%
       Map<String,Object> map = new HashMap<>();
       map.put("map1","aaa");
       map.put("map2","bbb");
       map.put("map3","ccc");
       pageContext.setAttribute("map",map);
   %>
   <c:forEach var="item" items="${map}">
       key: ${item.key} &nbsp; value: ${item.value} <br>
   </c:forEach>

</body>
</html>
package com.sf.bean;

public class User {
    private Integer userId;
    private String name;
    private String password;

    public User() {

    }

    public User(Integer userId, String name, String password) {
        this.userId = userId;
        this.name = name;
        this.password = password;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
image.png
格式化动作标签
formatNumber标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <!-- formatNumber -->
    <fmt:formatNumber value="10" type="number" var="num" /> ${num} <br>
    <fmt:formatNumber value="10" type="percent" /> <br>
    <fmt:formatNumber value="10" type="currency" /> <br>
    <!-- 设置时区 -->
    <fmt:setTimeZone value="en_US" /> <br>
    <fmt:formatNumber value="10" type="currency" /> <br>
</body>
</html>
image.png
forrmatDate标签
<%@ page import="java.util.Date" %><%--
  Created by IntelliJ IDEA.
  User: ljj
  Date: 2021/12/12
  Time: 下午3:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%
        request.setAttribute("myDate",new Date());
    %>
    ${myDate} <br>
    <fmt:formatDate value="${myDate}"/> <br>
    <fmt:formatDate value="${myDate}" type="date" /> <br>
    <fmt:formatDate value="${myDate}" type="time" /> <br>
    <fmt:formatDate value="${myDate}" type="both" /> <br>
    <fmt:formatDate value="${myDate}" type="both" dateStyle="FULL"/> <br>
    <fmt:formatDate value="${myDate}" type="both" timeStyle="short"/> <br>
    <fmt:formatDate value="${myDate}" type="both" pattern="yyyy-MM-dd"/> <br>
</body>
</html>
image.png
parseNumber与parseDate标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <fmt:setLocale value="zh_CN"/>
    <fmt:parseNumber value="100" /> <br>
    <fmt:parseNumber value="100" type="number" /> <br>
    <fmt:parseNumber value="100%" type="percent" /> <br>
    <fmt:parseNumber value="¥10.00" type="currency" /> <br>

    <hr>
    <fmt:parseDate value="2010-01-09" type="date" /> <br>
    <fmt:parseDate value="2010-09-23" type="yyyy/MM/dd" /> <br>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读