JavaWeb开发(五)Servlet-ServletContext

1. ServletContext

1.1. ServletContext简介

1.1.1. ServletContext定义

  ServletContext即Servlet上下文对象,该对象表示当前的web应用环境信息。

1.1.2. 获取ServletContext对象:

  (1)通过ServletConfig的getServletContext()方法可以得到ServletContext对象。
  (2)HttpServlet中直接通过this.getServletContext()获取。

1.1.3. 域对象

  域对象(域对象就是在不同资源之前来共享数据,保存数据,获取数据)ServletContext对象通常称为Context域对象。ServletContext是我们学习的第一个域对象。

1.2. ServletContext获取

   (1)String getInitParameter(String name);根据名称获取初始化参数。   (2)Enumeration getInitParameterNames();获取所有初始化的参数名称。

1.2.1. 配置文件

  在/web/WEB-INF/web.xml配置全局参数。这样会封装到所有Servlet对象中,每个Servlet都可直接获取到它。

  <context-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </context-param>
    <context-param>
        <param-name>encoding1</param-name>
        <param-value>utf-8</param-value>
    </context-param>

在这里插入图片描述

1.2.2. 实现

   新建MyContextServlet通过this.getServletContext()获取上下文对象。

     //方式一:根据名称获取配置参数
        String encoding=this.getServletContext().getInitParameter("encoding");
        System.out.println("getServletContext=="+encoding);
        //方式二:获取初始化所有配置参数
        Enumeration<String> enumeration=this.getServletContext().getInitParameterNames();
        System.out.println("getServletContext=="+enumeration);
package com.zzs.szy;

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(name = "MyContextServlet",urlPatterns = "/myContext")
public class MyContextServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          //方式一:根据名称获取配置参数
        String encoding=this.getServletContext().getInitParameter("encoding");
        System.out.println("getServletContext=="+encoding);
        //方式二:获取初始化所有配置参数
        Enumeration<String> enumeration=this.getServletContext().getInitParameterNames();
        System.out.println("getServletContext=="+enumeration);
    }
}

在这里插入图片描述

1.3. ServletContext在多个Servlet中共享数据

  (1)void setAttribute(String name,Object object);存放数据。
  (2)Object getAttribute(String name); 获取数据。
  (3)void removeAttribute(String name);删除数据。

        //存放数据
        String name="zzs";
        this.getServletContext().setAttribute("name",name);
        //获取数据
        String name = (String) this.getServletContext().getAttribute("name");
        System.out.println("获取数据:" + name);

在这里插入图片描述
在这里插入图片描述

1.4. ServletContext读取web项目的资源文件

1.4.1. db.properties

  新建db.properties文件
在这里插入图片描述

1.4.2. Servlet获取db.properties文件并查询数据

  获取资源文件文件流
  “/db.properties"为放在根部录下
  若文件放在src文件夹下路径则为”/WEB-INF/classes/db.properties"

package com.zzs.szy;
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.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
@WebServlet(name = "MyContextServlet",urlPatterns = "/myContext")
public class MyContextServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //方式一:根据名称获取配置参数
        String encoding=this.getServletContext().getInitParameter("encoding");
        System.out.println("getServletContext=="+encoding);
        //方式二:获取初始化所有配置参数
        Enumeration<String> enumeration=this.getServletContext().getInitParameterNames();
        System.out.println("getServletContext=="+enumeration);
        //存放数据
        String nameStr="zzs";
        this.getServletContext().setAttribute("name",nameStr);
        //获取资源文件文件流
        //"/db.properties"为放在根部录下
        //若文件放在src文件夹下路径则为"/WEB-INF/classes/db.properties"
        InputStream resourceAsStream = this.getServletContext()
                .getResourceAsStream("/db.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        String url = properties.getProperty("ur1");
        String name = properties.getProperty("name");
        String password = properties.getProperty("password");
        System.out.println("url:"+url);
        System.out.println("password:"+password);
        System.out.println("name:"+name);
    }
}

在这里插入图片描述

1.5. 请求转发

1.5.1. Servlet之间可以实现跳转

  Servlet之间可以实现跳转,从一个Servlet跳转到另个-Servlet,利用Servlet的跳转技术酊以很方便的把一块业务模块分开,比如使用一个Servlet接收用户提交数据,使用另个一个Servlet读取数据库,最后跳转到另一个Servlet把处理结果展示出来。这也就是MVC模式(modle,view,controller)
  MVC:用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。

1.5.2. 转发Forward简介

  在Serv1et中如果当前的web资源不想处理请求时,可以通过forward方将当前的请求传递给其它的Web资源处理,这种方式称为请求转发。
在这里插入图片描述
  (1)请求转发的相关方法:
  RequestDispatcher对象,可以通过request.getRequestDispatcher()方法获取调用这个对象的foward方法就可以实现请求转发。
  (2)转发过程中携带数据:
  request本身也是一个域对象,request可以携带数据传递给其他web资源
  setAttribute方法:
  getAttribute方法;
  removeAttribute方法:
  getAttributeNames方法:

1.5.3. 案例-登录错误时显示错误界面

  (1)新建LoginServlet

package com.zzs.szy;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = "zzs";
        String userPwd = "123456";
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        if (!name.equals(userName)) {
            //账户不存在
            request.setAttribute("errorMessage", "账户不存在");
            request.getRequestDispatcher("/loginError.jsp")
                    .forward(request, response);
        } else if (!password.equals(userPwd)) {
            //密码错误
            request.setAttribute("errorMessage", "密码错误");
            request.getRequestDispatcher("/loginError.jsp")
                    .forward(request, response);
        } else {
//                  response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
//                  response.setHeader("Location","https://www.baidu.com/");
            HttpSession session = request.getSession();
            Cookie cookie = new Cookie("JSESSION", session.getId());
            cookie.setMaxAge(60 * 60 * 24);
            response.addCookie(cookie);
            response.sendRedirect("/hello/home.html");
        }

    }
}

  (2)新建login.html,home.html,loginError.jsp
在这里插入图片描述
  (3)浏览器输入地址展示
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值