ServletContext

Servlet

ServletContext

概述

ServletContext 指的是 Servlet 上下文。服务器会为每一个项目创建一个对象,这个对象就是 ServletContext 对象。这个对象全局唯一,而且项目内部的所有 Servlet 都共享这个对象,都能够使用其内部存储的数据。所以也叫全局应用程序共享对象

ServletContext 接口定义了 Servlet 用于与其他 Servlet 容器通信的一组方法,例如,用于获取文件的MIME类型、分派请求或写入日志文件

特点

1、是一个域对象(域对象是服务器在内存上创建的存储空间,用于在不同动态资源(Servlet)之间传递与共享数据)

2、可以读取全局配置参数

3、可以搜索当前项目目录下面的资源文件

常用方法
// 获取 ServletContext 对象【重点】
ServletContext getServletContext();

// 通过ServletConfig对象获取对应的ServletContext对象
getServletConfig().getServletContext();
	
// 通过Request请求对象获取对应都是ServletContext对象
req.getServletContext();

// 通过HttpSession对象获取ServletContext对象
req.getSession().getServletContext();

// 【重点】作为数据传递的容器,设置属性及其属性值
void setAttribute(String var1, Object var2);

// 【重点】获取具有给定名称的 servlet 容器属性,如果没有该名称的属性,则返回 null
public Object getAttribute(String name);
	
// 获取一个枚举,其中包含此 servlet 上下文中可用的属性名称。使用带有属性名称的 getAttribute 方法来获取属性的值。
public Enumeration getAttributeNames();

// 删除指定的属性以及对应的属性值
void removeAttribute(String var1);
	
// 获取包含给定虚拟路径的真实路径的字符串	
public String getRealPath(String path);
	
// 	获取Tomcat服务器版本信息
public String getServerInfo();

案例代码一

/**
 * 测试 ServletContext
 */
@WebServlet("/TestServletContext")
public class TestServletContext1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // 获取上下文对象
        ServletContext servletContext = request.getServletContext();

        // 获取当前的项目的实际目录
        String realPath = servletContext.getRealPath("/");
        System.out.println("realPath:" + realPath);

        // 获取运行 servlet 的 servlet 容器的名称和版本
        String serverInfo = servletContext.getServerInfo();
        System.out.println("serverInfo:" + serverInfo);

        // 获取当前项目的根目录和jsp页面中用于和html页面联系的路由
        String contextPath = servletContext.getContextPath();
        System.out.println("contextPath:" + contextPath);

        // 设置请求参数
        servletContext.setAttribute("ServletContext", "上下文对象");
        servletContext.setAttribute("Person", new Person("易烊千玺", 20));
    }
}

案例代码二

/**
 * 测试 ServletContext2
 */
@WebServlet("/TestServletContext2")
public class TestServletContext2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // 获取上下文对象
        ServletContext servletContext = request.getServletContext();

        // 返回具有给定名称的servlet容器属性,如果没有该名称的属性,则返回null
        Object context = servletContext.getAttribute("ServletContext");
        Person person = (Person) servletContext.getAttribute("Person");

        System.out.println("ServletContext对应的值:" + context);
        System.out.println("Person对应的值:" + person);

        // 删除对应的属性和属性值
        servletContext.removeAttribute("Person");
        Person person1 = (Person) servletContext.getAttribute("Person");
        System.out.println("删除后的Person对象:" + person1);
    }
}

HttpServletRequest

通过定义一个 ServletRequest 对象来向 Servlet 提供客户端请求信息

  • Servlet 容器创建一个 ServletRequest 对象,并将其作为参数传递给 Servlet 的 service 方法
  • ServletRequest 对象提供数据,包括参数名和值、属性和输入流。扩展ServletRequest 的接口可以提供附加协议特定的数据(例如,HttpServletRequest 提供HTTP数据)
// 获取请求参数的类型,get或者post等
String getMethod();

// 【重点】获取不包含参数的URL,返回值类型是StringBuffer,便于对其进行操作
StringBuffer getRequestURL();

// 获取请求URL中的路径部分
String getRequestURI();

// 获取完整的请求参数对应的字符串
String getQueryString();

// 【重点】获取请求参数对应的map集合
Map getParameterMap();

// 获取访问用户的主机
String getRemoteHost();

// 如果访问用户通过了认证,则返回用户名,否则返回null
String getRemoteUser();

// 获取访问用户的最后一个代理IP地址
String getRemoteAddr();

// 获取访问用户的访问源端口号
int getRemotePort();

// 获取请求参数的枚举类型表示
Enumeration<String> getParameterNames();

// 通过参数名获取字符串数组类型的参数值
String[] getParameterValues(String var1);

// 获取对应请求头的值
String getHeader(String var1);

案例代码

/**
 * 测试请求对象
 */
@WebServlet("/request")
public class TestRequestServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数的类型
        String method = req.getMethod();
        System.out.println(method);

        // 获取请求URL
        StringBuffer requestURL = req.getRequestURL();
        System.out.println(requestURL);

        // 获取请求URL中的路径部分
        String requestURI = req.getRequestURI();
        System.out.println(requestURI);

        // 获取请求路径中的资源名
        System.out.println(requestURI.substring(requestURI.lastIndexOf('/')));

        // 获取完整的请求参数对应的字符串
        String queryString = req.getQueryString();
        System.out.println(queryString);

        // 获取请求参数对应的map集合
        Map<String, String[]> map = req.getParameterMap();

        // 遍历map中的数据
        Set<Map.Entry<String, String[]>> entries = map.entrySet();
        for (Map.Entry<String, String[]> entry: entries) {
            System.out.println(entry.getKey() + ":" + Arrays.toString(entry.getValue()));
        }

        // 获取访问用户的主机
        String remoteHost = req.getRemoteHost();
        System.out.println(remoteHost);

        // 如果访问用户通过了认证,则返回用户名,否则返回null
        String remoteUser = req.getRemoteUser();
        System.out.println(remoteUser);

        // 获取访问用户的最后一个代理IP地址
        String remoteAddr = req.getRemoteAddr();
        System.out.println(remoteAddr);

        // 获取访问用户的访问源端口号
        int remotePort = req.getRemotePort();
        System.out.println(remotePort);

        // 获取请求参数的枚举类型表示
        Enumeration<String> names = req.getParameterNames();

        // 枚举类型的遍历
        while (names.hasMoreElements()) {
            // 获取每一个参数名
            String name = names.nextElement();
            System.out.println(name);

            // 获取参数名对应的值
            String value = req.getParameter(name);
            System.out.println(value);

            // 获取字符串数组形式的参数名对应的值
            String[] values = req.getParameterValues(name);

            // 参数值遍历
            for (String paramValue: values) {
                System.out.println(paramValue);
            }
        }

        // 获取对应请求头的值
        String header = req.getHeader("Accept-Language");
        System.out.println(header);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

HttpServletResponse

用户发送请求到服务器,服务器会对应当前用户的请求针对性地提供响应,对应的就是HttpServletResponse 对象

服务器可以通过 response 对象发送响应告知浏览器,浏览器可以根据服务器响应数据进行解析操作。

// 设置响应内容编码集
void setCharacterEncoding(String charset);

// 获取字符输出流对象
PrintWriter getWriter();

// 设置具有给定名称和值的响应头。如果响应头已经设置,则新值将覆盖前一个值。
void setHeader(String var1, String var2);

// 设置响应状态码
void setStatus(int var1);

案例代码

/**
 * 测试响应对象中的方法
 */
@WebServlet("/response")
public class TestResponseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容编码集为UTF-8
        resp.setContentType("text/html; charset=UTF-8");

        // 设置具有给定名称和值的响应头。如果响应头已经设置,则新值将覆盖前一个值。
        resp.setHeader("stuId", "123456");

        // 设置响应状态码
        resp.setStatus(404);

        resp.getWriter().append("<h1>国家有力量,人民有希望</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

通过 BeanUtils 操作实体类

BeanUtils 是一种方便我们对 JavaBean 进行操作的工具类,是Apache组织下的产品。

使用前需要导入两个 jar 包:

commons-beanutils-1.8.3.jar
commons-logging-1.1.3.jar

常用方法

// 设置Bean对象中名称为name的属性值赋值为value.	
public void setProperty(Object bean, String name, Object value)

// 取得bean对象中名为name的属性的值
public String getProperty(Object bean, String name)

// 把orig对象copy到dest对象中.
public void copyProperties (Object dest, Object orig)

// 把Bean的属性值放入到一个Map里面
public Map describe(Object bean)

// 把map里面的值放入bean中
public void populate (Object bean, Map map)

实体类

/**
 * 实体类
 */
public class Student {
    private int id;
    private String name;
    private int age;
    private String gender;
    private String info;
    
	Constructor setter getter toString()
}

案例代码一

@WebServlet("/addStudent")
public class AddStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码集
        req.setCharacterEncoding("UTF8");

        // 获取存储请求参数的map
        Map<String, String[]> map = req.getParameterMap();

        Student student = new Student();

        try {
            // 将map中的数据存储到学生对象中
            BeanUtils.populate(student, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        System.out.println(student);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

案例代码二

需要使用的jar包:

# BeanUtils相关
commons-beanutils-1.8.3.jar
commons-logging-1.1.3.jar

# 连接数据库 
mysql-connector-java-5.1.47.jar

# DbUtils
commons-dbutils-1.7.jar

# C3P0数据库连接池(或者Druid连接池)
c3p0-0.9.2.jar
mchange-commons-java-0.2.19.jar

【注意】直接复制粘贴到 WEB-INF 目录下的 lib 目录中

需要使用的配置文件

c3p0-config.xml

【注意】此配置文件放在 src 目录下,并修改数据库名以及密码

前端添加页面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>增加</title>
</head>
<body>
<form method="post" action="addStudent">
    <table border="1px" align="center">
        <caption><h3>添加学生</h3></caption>
        <tr>
            <td>姓名</td>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <td>年龄</td>
            <td><input type="text" name="age"></td>
        </tr>
        <tr>
            <td>性别</td>
            <td>
                <input type="radio" name="gender" value="">
                <input type="radio" name="gender" value="">
            </td>
        </tr>
        <tr>
            <td>信息</td>
            <td><input type="text" name="info"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="reset" value="重置">
                <input type="submit" value="提交">
            </td>

        </tr>
    </table>
</form>
</body>
</html>

添加成功页面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>添加成功页</title>
</head>
<body>
    <h1 align="center" style="color: chartreuse">添加成功</h1>
    <h1 align="center" style="color: crimson">
        <a href="queryStudent">查询全部</a>
    </h1>
</body>
</html>

添加失败页面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>添加失败页</title>
</head>
<body>
    <h1 align="center" style="color: crimson">添加失败</h1>
    <h1 align="center" style="color: chartreuse">
        <a href="addStudent">重新添加</a>
    </h1>
</body>
</html>

添加操作

/**
 * 添加学生到数据库中
 */
@WebServlet("/addStudent")
public class AddStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码集
        req.setCharacterEncoding("UTF8");

        // 获取存储请求参数的map
        Map<String, String[]> map = req.getParameterMap();

        // 声明实体类对象
        Student student = new Student();

        try {
            // 将map中的数据存储到学生对象中
            BeanUtils.populate(student, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        System.out.println(student);

        // 获取DbUtils核心类对象
        QueryRunner queryRunner = new QueryRunner();

        // 获取通过c3p0获取数据库连接
        Connection connection = JdbcUtilsOnC3P0.getConnection();

        // 准备SQL语句
        String sql = "insert into student(name, age, gender, info) values(?, ?, ?, ?)";

        // 准备参数
        Object[] params = {student.getName(), student.getAge(), student.getGender(), student.getInfo()};

        // 提取受影响的行数
        int affectedRows = 0;

        try {
            // 执行SQL语句并获取受影响的行数
            affectedRows = queryRunner.update(connection, sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 判断受影响的行数是否大于0
        if (affectedRows > 0) {
            // 重定向至添加成功页
            resp.sendRedirect("success.html");
        } else {
            // 重定向至添加失败页
            resp.sendRedirect("fail.html");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

查询操作

/**
 * 查询所有学生
 */
@WebServlet("/queryStudent")
public class QueryStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取DbUtils核心类对象
        QueryRunner queryRunner = new QueryRunner();

        // 获取通过c3p0获取数据库连接
        Connection connection = JdbcUtilsOnC3P0.getConnection();

        // 准备SQL语句
        String sql = "select * from student";

        List<Student> list = null;

        try {
            // 执行SQL语句并获取包含学生对象的List集合
            list = queryRunner.query(connection, sql, new BeanListHandler<Student>(Student.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 设置响应内容字符集
        resp.setContentType("text/html; charset=UTF-8");

        // 准备HTML前端页面
        String html = "<table width='600' border='1px' align='center'>" +
                "<caption><h3>所有学生</h3></caption>" +
                "<tr>" +
                "<th>id</th><th>姓名</th><th>年龄</th><th>性别</th><th>信息</th><th>操作</th>" +
                "</tr>";
        
        // 判断如果List集合不为空,向HTML中填充数据
        if (list != null) {
            for (Student student : list) {
                html += "<tr>";
                html += "<td>" + student.getId() + "</td>";
                html += "<td>" + student.getName() + "</td>";
                html += "<td>" + student.getAge() + "</td>";
                html += "<td>" + student.getGender() + "</td>";
                html += "<td>" + student.getInfo() + "</td>";
                html += "<td>";
                html += "<a href='updateStudent?id=" + student.getId() + "'>修改</a>&nbsp;";
                //<a href='updateStudent?id=1'></a>
                html += "<a href='deleteStudent?id=" + student.getId() + "'>删除</a>";
                html += "</td>";
                html += "</tr>";
            }
        }
        html += "<tr align='center'><td colspan='7'><a href='add.html'>添加学生</a></td></tr>";
        html += "</table>";

        resp.getWriter().append(html);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值