【超全必看】JavaWeb中Cookie、Session、JSP的使用详解(附示例代码)

本文深入讲解JavaWeb中的会话管理,包括Cookie、Session和JSP的使用。介绍了Cookie的基本操作、设置与读取,讨论了Cookie的存储、生存时间和共享问题。同时,探讨了Session的工作原理、生命周期及其与Cookie的区别。还涵盖了JSP的脚本、内置对象和使用,以及EL表达式和JSTL标签库的应用。最后,通过实例展示了如何使用这些技术来实现验证码验证功能。
摘要由CSDN通过智能技术生成

会话

会话
一次会话中包含多次请求和响应。
当浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止,会话结束。
功能
在一次会话的范围内的多次请求间,共享数据
方式
客户端会话技术:Cookie
服务器端会话技术:Session


Cookie

概念:客户端会话技术,将数据保存到客户端

快速入门

使用步骤
1.创建Cookie对象,绑定数据
new Cookie(String name, String value)
2.发送Cookie对象
response.addCookie(Cookie cookie)
3.获取Cookie,拿到数据
request.getCookies()

设置Cookie:

@WebServlet("/setCookie")
public class SetCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("msg", "hello");
        response.addCookie(cookie);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

获取Cookie:

@WebServlet("/getCookie")
public class GetCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie:cookies){
                System.out.println(cookie.getName()+"->"+cookie.getValue());
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

先访问setCookie,再访问getCookie,控制台输出:
在这里插入图片描述
我有个疑惑,cookie和attribute的区别,在setCookie的servlet里添加了attribute,但是在getCookie的servlet里获取的结果是null,因此attribute只能是在服务器转发时有效。

使用细节

一次可不可以发送多个cookie?

可以,可以创建多个Cookie对象,使用response调用多次addCookie方法发送cookie即可。
设置Cookie:

@WebServlet("/setCookie")
public class SetCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie1 = new Cookie("msg1", "hello1");
        response.addCookie(cookie1);
        Cookie cookie2 = new Cookie("msg2", "hello2");
        response.addCookie(cookie2);
        Cookie cookie3 = new Cookie("msg3", "hello3");
        response.addCookie(cookie3);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

获取Cookie代码和上面的相同
控制台输出:

msg->hello
JSESSIONID->0AFC0015C44A18D6DF3641273CBC53E4
msg1->hello1
msg2->hello2
msg3->hello3
Idea-fe3516c6->7bffffd5-2036-45b3-9613-35358f80bd96
Webstorm-cca88c1f->3ab543cf-2131-4475-9a5b-d0cd0e5d216b

cookie在浏览器中保存多长时间?

1 默认情况下,当浏览器关闭后,Cookie数据被销毁
2.持久化存储:setMaxAge(int seconds)

  1. 正数:将Cookie数据写到硬盘的文件中。持久化存储。并指定cookie存活时间,时间到后,cookie文件自动失效
  2. 负数:默认值
  3. 零:删除cookie信息
@WebServlet("/setCookie")
public class SetCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie1 = new Cookie("msg1", "hello1");
        cookie1.setMaxAge(0);//删除cookie
        cookie1.setMaxAge(-1);//默认情况
        cookie1.setMaxAge(1000);//1000秒后删除
        response.addCookie(cookie1);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
cookie能不能存中文?
  • 在tomcat 8 之前 cookie中不能直接存储中文数据。
    需要将中文数据转码—一般采用URL编码(%E3)
  • 在tomcat 8 之后,cookie支持中文数据。特殊字符还是不支持,建议使用URL编码存储,URL解码解析
cookie共享问题?
  • 假设在一个tomcat服务器中,部署了多个web项目,那么在这些web项目中cookie能不能共享?
    默认情况下cookie不能共享
    setPath(String path)设置cookie的获取范围。默认情况下,设置当前的虚拟目录
    如果要共享,则可以将path设置为/
    在这里插入图片描述

在这里插入图片描述

  • 不同的tomcat服务器间cookie共享问题?
    setDomain(String path)如果设置一级域名相同,那么多个服务器之间cookie可以共享
    setDomain(".baidu.com")那么tieba.baidu.com和news.baidu.com中cookie可以共享
Cookie的特点和作用
  • cookie存储数据在客户端浏览器
  • 浏览器对于单个cookie 的大小有限制(4kb) 以及 对同一个域名下的总cookie数量也有限制(20个)
  • 作用:
    1. cookie一般用于存出少量的不太敏感的数据
    2. 在不登录的情况下,完成服务器对客户端的身份识别

案例:记住上一次访问时间

  • 需求:
    1. 访问一个Servlet,如果是第一次访问,则提示:您好,欢迎您首次访问。
    2. 如果不是第一次访问,则提示:欢迎回来,您上次访问时间为:显示时间字符串
  • 分析:
    • 可以采用Cookie来完成
    • 在服务器中的Servlet判断是否有一个名为lastTime的cookie
      有:不是第一次访问,响应数据,写回Cookie
      没有:是第一次访问,响应数据:您好,欢迎您首次访问,写回Cookie
@WebServlet("/GetTime")
public class GetTime extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("text/html;charset=utf-8");//设置响应编码
        boolean firstVisit=true;
        //获取Cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            if(cookieName.equals("time")){
                String newDate=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date());//获取当前时间
                firstVisit=false;//不是第一次访问
                String oldDate = cookie.getValue();//获取上次访问时间
                oldDate=URLDecoder.decode(oldDate,"utf-8");//解码上次访问时间
                response.getWriter().write("欢迎回来,上次您访问时间: "+oldDate);
                newDate=URLEncoder.encode(newDate,"utf-8");//编码当前时间
                cookie.setValue(newDate);//更新cookie值
                cookie.setMaxAge(1000);
                response.addCookie(cookie);
                break;
            }
        }
        if(firstVisit){
            String newDate=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date());
            response.getWriter().write("欢迎第一次登陆");
            newDate = URLEncoder.encode(newDate, "utf-8");//编码当前时间
            Cookie cookie = new Cookie("time", newDate);
            cookie.setMaxAge(1000);
            response.addCookie(cookie);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

首次访问时:
在这里插入图片描述
刷新后:
在这里插入图片描述


JSP

概念

Java Server Pages: java服务器端页面
可以理解为:一个特殊的页面,其中既可以指定定义html标签,又可以定义java代码
用于简化书写

原理

JSP本质上就是一个Servlet

JSP的脚本

JSP定义Java代码的方式
<% 代码 %>定义的java代码,在service方法中。service方法中可以定义什么,该脚本中就可以定义什么。
<%! 代码 %>定义的java代码,在jsp转换后的java类的成员位置。
<%= 代码 %>定义的java代码,会输出到页面上。输出语句中可以定义什么,该脚本中就可以定义什么。

内置对象1

在jsp页面中不需要获取和创建,可以直接使用的对象
jsp一共有9个内置对象。
先说3个:

  • request
  • response
  • out:字符输出流对象。可以将数据输出到页面上。和response.getWriter()类似
    response.getWriter()out的区别:
    在tomcat服务器真正给客户端做出响应之前,会先找response缓冲区数据,再找out缓冲区数据。
    response.getWriter().write()数据输出永远在out.write()之前
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <%
      out.write("这是out输出的");  
    %>
    <%
      response.getWriter().write("这是response输出的");
    %>
  </body>
</html>

结果:
在这里插入图片描述

使用jsp改造cookie时间案例

<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <%
      boolean firstVisit=true;
      //获取Cookie
      Cookie[] cookies = request.getCookies();
      for (Cookie cookie : cookies) {
        String cookieName = cookie.getName();
        if(cookieName.equals("time")) {
          String newDate = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date());//获取当前时间
          firstVisit = false;//不是第一次访问
          String oldDate = cookie.getValue();//获取上次访问时间
          oldDate = URLDecoder.decode(oldDate, "utf-8");//解码上次访问时间
    %>

    <h1>欢迎回来,上次您访问时间: <%= oldDate%></h1>
    <%
          newDate= URLEncoder.encode(newDate,"utf-8");//编码当前时间
          cookie.setValue(newDate);//更新cookie值
          cookie.setMaxAge(1000);
          response.addCookie(cookie);
          break;
        }
      }
      if(firstVisit) {
        String newDate = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date());
       %>
    <h1>欢迎第一次登陆</h1>
    <%
        newDate = URLEncoder.encode(newDate, "utf-8");//编码当前时间
        Cookie cookie = new Cookie("time", newDate);
        cookie.setMaxAge(1000);
        response.addCookie(cookie);
      }
    %>
  </body>
</html>

结果:
在这里插入图片描述

指令

作用
用于配置JSP页面,导入资源文件
格式
<%@ 指令名称 属性名1=属性值1 属性名2=属性值2 ... %>
分类

  • page: 配置JSP页面
    • contentType:

      设置响应体的mime类型以及字符集
      设置当前jsp页面的编码(只能是高级的IDE才能生效,如果使用低级工具,则需要设置pageEncoding属性设置当前页面的字符集)

    • import:导包
    • errorPage:当前页面发生异常后,会自动跳转到指定的错误页面
    • isErrorPage:标识当前也是是否是错误页面。

      true:是,可以使用内置对象exception
      false:否。默认值。不可以使用内置对象exception

  • include : 页面包含的。导入页面的资源文件
  • taglib : 导入资源
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    prefix 前缀,自定义的,一般用c
    需要导入相关jar包
    在这里插入图片描述

注释

html注释:
<!-- -->只能注释html代码片段,在网页源代码中可以显示
jsp注释:推荐使用
<%-- --%>可以注释所有,在网页源代码中不会显示
在这里插入图片描述
打开网页查看源代码:
在这里插入图片描述

内置对象2

在jsp页面中不需要创建,直接使用的对象

变量名真实类型作用
pageContextPageContext当前页面共享数据,还可以获取其他八个内置对象
requestHttpServletRequest一次请求访问的多个资源(转发)
sessionHttpSession一次会话的多个请求间
applicationServletContext所有用户间共享数据
responseHttpServletResponse响应对象
pageObject当前页面(Servlet)的对象 this
outJspWriter输出对象,数据输出到页面上
configServletConfigServlet的配置对象
exceptionThrowable异常对象

Session

概念

服务器端会话技术,在一次会话的多次请求间共享数据,将数据保存在服务器端的对象中。

快速入门

1.获取HttpSession对象:
request.getSession()
2.使用HttpSession对象:
Object getAttribute(String name)
void setAttribute(String name, Object value)
void removeAttribute(String name)

设置session

@WebServlet("/SetSession")
public class SetSession extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.setAttribute("msg","this is the message");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

获取session

@WebServlet("/GetSession")
public class GetSession extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String msg = (String) session.getAttribute("msg");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(msg);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

结果:
在这里插入图片描述

在这里插入图片描述

原理

Session的实现是依赖于Cookie的。
在这里插入图片描述
在这里插入图片描述
服务器是通过cookie中的JESSIONID判断session是否是同一个的
在这里插入图片描述

细节

当客户端关闭后,服务器不关闭,两次获取session是否为同一个?

默认情况下。不是。
如果需要相同,则可以创建Cookie,键为JSESSIONID,设置最大存活时间,让cookie持久化保存。

@WebServlet("/SetSession")
public class SetSession extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.setAttribute("msg","this is the message");
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60*60);
        response.addCookie(cookie);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

客户端不关闭,服务器关闭后,两次获取的session是同一个吗?

不是同一个,但是要确保数据不丢失。tomcat自动完成以下工作
session的钝化:

在服务器正常关闭之前,将session对象系列化到硬盘上

session的活化:

在服务器启动后,将session文件转化为内存中的session对象即可。

客户端不关闭,服务器关闭后,两次获取的session是同一个吗?

不是同一个,但是要确保数据不丢失。tomcat自动完成以下工作

  • session的钝化: 在服务器正常关闭之前,将session对象系列化到硬盘上
  • session的活化: 在服务器启动后,将session文件转化为内存中的session对象即可。
session什么时候被销毁?

服务器关闭
session对象调用invalidate() 。
session默认失效时间 30分钟

         选择性配置修改	
		<session-config>
        <session-timeout>30</session-timeout>
	    </session-config>
session的特点

session用于存储一次会话的多次请求的数据,存在服务器端
session可以存储任意类型,任意大小的数据
session与Cookie的区别:

  • session存储数据在服务器端,Cookie在客户端
  • session没有数据大小限制,Cookie有
  • session数据安全,Cookie相对于不安全

综合案例:验证码

  • 访问带有验证码的登录页面login.jsp
    用户输入用户名,密码以及验证码。
  • 如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误
    如果验证码输入有误,跳转登录页面,提示:验证码错误
    如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您

用户User类,数据库表和UserDao操作类见上一篇文章:request和response对象详解

登录页login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script>
        window.onload=function () {
            var image=document.getElementById("check");
            var change=document.getElementById("change");
            change.onclick=function () {
                var date=new Date().getTime();
                image.src="/root/CheckServlet"+date;
            }
        }
    </script>
</head>
<body>
    <form action="/root/LoginServlet" method="post">
        <table>
            <tr>
                <td>姓名</td>
                <td><input name="username" type="text"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input name="password" type="password"></td>
            </tr>
            <tr>
                <td>验证码:</td>
                <td><input name="checkcode" type="text" placeholder="验证码:"></td>
            </tr>
            <tr>
                <td><img id="check" src="/root/CheckServlet"></td>
                <td><a id="change" href="">看不清?点击切换</a></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="登陆"></td>
            </tr>
        </table>
    </form>
    <div><%= request.getAttribute("error1")==null?"":request.getAttribute("error1")%></div>
    <div><%= request.getAttribute("error2")==null?"":request.getAttribute("error2")%></div>
</body>
</html>

LoginServlet

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集编码
        request.setCharacterEncoding("utf-8");
        String checkcode = request.getParameter("checkcode");
        HttpSession session = request.getSession();
        String code = (String)session.getAttribute("checkcode");
        session.removeAttribute("checkcode");
        if(checkcode!=null&&checkcode.equals(code)){
            User user = new User();
            Map<String, String[]> parameterMap = request.getParameterMap();
            try {
                //使用beanutils封装表单提交的数据
                BeanUtils.populate(user,parameterMap);
                //查询该用户在数据库是否存在
                User loginuser = new UserDao().login(user);
                if(loginuser!=null){
                    session.setAttribute("user",loginuser.getUsername());
                    response.sendRedirect(request.getContextPath()+"/success.jsp");
                }else {
                    request.setAttribute("error1","用户名或密码错误,请重新登陆");
                    request.getRequestDispatcher("/login.jsp").forward(request,response);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            request.setAttribute("error2","验证码错误,请重新登陆");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

登陆成功页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1><%= request.getSession().getAttribute("user")%>,欢迎您</h1>
</body>
</html>

验证码

@WebServlet("/CheckServlet")
public class CheckServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取图片对象
        int width=100;//宽
        int height=50;//高
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //设置背景色
        Graphics graphics = image.getGraphics();//得到画笔
        graphics.setColor(Color.PINK);//设置颜色
        graphics.fillRect(0,0,width-1,height-1);//填充颜色
        //画边
        graphics.setColor(Color.blue);
        graphics.drawRect(0,0,width-1,height-1);
        //加验证码
        Random random = new Random();
        String s="qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0123456789";
        StringBuilder sb=new StringBuilder();
        for (int i = 1; i <=4 ; i++) {
            int index = random.nextInt(s.length());
            char c = s.charAt(index);
            sb.append(c);
            graphics.drawString(c+"",width/5*i,height/2);
        }
        //加干扰线
        graphics.setColor(Color.green);
        for (int i = 1; i <=4 ; i++) {
            int x1=random.nextInt(width);
            int x2=random.nextInt(width);
            int y1=random.nextInt(height);
            int y2=random.nextInt(height);
            graphics.drawLine(x1,y1,x2,y2);
        }
        //输出图片
        ImageIO.write(image,"jpg",response.getOutputStream());
        //存到session
        HttpSession session = request.getSession();
        session.setAttribute("checkcode",sb.toString());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

EL表达式

概念

Expression Language 表达式语言

作用

替换和简化jsp页面中java代码的编写

语法

${表达式}

注意:
jsp默认支持el表达式的,如果要忽略el表达式

  1. 设置jsp中page指令中:isELIgnored="true"忽略当前jsp页面中所有的el表达式
  2. \${表达式} :忽略当前这个EL表达式

使用

  • 运算:

    运算符:

    • 算数运算符: + - * /(div) %(mod)
    • 比较运算符: > < >= <= == !=
    • 逻辑运算符: &&(and) ||(or) !(not)
    • 空运算符: empty 功能:用于判断字符串、集合、数组对象是否为null或者长度是否为0 ${empty list}:判断字符串、集合、数组对象是否为null或者长度为0 ${not empty
      str}:表示判断字符串、集合、数组对象是否不为null 并且 长度>0
  • 获取值

    • EL表达式只能从域对象中获取值
    • 语法:
      • ${域名称.键名}| ${域名称.对应get(键名)方法}从指定域中获取指定键的值
        域名称:
        1. pageScope --> pageContext
        2. requestScope --> request
        3. sessionScope --> session
        4. applicationScope --> application(ServletContext)
      • ${键名}表示依次从最小的域中查找是否有该键对应的值,直到找到为止。
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <%
            pageContext.setAttribute("张若昀","范闲");
            request.setAttribute("李纯","司理理");
            session.setAttribute("辛芷蕾","海棠朵朵");
            application.setAttribute("李沁","林婉儿");
        %>
        <h3>EL表达式获取值</h3>
        pageContext:${pageContext.getAttribute("张若昀")}<br>
        request:${requestScope.get("李纯")}<br>
        session:${sessionScope.get("辛芷蕾")}<br>
        application:${applicationScope.get("李沁")}
    </body>
    </html>
    
    

    访问jsp页面:
    在这里插入图片描述

  • 获取对象
    ${域名称.键名.属性名} 本质上会去调用对象的getter方法
    jsp代码:

    	<%
            User user=new User();
            user.setUsername("范闲");
            request.setAttribute("user",user);
        %>
        方式一:获取user的name值:${user.username}<br>
        方式二:获取user的name值:${requestScope.user.username}<br>
        方式三:获取user的name值:${requestScope.get("user").username}<br>
    

    访问jsp:
    在这里插入图片描述

  • 获取 List集合:
    ${域名称.键名[索引]}

    jsp代码:

    	<%
            ArrayList list=new ArrayList();
            list.add("aaa");
            list.add(1);
            request.setAttribute("list",list);
        %>
        获取list的值:${list}<br>
        获取list的值1:${list[0]}<br>
        获取list的值1:${list[1]}
    

    访问jsp:
    在这里插入图片描述

  • 获取 Map集合:
    ${域名称.键名.key名称}
    ${域名称.键名["key名称"]}

    jsp代码:

        <%
            HashMap<String,String> map=new HashMap<>();
            map.put("name","james");
            map.put("age","35");
            request.setAttribute("map",map);
        %>
        获取map的值:${map}<br>
        获取map的值1:${map.name}<br>
        获取map的值1:${map.get("name")}<br>
        获取map的值2:${map["age"]}
    

    访问jsp:
    在这里插入图片描述

  • 隐式对象:
    el表达式中有11个隐式对象
    pageContext:获取jsp其他八个内置对象
    ${pageContext.request.contextPath} :动态获取虚拟目录

JSTL

概念

JavaServer Pages Tag Library JSP标准标签库
是由Apache组织提供的开源的免费的jsp标签

作用

用于简化和替换jsp页面上的java代码

使用步骤

  1. 导入jstl相关jar包
  2. 引入标签库: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  3. 使用标签

if 标签

  • test 必需属性,接受boolean表达式
  • 如果表达式为true,则显示if标签体内容,如果为false,则不显示标签体内容
  • 一般情况下,test属性值会结合el表达式一起使用
  • c:if标签没有else情况,想要else情况,则可以再定义一个c:if标签

choose

相当于java代码的switch语句

  1. 使用choose标签声明 相当于switch声明
  2. 使用when标签做判断 相当于case
  3. 使用otherwise标签做其他情况的声明 相当于default
<%
        request.setAttribute("number",3);
    %>
    <c:choose>
        <c:when test="${number==1}">1</c:when>
        <c:when test="${number==2}">2</c:when>
        <c:when test="${number==3}">3</c:when>
        <c:when test="${number==4}">4</c:when>
        <c:when test="${number==5}">5</c:when>
        <c:otherwise>周末</c:otherwise>
    </c:choose>

在这里插入图片描述

foreach

var 循环变量
begin 起始值
end结束值
step 步长
用法一 遍历容器:

	<%
        ArrayList<Integer> list=new ArrayList<>();
        list.add(10);
        list.add(22);
        list.add(35);
        request.setAttribute("list",list);
    %>
    <c:if test="${not empty list}">
        <c:forEach items="${list}" var="item" varStatus="i">
            索引:${i.index}<br>
            遍历次数:${i.count}<br>:${item}<br>
        </c:forEach>
    </c:if>

结果:
在这里插入图片描述
用法二 for循环:

	<c:forEach begin="0" end="5" step="1" var="x" varStatus="i">
        索引:${i.index} -> 遍历次数:${i.count} ->:${x}<br>
    </c:forEach>

结果:
在这里插入图片描述

EL、JSTL综合案例

在request域中有一个存有User对象的List集合。需要使用jstl+el将list集合数据展示到jsp页面的表格table中,奇数行和偶数行显示不同颜色

<%@ page import="RequestAndResponse.loginDemo.User" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <%
        List<User> list=new ArrayList<>();
        list.add(new User(1,"范闲","fanxian"));
        list.add(new User(2,"司理理","silili"));
        list.add(new User(3,"王启年","wangqinian"));
        request.setAttribute("list",list);
    %>
    <table border="1" width="500" align="center">
        <tr>
            <th>id</th>
            <th>姓名</th>
            <th>密码</th>
        </tr>
        <c:forEach items="${list}" var="user">
            <c:if test="${user.id%2==0}">
                <tr bgcolor="#5f9ea0">
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.password}</td>
                </tr>
            </c:if>
            <c:if test="${user.id%2!=0}">
                <tr bgcolor="#f0ffff">
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.password}</td>
                </tr>
            </c:if>
        </c:forEach>
    </table>
</body>
</html>

结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值