编程自学指南:java程序设计开发,内置对象详解,九大内置对象的核心作用与生命周期,灵活运用内置对象request/response/session/application

编程自学指南:java程序设计开发,内置对象详解

一、课程信息

学习目标

  1. 理解九大内置对象的核心作用与生命周期
  2. 掌握 request/response/session/application 的关键方法
  3. 能在项目中灵活运用内置对象实现复杂功能
  4. 理解内置对象与其他 Web 技术的协作关系

二、课程导入:生活中的内置工具

🌰 餐厅场景类比

内置对象生活工具作用描述
request点餐单记录顾客需求(参数 / 头信息)
response收银机输出小票(响应内容 / 状态码)
session顾客储物柜存储顾客暂存物品(会话数据)
application餐厅公告栏存储全店信息(如今日特价)

三、内置对象总览

🔍 1. 分类与作用

四、核心内置对象详解

🔥 1. request 对象

✅ 核心方法与案例
// 获取表单参数
String username = request.getParameter("username");

// 获取请求头
String userAgent = request.getHeader("User-Agent");

// 获取请求体(POST)
BufferedReader reader = request.getReader();
StringBuilder body = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    body.append(line);
}
✅ 案例:用户注册
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
        throws IOException {
        
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        // 保存到数据库...
        resp.sendRedirect("/success.jsp");
    }
}

🔥 2. response 对象

✅ 核心方法与案例
// 设置响应内容
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("<h1>Hello, Response!</h1>");

// 重定向
response.sendRedirect("/login.jsp");

// 设置下载文件
response.setHeader("Content-Disposition", "attachment; filename=report.pdf");
✅ 案例:文件下载
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws IOException {
        
        File file = new File("d:/report.pdf");
        Files.copy(file.toPath(), resp.getOutputStream());
    }
}

🔥 3. session 对象

✅ 核心方法与案例
// 存储数据
HttpSession session = request.getSession();
session.setAttribute("user", "john");

// 读取数据
String username = (String) session.getAttribute("user");

// 销毁会话
session.invalidate();
✅ 案例:登录状态保持
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
        throws IOException {
        
        if (isValidUser(req)) {
            req.getSession().setAttribute("user", "admin");
            resp.sendRedirect("/home.jsp");
        }
    }
}

🔥 4. application 对象

✅ 核心方法与案例
// 存储应用级数据
ServletContext context = getServletContext();
context.setAttribute("appName", "在线商城");

// 读取数据
String appName = (String) context.getAttribute("appName");
✅ 案例:统计总访问量
@WebServlet("/counter")
public class CounterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws IOException {
        
        ServletContext context = getServletContext();
        int count = (int) context.getAttribute("count");
        context.setAttribute("count", ++count);
        resp.getWriter().write("总访问量:" + count);
    }
}

五、综合案例:用户登录系统

🔥 1. 登录页(login.jsp)

<form action="/login" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="登录">
</form>

🔥 2. 登录 Servlet

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
        throws IOException {
        
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        
        if ("admin".equals(username) && "123".equals(password)) {
            req.getSession().setAttribute("user", username);
            resp.sendRedirect("/home.jsp");
        } else {
            req.setAttribute("error", "用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}

🔥 3. 主页(home.jsp)

<%
    String user = (String) session.getAttribute("user");
    if (user == null) {
        response.sendRedirect("/login.jsp");
        return;
    }
%>
<h1>欢迎 <%= user %> 登录!</h1>

六、关联知识:内置对象协作

🔗 1. 与 Filter 的协作

@WebFilter("/*")
public class EncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, 
                        FilterChain chain) throws IOException, ServletException {
        
        req.setCharacterEncoding("UTF-8");
        res.setContentType("text/html;charset=UTF-8");
        chain.doFilter(req, res);
    }
}

🔗 2. 与 JSP 标签库的协作

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:out value="${requestScope.error}" />

七、课堂练习

练习 1:购物车功能

任务

  1. 使用 session 对象实现购物车
  2. 支持添加商品、显示购物车列表

练习 2:应用级计数器

任务

  1. 使用 application 对象统计网站总访问量
  2. 在首页显示:您是第 1234 位访客

八、课程总结

知识图谱:

内置对象  
   ↳ request:获取请求数据(参数/头/体)  
   ↳ response:设置响应(内容/状态码/头)  
   ↳ session:会话管理(登录状态/购物车)  
   ↳ application:应用级数据共享(计数器/配置)  
   ↳ out:输出内容(JSP 专用)  

口诀记忆:

“内置对象九大员,request 来 response 填,
session 存会话,application 全局见,
out 输出内容快,config 取配置,
pageContext 是管家,关联对象全靠它!”

九、课后作业

必做 1:在线考试系统

要求

  1. 使用 session 对象记录用户答题状态
  2. 使用 application 对象保存考试题目

必做 2:多语言切换

任务

  1. 使用 session 对象存储用户语言偏好(中文 / 英文)
  2. 根据语言动态加载不同的资源文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zl515035644

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值