11.22

1. request:处理客户端请求(获取表单参数、请求头、路径等)

  • 示例:获取表单提交的用户名
    jsp
    <%
    // 解决请求参数中文乱码(需在获取参数前调用)
    request.setCharacterEncoding("UTF-8");
    String username = request.getParameter("username"); // 获取单个参数
    String[] hobbies = request.getParameterValues("hobby"); // 获取多个同名参数(如复选框)
    %>
     
    2. response:处理服务器响应(重定向、设置响应头、Cookie等)
  • 示例:重定向到首页(注意:重定向前不能有页面输出)
    jsp
    <%
    // 3秒后重定向到index.jsp
    response.setHeader("Refresh", "3;url=index.jsp");
    // 直接重定向(立即跳转)
    // response.sendRedirect("index.jsp");
    %>
     
    3. session:存储用户会话数据(登录状态、用户信息,默认有效期30分钟)
  • 示例:记录用户登录状态
    jsp
    <%
    // 登录成功后,把用户名存入session
    session.setAttribute("username", "张三");
    // 获取session中的值
    String uname = (String) session.getAttribute("username");
    // 销毁session(退出登录)
    // session.invalidate();
    %>
     
    4. application:全局对象(整个Web应用共享,存储全局数据,如网站访问量)
  • 示例:统计网站总访问次数
    jsp
    <%
    Integer totalCount = (Integer) application.getAttribute("totalCount");
    if (totalCount == null) {
    totalCount = 1;
    } else {
    totalCount++;
    }
    application.setAttribute("totalCount", totalCount);
    %>

网站总访问次数:<%= totalCount %>

posted @ 2025-11-22 22:05  喜欢写轻小说的日央  阅读(4)  评论(0)    收藏  举报